diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8431418fd0e340d684e3d42e3b05b09e7a820710
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7a13c9de345e8e46e19a3bffc5d5715b9517679
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__init__.py
@@ -0,0 +1,43 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""The agentplatform module."""
+
+import importlib
+
+from .client import Client
+
+_evals = None
+
+
+def __getattr__(name): # type: ignore[no-untyped-def]
+ if name == "evals":
+ global _evals
+ if _evals is None:
+ try:
+ _evals = importlib.import_module(".evals", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'evals' module requires additional dependencies. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[evaluation]"
+ ) from e
+ return _evals
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
+
+
+__all__ = [
+ "Client",
+ "evals",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd12512e2d6ea2c826f7e634afd8616f19603e1c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_agent_engines_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_agent_engines_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a54f4867f36f8d4d9692679c8ef9eee40271bf3f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_agent_engines_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_bigquery_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_bigquery_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cae62e59f34113a1ed02e9b34c610f554da70e25
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_bigquery_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_datasets_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_datasets_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f66ab3e77d389258d6b72498d215a73af173f8b2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_datasets_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_constant.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_constant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3f3d6ac430deec04e26e480011f38fbdd352acd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_constant.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_data_converters.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_data_converters.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f22698ec7b1a9e690cab8708157529111fbc50d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_data_converters.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_handlers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02c4cff7e8b4f65aea7dd6e9fa58ac4691bdf5d4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_handlers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_loaders.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_loaders.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65a5b9e1bb166ebcee168bb274a81e77c8f8822e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_loaders.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c1704dd195bb1f5cc55beece378d4aea9eeab93
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_gcs_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_gcs_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9aed4329c8978cbef1ae35e81ecfa7f05ce7451d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_gcs_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_logging_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_logging_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56f5abc4547577232486d59388e2c15534c8d2ee
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_logging_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_observability_data_converter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_observability_data_converter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a40bfaccb4e922ed543cfd7be9da760e71b557ab
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_observability_data_converter.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_management_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_management_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e1f418e4ba75ed95980e1dc79abb41eb96f71cb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_management_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_optimizer_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_optimizer_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a98e99af482e4c2a23d425ca6f7fc31710d6eb94
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_optimizer_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_skills_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_skills_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cea981cc72f7e21a69a14ea368fd61c0f31ccee6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_skills_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_transformers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_transformers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8778dc9d5d44bc8a10d14db40ca758bb405fdc60
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_transformers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_task_events.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_task_events.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e13f69fcd1cfb5ac9e10cd5f4a53aa88cf5178f2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_task_events.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_tasks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_tasks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b35f16a9b352d00fd0d9fa2c825bdf8274649747
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_tasks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65a44dd84ef32a698c98b9356e93e982602c7135
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/datasets.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/datasets.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a643e6992bd1f7ae23cde10ac03a84119fa7c0a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/datasets.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3c5c278f5ba586ef31828b50745890f783f7f04
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live_agent_engines.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live_agent_engines.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e578dd3148243a3c1297a6efdaf426551e3714f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live_agent_engines.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/memory_revisions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/memory_revisions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6de7885cd5e9823a294ad969fa8c0f9a2aee284e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/memory_revisions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/prompt_optimizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/prompt_optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68fc68ee78ac463506dddb161d0173c809e53998
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/prompt_optimizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtime_revisions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtime_revisions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f96cc1c99e0290d3ff4733541633285947a6b8d0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtime_revisions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtimes.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtimes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b91e2bb6d408fec0cd26d8b9b33561545d0a93d8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtimes.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_snapshots.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_snapshots.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50721e9e82610b1b1d35c71a0ecada1998bbc87e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_snapshots.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_templates.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_templates.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0bac4ec4e5230b713b475f35bc2de07030ddd6c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_templates.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandboxes.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandboxes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85d4351c272ab015242f1c4f99b429da9e25fb9b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandboxes.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/session_events.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/session_events.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c80d98bb32110a31267a141e396b8e1d983a48d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/session_events.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sessions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sessions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ede78bcec1d2ae58b13ff2ea0d75ebdb12e427ae
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sessions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skill_revisions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skill_revisions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..117f02891a257bac80381fe659b39a65ea63f9cd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skill_revisions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skills.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skills.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3db72e5d8e8b374a88a7f58dfd3e38277462f5ca
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skills.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_agent_engines_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_agent_engines_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b269ba0833875458ca53c42209b33983c0c30bcf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_agent_engines_utils.py
@@ -0,0 +1,1996 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Utility functions for agent engines."""
+
+import abc
+import asyncio
+import base64
+from importlib import metadata as importlib_metadata
+import inspect
+import io
+import json
+import logging
+import os
+import re
+import sys
+import tarfile
+import time
+import types
+import typing
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Coroutine,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Protocol,
+ Sequence,
+ Set,
+ TypedDict,
+ Union,
+)
+
+import httpx
+
+import proto
+
+from google.api_core import exceptions
+from google.genai import types as google_genai_types
+from google.protobuf import struct_pb2
+from google.protobuf import json_format
+
+from . import types as genai_types
+
+
+if sys.version_info >= (3, 10):
+ from typing import TypeAlias
+else:
+ from typing_extensions import TypeAlias
+
+
+try:
+ _BUILTIN_MODULE_NAMES: Sequence[str] = sys.builtin_module_names
+except AttributeError:
+ _BUILTIN_MODULE_NAMES: Sequence[str] = [] # type: ignore[no-redef]
+
+try:
+ _PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = (
+ importlib_metadata.packages_distributions()
+ )
+except AttributeError:
+ _PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = {} # type: ignore[no-redef]
+
+try:
+ # sys.stdlib_module_names is available from Python 3.10 onwards.
+ _STDLIB_MODULE_NAMES: frozenset[str] = sys.stdlib_module_names
+except AttributeError:
+ _STDLIB_MODULE_NAMES: frozenset[str] = frozenset() # type: ignore[no-redef]
+
+
+if typing.TYPE_CHECKING:
+ from google.cloud import storage # type: ignore[attr-defined]
+
+ _StorageBucket: TypeAlias = storage.Bucket
+else:
+ try:
+ from google.cloud import storage # type: ignore[attr-defined]
+
+ _StorageBucket: type[Any] = storage.Bucket
+ except (ImportError, AttributeError):
+ _StorageBucket: type[Any] = Any # type: ignore[no-redef]
+
+
+if typing.TYPE_CHECKING:
+ import packaging
+
+ _SpecifierSet = packaging.specifiers.SpecifierSet
+else:
+ try:
+ import packaging
+
+ _SpecifierSet: type[Any] = packaging.specifiers.SpecifierSet
+ except (ImportError, AttributeError):
+ _SpecifierSet: type[Any] = Any # type: ignore[no-redef]
+
+
+try:
+ from a2a.types import (
+ AgentCard,
+ TransportProtocol,
+ Message,
+ TaskIdParams,
+ TaskQueryParams,
+ )
+ from a2a.client import ClientConfig, ClientFactory
+
+ AgentCard = AgentCard
+ TransportProtocol = TransportProtocol
+ Message = Message
+ ClientConfig = ClientConfig
+ ClientFactory = ClientFactory
+ TaskIdParams = TaskIdParams
+ TaskQueryParams = TaskQueryParams
+except (ImportError, AttributeError):
+ AgentCard = None
+ TransportProtocol = None
+ Message = None
+ ClientConfig = None
+ ClientFactory = None
+ TaskIdParams = None
+ TaskQueryParams = None
+
+_ACTIONS_KEY = "actions"
+_ACTION_APPEND = "append"
+_AGENT_FRAMEWORK_ATTR = "agent_framework"
+_ASYNC_API_MODE = "async"
+_ASYNC_STREAM_API_MODE = "async_stream"
+_BIDI_STREAM_API_MODE = "bidi_stream"
+_BASE_MODULES = set(_BUILTIN_MODULE_NAMES).union(_STDLIB_MODULE_NAMES)
+_BLOB_FILENAME = "agent_engine.pkl"
+_DEFAULT_AGENT_FRAMEWORK = "custom"
+_SUPPORTED_AGENT_FRAMEWORKS = frozenset(
+ [
+ "google-adk",
+ "langchain",
+ "langgraph",
+ "ag2",
+ "llama-index",
+ "custom",
+ "a2a",
+ ]
+)
+_DEFAULT_ASYNC_METHOD_NAME = "async_query"
+_DEFAULT_ASYNC_METHOD_RETURN_TYPE = "Coroutine[Any]"
+_DEFAULT_ASYNC_STREAM_METHOD_NAME = "async_stream_query"
+_DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE = "AsyncIterable[Any]"
+_DEFAULT_GCS_DIR_NAME = "agent_engine"
+_DEFAULT_METHOD_DOCSTRING_TEMPLATE = """
+ Runs the Agent Engine to serve the user request.
+ This will be based on the `.{method_name}(...)` of the python object that
+ was passed in when creating the Agent Engine. The method will invoke the
+ `{default_method_name}` API client of the python object.
+ Args:
+ **kwargs:
+ Optional. The arguments of the `.{method_name}(...)` method.
+ Returns:
+ {return_type}: The response from serving the user request.
+"""
+_DEFAULT_METHOD_NAME = "query"
+_DEFAULT_METHOD_RETURN_TYPE = "dict[str, Any]"
+_DEFAULT_STREAM_METHOD_RETURN_TYPE = "Iterable[Any]"
+_DEFAULT_REQUIRED_PACKAGES = frozenset(["cloudpickle", "pydantic"])
+_DEFAULT_STREAM_METHOD_NAME = "stream_query"
+_DEFAULT_BIDI_STREAM_METHOD_NAME = "bidi_stream_query"
+_EXTRA_PACKAGES_FILE = "dependencies.tar.gz"
+_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE = (
+ "Failed to register API methods. Please follow the guide to "
+ "register the API methods: "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#custom-methods. "
+ "Error: {%s}"
+)
+_INSTALLATION_SUBDIR = "installation_scripts"
+_METHOD_NAME_KEY_IN_SCHEMA = "name"
+_MODE_KEY_IN_SCHEMA = "api_mode"
+_REQUIREMENTS_FILE = "requirements.txt"
+_STANDARD_API_MODE = ""
+_STREAM_API_MODE = "stream"
+_A2A_EXTENSION_MODE = "a2a_extension"
+_A2A_AGENT_CARD = "a2a_agent_card"
+_WARNINGS_KEY = "warnings"
+_WARNING_MISSING = "missing"
+_WARNING_INCOMPATIBLE = "incompatible"
+
+_DEFAULT_METHOD_NAME_MAP = {
+ _STANDARD_API_MODE: _DEFAULT_METHOD_NAME,
+ _ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_NAME,
+ _STREAM_API_MODE: _DEFAULT_STREAM_METHOD_NAME,
+ _ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_NAME,
+}
+_DEFAULT_METHOD_RETURN_TYPE_MAP = {
+ _STANDARD_API_MODE: _DEFAULT_METHOD_RETURN_TYPE,
+ _ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_RETURN_TYPE,
+ _STREAM_API_MODE: _DEFAULT_STREAM_METHOD_RETURN_TYPE,
+ _ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE,
+}
+
+
+logger = logging.getLogger("agentplatform_genai.agentengines")
+
+
+@typing.runtime_checkable
+class Queryable(Protocol):
+ """Protocol for Agent Engines that can be queried."""
+
+ @abc.abstractmethod
+ def query(self, **kwargs): # type: ignore[no-untyped-def]
+ """Runs the Agent Engine to serve the user query."""
+
+
+@typing.runtime_checkable
+class AsyncQueryable(Protocol):
+ """Protocol for Agent Engines that can be queried asynchronously."""
+
+ @abc.abstractmethod
+ def async_query(self, **kwargs): # type: ignore[no-untyped-def]
+ """Runs the Agent Engine to serve the user query asynchronously."""
+
+
+@typing.runtime_checkable
+class AsyncStreamQueryable(Protocol):
+ """Protocol for Agent Engines that can stream responses asynchronously."""
+
+ @abc.abstractmethod
+ async def async_stream_query(self, **kwargs) -> AsyncIterator[Any]: # type: ignore[no-untyped-def]
+ """Asynchronously stream responses to serve the user query."""
+
+
+@typing.runtime_checkable
+class StreamQueryable(Protocol):
+ """Protocol for Agent Engines that can stream responses."""
+
+ @abc.abstractmethod
+ def stream_query(self, **kwargs) -> Iterator[Any]: # type: ignore[no-untyped-def]
+ """Stream responses to serve the user query."""
+
+
+@typing.runtime_checkable
+class BidiStreamQueryable(Protocol):
+ """Protocol for Agent Engines that can stream requests and responses."""
+
+ @abc.abstractmethod
+ async def bidi_stream_query(
+ self, input_queue: asyncio.Queue[Any]
+ ) -> AsyncIterator[Any]:
+ """Stream requests and responses to serve the user queries."""
+
+
+@typing.runtime_checkable
+class Cloneable(Protocol):
+ """Protocol for Agent Engines that can be cloned."""
+
+ @abc.abstractmethod
+ def clone(self) -> Any:
+ """Return a clone of the object."""
+
+
+@typing.runtime_checkable
+class OperationRegistrable(Protocol):
+ """Protocol for agents that have registered operations."""
+
+ @abc.abstractmethod
+ def register_operations(self, **kwargs: Any) -> dict[str, list[str]]:
+ """Register the user provided operations (modes and methods)."""
+ pass
+
+
+if typing.TYPE_CHECKING:
+ from google.adk.agents import BaseAgent
+
+ ADKAgent: TypeAlias = BaseAgent
+else:
+ try:
+ from google.adk.agents import BaseAgent
+
+ ADKAgent: Optional[TypeAlias] = BaseAgent
+ except (ImportError, AttributeError):
+ ADKAgent = None # type: ignore[no-redef]
+
+_AgentEngineInterface = Union[
+ ADKAgent,
+ AsyncQueryable,
+ AsyncStreamQueryable,
+ OperationRegistrable,
+ Queryable,
+ StreamQueryable,
+ BidiStreamQueryable,
+]
+
+
+class _ModuleAgentAttributes(TypedDict, total=False):
+ module_name: str
+ agent_name: str
+ register_operations: Dict[str, list[str]]
+ sys_paths: Optional[Sequence[str]]
+ agent: _AgentEngineInterface
+
+
+class ModuleAgent(Cloneable, OperationRegistrable):
+ """Agent that is defined by a module and an agent name.
+
+ This agent is instantiated by importing a module and instantiating an agent
+ from that module. It also allows to register operations that are defined in
+ the agent.
+ """
+
+ def __init__(
+ self,
+ *,
+ module_name: str,
+ agent_name: str,
+ register_operations: Dict[str, list[str]],
+ sys_paths: Optional[Sequence[str]] = None,
+ ):
+ """Initializes a module-based agent.
+
+ Args:
+ module_name (str):
+ Required. The name of the module to import.
+ agent_name (str):
+ Required. The name of the agent in the module to instantiate.
+ register_operations (Dict[str, list[str]]):
+ Required. A dictionary of API modes to a list of method names.
+ sys_paths (Sequence[str]):
+ Optional. The system paths to search for the module. It should
+ be relative to the directory where the code will be running.
+ I.e. it should correspond to the directory being passed to
+ `extra_packages=...` in the create method. It will be appended
+ to the system path in the sequence being specified here, and
+ only be appended if it is not already in the system path.
+ """
+ self._tmpl_attrs: _ModuleAgentAttributes = {
+ "module_name": module_name,
+ "agent_name": agent_name,
+ "register_operations": register_operations,
+ "sys_paths": sys_paths,
+ }
+
+ def clone(self) -> "ModuleAgent":
+ """Return a clone of the agent."""
+ return ModuleAgent(
+ module_name=self._tmpl_attrs.get("module_name"),
+ agent_name=self._tmpl_attrs.get("agent_name"),
+ register_operations=self._tmpl_attrs.get("register_operations"),
+ sys_paths=self._tmpl_attrs.get("sys_paths"),
+ )
+
+ def register_operations(self, **kwargs: Any) -> dict[str, list[str]]:
+ reg_operations = self._tmpl_attrs.get("register_operations")
+ if reg_operations is None:
+ raise ValueError("Register operations is not set.")
+ return reg_operations
+
+ def set_up(self) -> None:
+ """Sets up the agent for execution of queries at runtime.
+
+ It runs the code to import the agent from the module, and registers the
+ operations of the agent.
+ """
+ sys_paths = self._tmpl_attrs.get("sys_paths")
+ if isinstance(sys_paths, Sequence):
+ import sys
+
+ for sys_path in sys_paths:
+ abs_path = os.path.abspath(sys_path)
+ if abs_path not in sys.path:
+ sys.path.append(abs_path)
+
+ import importlib
+
+ module = importlib.import_module(self._tmpl_attrs.get("module_name"))
+ try:
+ importlib.reload(module)
+ except Exception as e:
+ logger.warning(
+ f"Failed to reload module {self._tmpl_attrs.get('module_name')}: {e}"
+ )
+ agent_name = self._tmpl_attrs.get("agent_name")
+ try:
+ agent = getattr(module, agent_name)
+ except AttributeError as e:
+ raise AttributeError(
+ f"Agent {agent_name} not found in module "
+ f"{self._tmpl_attrs.get('module_name')}"
+ ) from e
+ self._tmpl_attrs["agent"] = agent
+ if hasattr(agent, "set_up"):
+ agent.set_up()
+ for operations in self.register_operations().values():
+ for operation in operations:
+ op = _wrap_agent_operation(agent=agent, operation=operation)
+ setattr(self, operation, types.MethodType(op, self))
+
+
+class _RequirementsValidationActions(TypedDict):
+ append: Set[str]
+
+
+class _RequirementsValidationWarnings(TypedDict):
+ missing: Set[str]
+ incompatible: Set[str]
+
+
+class _RequirementsValidationResult(TypedDict):
+ warnings: _RequirementsValidationWarnings
+ actions: _RequirementsValidationActions
+
+
+AgentEngineOperationUnion = Union[
+ genai_types.AgentEngineOperation,
+ genai_types.AgentEngineMemoryOperation,
+ genai_types.AgentEngineGenerateMemoriesOperation,
+]
+
+
+class GetOperationFunction(Protocol):
+ def __call__(
+ self, *, operation_name: str, **kwargs: Any
+ ) -> AgentEngineOperationUnion:
+ pass
+
+
+class GetAsyncOperationFunction(Protocol):
+ async def __call__(
+ self, *, operation_name: str, **kwargs: Any
+ ) -> AgentEngineOperationUnion:
+ pass
+
+
+def _get_reasoning_engine_id(operation_name: str = "", resource_name: str = "") -> str:
+ """Returns reasoning engine ID from operation name or resource name."""
+ if not resource_name and not operation_name:
+ raise ValueError("Resource name or operation name cannot be empty.")
+
+ if resource_name:
+ match = re.match(
+ r"^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)$",
+ resource_name,
+ )
+ if match:
+ return match.group(1)
+ else:
+ raise ValueError(
+ "Failed to parse reasoning engine ID from resource name: "
+ f"`{resource_name}`"
+ )
+
+ if not operation_name:
+ raise ValueError("Operation name cannot be empty.")
+
+ match = re.match(
+ r"^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)/operations/[^/]+$",
+ operation_name,
+ )
+ if match:
+ return match.group(1)
+ raise ValueError(
+ "Failed to parse reasoning engine ID from operation name: "
+ f"`{operation_name}`"
+ )
+
+
+async def _await_async_operation(
+ *,
+ operation_name: str,
+ get_operation_fn: GetAsyncOperationFunction,
+ poll_interval_seconds: float = 10,
+) -> Any:
+ """Waits for the operation for creating an agent engine to complete.
+
+ Args:
+ operation_name (str):
+ Required. The name of the operation for creating the Agent Engine.
+ poll_interval_seconds (float):
+ The number of seconds to wait between each poll.
+ get_operation_fn (Callable[[str], Awaitable[Any]]):
+ Optional. The async function to use for getting the operation. If not
+ provided, `self._get_agent_operation` will be used.
+
+ Returns:
+ The operation that has completed (i.e. `operation.done==True`).
+ """
+ operation = await get_operation_fn(operation_name=operation_name)
+ while not operation.done:
+ await asyncio.sleep(poll_interval_seconds)
+ operation = await get_operation_fn(operation_name=operation.name)
+
+ return operation
+
+
+def _await_operation(
+ *,
+ operation_name: str,
+ get_operation_fn: GetOperationFunction,
+ poll_interval_seconds: float = 10,
+) -> Any:
+ """Waits for the operation for creating an agent engine to complete.
+
+ Args:
+ operation_name (str):
+ Required. The name of the operation for creating the Agent Engine.
+ poll_interval_seconds (float):
+ The number of seconds to wait between each poll.
+ get_operation_fn (Callable[[str], Any]):
+ Optional. The function to use for getting the operation. If not
+ provided, `self._get_agent_operation` will be used.
+
+ Returns:
+ The operation that has completed (i.e. `operation.done==True`).
+ """
+ operation = get_operation_fn(operation_name=operation_name)
+ while not operation.done:
+ time.sleep(poll_interval_seconds)
+ operation = get_operation_fn(operation_name=operation.name)
+
+ return operation
+
+
+def _compare_requirements(
+ *,
+ requirements: Mapping[str, str],
+ constraints: Union[Sequence[str], Mapping[str, Optional["_SpecifierSet"]]],
+ required_packages: Optional[Iterator[str]] = None,
+) -> _RequirementsValidationResult:
+ """Compares the requirements with the constraints.
+
+ Args:
+ requirements (Mapping[str, str]):
+ Required. The packages (and their versions) to compare with the constraints.
+ This is assumed to be the result of `scan_requirements`.
+ constraints (Union[Sequence[str], Mapping[str, SpecifierSet]]):
+ Required. The package constraints to compare against. This is assumed
+ to be the result of `parse_constraints`.
+ required_packages (Iterator[str]):
+ Optional. The set of packages that are required to be in the
+ constraints. It defaults to the set of packages that are required
+ for deployment on Agent Engine.
+
+ Returns:
+ dict[str, dict[str, Any]]: The comparison result as a dictionary containing:
+ * warnings:
+ * missing: The set of packages that are not in the constraints.
+ * incompatible: The set of packages that are in the constraints
+ but have versions that are not in the constraint specifier.
+ * actions:
+ * append: The set of packages that are not in the constraints
+ but should be appended to the constraints.
+ """
+ packaging_version = _import_packaging_version_or_raise()
+ if required_packages is None:
+ required_packages = _DEFAULT_REQUIRED_PACKAGES # type: ignore[assignment]
+ result = _RequirementsValidationResult(
+ warnings=_RequirementsValidationWarnings(missing=set(), incompatible=set()),
+ actions=_RequirementsValidationActions(append=set()),
+ )
+ if isinstance(constraints, list):
+ constraints = _parse_constraints(constraints=constraints)
+ for package, package_version in requirements.items():
+ if package not in constraints:
+ result[_WARNINGS_KEY][_WARNING_MISSING].add(package) # type: ignore[literal-required]
+ if package in required_packages: # type: ignore[operator]
+ result[_ACTIONS_KEY][_ACTION_APPEND].add( # type: ignore[literal-required]
+ f"{package}=={package_version}"
+ )
+ continue
+ if package_version:
+ package_specifier = constraints[package] # type: ignore[call-overload]
+ if not package_specifier:
+ continue
+ if packaging_version.Version(package_version) not in package_specifier:
+ result[_WARNINGS_KEY][_WARNING_INCOMPATIBLE].add( # type: ignore[literal-required]
+ f"{package}=={package_version} (required: {str(package_specifier)})"
+ )
+ return result
+
+
+def _generate_class_methods_spec_or_raise(
+ *,
+ agent: _AgentEngineInterface,
+ operations: Dict[str, List[str]],
+) -> List[proto.Message]:
+ """Generates a ReasoningEngineSpec based on the registered operations.
+
+ Args:
+ agent: The AgentEngine instance.
+ operations: A dictionary of API modes and method names.
+
+ Returns:
+ A list of ReasoningEngineSpec.ClassMethod messages.
+
+ Raises:
+ ValueError: If a method defined in `register_operations` is not found on
+ the AgentEngine.
+ """
+ if isinstance(agent, ModuleAgent):
+ # We do a dry-run of setting up the agent engine to have the operations
+ # needed for registration.
+ agent: ModuleAgent = agent.clone() # type: ignore[no-redef]
+ try:
+ agent.set_up()
+ except Exception as e:
+ raise ValueError(f"Failed to set up agent {agent}: {e}") from e
+ class_methods_spec = []
+ for mode, method_names in operations.items():
+ for method_name in method_names:
+ if not hasattr(agent, method_name):
+ raise ValueError(
+ f"Method `{method_name}` defined in `register_operations`"
+ " not found on agent."
+ )
+
+ method = getattr(agent, method_name)
+ try:
+ schema_dict = _generate_schema(method, schema_name=method_name)
+ except Exception as e:
+ logger.warning(f"failed to generate schema for {method_name}: {e}")
+ continue
+
+ class_method = _to_proto(schema_dict)
+ class_method[_MODE_KEY_IN_SCHEMA] = mode
+ if hasattr(agent, "agent_card"):
+ class_method[_A2A_AGENT_CARD] = json_format.MessageToJson(
+ getattr(agent, "agent_card")
+ )
+ class_methods_spec.append(class_method)
+
+ return class_methods_spec
+
+
+def _class_methods_to_class_methods_spec(
+ class_methods: List[dict[str, Any]],
+) -> List[proto.Message]:
+ """Converts a list of class methods to a list of ReasoningEngineSpec.ClassMethod messages."""
+ return [_to_proto(class_method) for class_method in class_methods]
+
+
+def _is_pydantic_serializable(param: inspect.Parameter) -> bool:
+ """Checks if the parameter is pydantic serializable."""
+
+ if param.annotation == inspect.Parameter.empty:
+ return True
+
+ if "ForwardRef" in repr(param.annotation):
+ return True
+
+ if isinstance(param.annotation, str):
+ return False
+
+ pydantic = _import_pydantic_or_raise()
+ try:
+ pydantic.TypeAdapter(param.annotation)
+ return True
+ except Exception:
+ return False
+
+
+def _generate_schema(
+ f: Callable[..., Any],
+ *,
+ schema_name: Optional[str] = None,
+ descriptions: Mapping[str, str] = {},
+ required: Sequence[str] = [],
+) -> Dict[str, Any]:
+ """Generates the OpenAPI Schema for a callable object.
+
+ Only positional and keyword arguments of the function `f` will be supported
+ in the OpenAPI Schema that is generated. I.e. `*args` and `**kwargs` will
+ not be present in the OpenAPI schema returned from this function. For those
+ cases, you can either include it in the docstring for `f`, or modify the
+ OpenAPI schema returned from this function to include additional arguments.
+
+ Args:
+ f (Callable):
+ Required. The function to generate an OpenAPI Schema for.
+ schema_name (str):
+ Optional. The name for the OpenAPI schema. If unspecified, the name
+ of the Callable will be used.
+ descriptions (Mapping[str, str]):
+ Optional. A `{name: description}` mapping for annotating input
+ arguments of the function with user-provided descriptions. It
+ defaults to an empty dictionary (i.e. there will not be any
+ description for any of the inputs).
+ required (Sequence[str]):
+ Optional. For the user to specify the set of required arguments in
+ function calls to `f`. If specified, it will be automatically
+ inferred from `f`.
+
+ Returns:
+ dict[str, Any]: The OpenAPI Schema for the function `f` in JSON format.
+ """
+ pydantic = _import_pydantic_or_raise()
+ defaults = dict(inspect.signature(f).parameters)
+ fields_dict = {
+ name: (
+ # 1. We infer the argument type here: use Any rather than None so
+ # it will not try to auto-infer the type based on the default value.
+ (
+ param.annotation
+ if param.annotation != inspect.Parameter.empty
+ and "ForwardRef" not in repr(param.annotation)
+ else Any
+ ),
+ pydantic.Field(
+ # 2. We do not support default values for now.
+ # default=(
+ # param.default if param.default != inspect.Parameter.empty
+ # else None
+ # ),
+ # 3. We support user-provided descriptions.
+ description=descriptions.get(name, None),
+ ),
+ )
+ for name, param in defaults.items()
+ # We do not support *args or **kwargs
+ if param.kind
+ in (
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ inspect.Parameter.KEYWORD_ONLY,
+ inspect.Parameter.POSITIONAL_ONLY,
+ )
+ # For a bidi endpoint, it requires an asyncio.Queue as the input, but
+ # it is not JSON serializable. We hence exclude it from the schema.
+ and param.annotation != asyncio.Queue and _is_pydantic_serializable(param)
+ }
+ parameters = pydantic.create_model(f.__name__, **fields_dict).schema()
+ # Postprocessing
+ # 4. Suppress unnecessary title generation:
+ # * https://github.com/pydantic/pydantic/issues/1051
+ # * http://cl/586221780
+ parameters.pop("title", "")
+ for name, function_arg in parameters.get("properties", {}).items():
+ function_arg.pop("title", "")
+ annotation = defaults[name].annotation
+ # 5. Nullable fields:
+ # * https://github.com/pydantic/pydantic/issues/1270
+ # * https://stackoverflow.com/a/58841311
+ # * https://github.com/pydantic/pydantic/discussions/4872
+ if typing.get_origin(annotation) is Union and type(None) in typing.get_args(
+ annotation
+ ):
+ # for "typing.Optional" arguments, function_arg might be a
+ # dictionary like
+ #
+ # {'anyOf': [{'type': 'integer'}, {'type': 'null'}]
+ for schema in function_arg.pop("anyOf", []):
+ schema_type = schema.get("type")
+ if schema_type and schema_type != "null":
+ function_arg["type"] = schema_type
+ break
+ function_arg["nullable"] = True
+ # 6. Annotate required fields.
+ if required:
+ # We use the user-provided "required" fields if specified.
+ parameters["required"] = required
+ else:
+ # Otherwise we infer it from the function signature.
+ parameters["required"] = [
+ k
+ for k in defaults
+ if (
+ defaults[k].default == inspect.Parameter.empty
+ and defaults[k].kind
+ in (
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ inspect.Parameter.KEYWORD_ONLY,
+ inspect.Parameter.POSITIONAL_ONLY,
+ )
+ )
+ ]
+ schema = dict(name=f.__name__, description=f.__doc__, parameters=parameters)
+ if schema_name:
+ schema["name"] = schema_name
+ return schema
+
+
+def _get_agent_framework(
+ *,
+ agent_framework: Optional[str],
+ agent: _AgentEngineInterface,
+) -> Union[str, Any]:
+ """Gets the agent framework to use.
+
+ The agent framework is determined in the following order of priority:
+ 1. The `agent_framework` passed to this function.
+ 2. The `agent_framework` attribute on the `agent` object.
+ 3. The default framework, "custom".
+
+ Args:
+ agent_framework (str):
+ The agent framework provided by the user.
+ agent (_AgentEngineInterface):
+ The agent engine instance.
+
+ Returns:
+ str: The name of the agent framework to use.
+ """
+ if agent_framework is not None and agent_framework in _SUPPORTED_AGENT_FRAMEWORKS:
+ logger.info(f"Using agent framework: {agent_framework}")
+ return agent_framework
+ if hasattr(agent, _AGENT_FRAMEWORK_ATTR):
+ agent_framework_attr = getattr(agent, _AGENT_FRAMEWORK_ATTR)
+ if (
+ agent_framework_attr is not None
+ and isinstance(agent_framework_attr, str)
+ and agent_framework_attr in _SUPPORTED_AGENT_FRAMEWORKS
+ ):
+ logger.info(f"Using agent framework: {agent_framework_attr}")
+ return agent_framework_attr
+ logger.info(
+ f"The provided agent framework {agent_framework} is not supported."
+ f" Defaulting to {_DEFAULT_AGENT_FRAMEWORK}."
+ )
+ return _DEFAULT_AGENT_FRAMEWORK
+
+
+def _get_gcs_bucket(
+ *,
+ project: str,
+ location: str,
+ staging_bucket: str,
+ credentials: Optional[Any] = None,
+) -> _StorageBucket:
+ """Gets or creates the GCS bucket."""
+ storage = _import_cloud_storage_or_raise()
+ storage_client = storage.Client(project=project, credentials=credentials)
+ staging_bucket = staging_bucket.replace("gs://", "")
+ try:
+ gcs_bucket = storage_client.get_bucket(staging_bucket)
+ logger.info(f"Using bucket {staging_bucket}")
+ except exceptions.NotFound:
+ new_bucket = storage_client.bucket(staging_bucket)
+ gcs_bucket = storage_client.create_bucket(new_bucket, location=location)
+ logger.info(f"Creating bucket {staging_bucket} in {location=}")
+ return gcs_bucket
+
+
+def _get_registered_operations(
+ *,
+ agent: _AgentEngineInterface,
+) -> dict[str, list[str]]:
+ """Retrieves registered operations for a AgentEngine."""
+ if isinstance(agent, OperationRegistrable):
+ return agent.register_operations()
+
+ operations = {}
+ if isinstance(agent, Queryable):
+ operations[_STANDARD_API_MODE] = [_DEFAULT_METHOD_NAME]
+ if isinstance(agent, AsyncQueryable):
+ operations[_ASYNC_API_MODE] = [_DEFAULT_ASYNC_METHOD_NAME]
+ if isinstance(agent, StreamQueryable):
+ operations[_STREAM_API_MODE] = [_DEFAULT_STREAM_METHOD_NAME]
+ if isinstance(agent, AsyncStreamQueryable):
+ operations[_ASYNC_STREAM_API_MODE] = [_DEFAULT_ASYNC_STREAM_METHOD_NAME]
+ if isinstance(agent, BidiStreamQueryable):
+ operations[_BIDI_STREAM_API_MODE] = [_DEFAULT_BIDI_STREAM_METHOD_NAME]
+ return operations
+
+
+def _import_cloudpickle_or_raise() -> types.ModuleType:
+ """Tries to import the cloudpickle module."""
+ try:
+ import cloudpickle # noqa:F401
+ except ImportError as e:
+ raise ImportError(
+ "cloudpickle is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return cloudpickle # type: ignore[no-any-return]
+
+
+def _import_cloud_storage_or_raise() -> types.ModuleType:
+ """Tries to import the Cloud Storage module."""
+ try:
+ from google.cloud import storage # type: ignore[attr-defined]
+ except ImportError as e:
+ raise ImportError(
+ "Cloud Storage is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return storage # type: ignore[no-any-return]
+
+
+def _import_packaging_requirements_or_raise() -> types.ModuleType:
+ """Tries to import the packaging.requirements module."""
+ try:
+ from packaging import requirements
+ except ImportError as e:
+ raise ImportError(
+ "packaging.requirements is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return requirements
+
+
+def _import_packaging_version_or_raise() -> types.ModuleType:
+ """Tries to import the packaging.requirements module."""
+ try:
+ from packaging import version
+ except ImportError as e:
+ raise ImportError(
+ "packaging.version is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return version
+
+
+def _import_pydantic_or_raise() -> types.ModuleType:
+ """Tries to import the pydantic module."""
+ try:
+ import pydantic
+
+ _ = pydantic.Field
+ except AttributeError:
+ from pydantic import v1 as pydantic # type: ignore[no-redef]
+ except ImportError as e:
+ raise ImportError(
+ "pydantic is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return pydantic
+
+
+def _parse_constraints(
+ *,
+ constraints: Sequence[str],
+) -> Mapping[str, Optional["_SpecifierSet"]]:
+ """Parses a list of constraints into a dict of requirements.
+
+ Args:
+ constraints (list[str]):
+ Required. The list of package requirements to parse. This is assumed
+ to come from the `requirements.txt` file.
+
+ Returns:
+ dict[str, SpecifierSet]: The specifiers for each package.
+ """
+ requirements = _import_packaging_requirements_or_raise()
+ result: Dict[str, Optional[_SpecifierSet]] = {}
+ for constraint in constraints:
+ try:
+ if constraint.endswith(".whl"):
+ constraint = os.path.basename(constraint)
+ requirement = requirements.Requirement(constraint)
+ except Exception as e:
+ logger.warning(f"Failed to parse constraint: {constraint}. Exception: {e}")
+ continue
+ result[requirement.name] = requirement.specifier or None
+ return result
+
+
+def _prepare(
+ *,
+ agent: Optional[_AgentEngineInterface],
+ requirements: Optional[Sequence[str]],
+ extra_packages: Optional[Sequence[str]],
+ project: str,
+ location: str,
+ staging_bucket: str,
+ gcs_dir_name: str,
+ credentials: Optional[Any] = None,
+) -> None:
+ """Prepares the agent engine for creation or updates in Vertex AI.
+
+ This involves packaging and uploading artifacts to Cloud Storage. Note that
+ 1. This does not actually update the Agent Engine in Vertex AI.
+ 2. This will only generate and upload a pickled object if specified.
+ 3. This will only generate and upload the dependencies.tar.gz file if
+ extra_packages is non-empty.
+
+ Args:
+ agent: The agent engine to be prepared.
+ requirements (Sequence[str]): The set of PyPI dependencies needed.
+ extra_packages (Sequence[str]): The set of extra user-provided packages.
+ project (str): The project for the staging bucket.
+ location (str): The location for the staging bucket.
+ staging_bucket (str): The staging bucket name in the form "gs://...".
+ gcs_dir_name (str): The GCS bucket directory under `staging_bucket` to use
+ for staging the artifacts needed.
+ credentials: The credentials to use for the storage client.
+ """
+ if agent is None:
+ return
+ gcs_bucket = _get_gcs_bucket(
+ project=project,
+ location=location,
+ staging_bucket=staging_bucket,
+ credentials=credentials,
+ )
+ _upload_agent_engine(
+ agent=agent,
+ gcs_bucket=gcs_bucket,
+ gcs_dir_name=gcs_dir_name,
+ )
+ if requirements is not None:
+ _upload_requirements(
+ requirements=requirements,
+ gcs_bucket=gcs_bucket,
+ gcs_dir_name=gcs_dir_name,
+ )
+ if extra_packages is not None:
+ _upload_extra_packages(
+ extra_packages=extra_packages,
+ gcs_bucket=gcs_bucket,
+ gcs_dir_name=gcs_dir_name,
+ )
+
+
+def _register_api_methods_or_raise(
+ *,
+ agent_engine: genai_types.AgentEngine | genai_types.AgentEngineRuntimeRevision,
+ wrap_operation_fn: Optional[
+ dict[str, Callable[[str, str], Callable[..., Any]]]
+ ] = None,
+) -> None:
+ """Registers Agent Engine API methods based on operation schemas.
+
+ This function iterates through operation schemas provided by the
+ `agent_engine`. Each schema defines an API mode and method name.
+ It dynamically creates and registers methods on the `agent_engine`
+ to handle API calls based on the specified API mode.
+ Currently, only standard API mode `` is supported.
+
+ Args:
+ agent_engine: The AgentEngine to augment with API methods.
+ wrap_operation_fn: A dictionary of API modes and method wrapping
+ functions.
+
+ Raises:
+ ValueError: If the API mode is not supported or if the operation schema
+ is missing any required fields (e.g. `api_mode` or `name`).
+ """
+ operation_schemas = agent_engine.operation_schemas()
+ if not operation_schemas:
+ return
+ for operation_schema in operation_schemas:
+ if _MODE_KEY_IN_SCHEMA not in operation_schema:
+ raise ValueError(
+ f"Operation schema {operation_schema} does not"
+ f" contain an `{_MODE_KEY_IN_SCHEMA}` field."
+ )
+ api_mode = operation_schema.get(_MODE_KEY_IN_SCHEMA)
+ # For bidi stream api mode, we don't need to wrap the operation.
+ if api_mode == _BIDI_STREAM_API_MODE:
+ continue
+
+ if _METHOD_NAME_KEY_IN_SCHEMA not in operation_schema:
+ raise ValueError(
+ f"Operation schema {operation_schema} does not"
+ f" contain a `{_METHOD_NAME_KEY_IN_SCHEMA}` field."
+ )
+ method_name = operation_schema.get(_METHOD_NAME_KEY_IN_SCHEMA)
+ if not isinstance(method_name, str):
+ raise ValueError(
+ "Operation schema has a non-string value for"
+ f" `{_METHOD_NAME_KEY_IN_SCHEMA}`: {method_name}"
+ )
+ method_description = operation_schema.get(
+ "description",
+ _DEFAULT_METHOD_DOCSTRING_TEMPLATE.format(
+ method_name=method_name,
+ default_method_name=_DEFAULT_METHOD_NAME_MAP.get(
+ api_mode, _DEFAULT_METHOD_NAME
+ ),
+ return_type=_DEFAULT_METHOD_RETURN_TYPE_MAP.get(
+ api_mode,
+ _DEFAULT_METHOD_RETURN_TYPE,
+ ),
+ ),
+ )
+ _wrap_operation_map = {
+ _STANDARD_API_MODE: _wrap_query_operation,
+ _ASYNC_API_MODE: _wrap_async_query_operation,
+ _STREAM_API_MODE: _wrap_stream_query_operation,
+ _ASYNC_STREAM_API_MODE: _wrap_async_stream_query_operation,
+ _A2A_EXTENSION_MODE: _wrap_a2a_operation,
+ }
+ if isinstance(wrap_operation_fn, dict) and api_mode in wrap_operation_fn:
+ # Override the default function with user-specified function if it exists.
+ _wrap_operation = wrap_operation_fn[api_mode]
+ elif api_mode in _wrap_operation_map:
+ _wrap_operation = _wrap_operation_map[api_mode] # type: ignore[assignment]
+ else:
+ supported_api_modes = ", ".join(
+ f"`{mode}`" for mode in sorted(_wrap_operation_map.keys())
+ )
+ raise ValueError(
+ f"Unsupported api mode: `{api_mode}`,"
+ f" Supported modes are: {supported_api_modes}."
+ )
+
+ # Bind the method to the object.
+ if api_mode == _A2A_EXTENSION_MODE:
+ agent_card = operation_schema.get(_A2A_AGENT_CARD)
+ method = _wrap_operation(
+ method_name=method_name, agent_card=agent_card
+ ) # type: ignore[call-arg]
+ else:
+ method = _wrap_operation(method_name=method_name) # type: ignore[call-arg]
+ method.__name__ = method_name
+ if method_description and isinstance(method_description, str):
+ method.__doc__ = method_description
+ setattr(agent_engine, method_name, types.MethodType(method, agent_engine))
+
+
+def _scan_requirements(
+ *,
+ obj: Any,
+ ignore_modules: Optional[Sequence[str]] = None,
+ package_distributions: Optional[Mapping[str, Sequence[str]]] = None,
+ inspect_getmembers_kwargs: Optional[Mapping[str, Any]] = None,
+) -> Mapping[str, str]:
+ """Scans the object for modules and returns the requirements discovered.
+
+ This is not a comprehensive scan of the object, and only detects for common
+ cases based on the members of the object returned by `dir(obj)`.
+
+ Args:
+ obj (Any):
+ Required. The object to scan for package requirements.
+ ignore_modules (Sequence[str]):
+ Optional. The set of modules to ignore. It defaults to the set of
+ built-in and stdlib modules.
+ package_distributions (Mapping[str, Sequence[str]]):
+ Optional. The mapping of module names to the set of packages that
+ contain them. It defaults to the set of packages from
+ `importlib_metadata.packages_distributions()`.
+ inspect_getmembers_kwargs (Mapping[str, Any]):
+ Optional. The keyword arguments to pass to `inspect.getmembers`. It
+ defaults to an empty dictionary.
+
+ Returns:
+ Sequence[str]: The list of requirements that were discovered.
+ """
+ if ignore_modules is None:
+ ignore_modules = _BASE_MODULES # type: ignore[assignment]
+ if package_distributions is None:
+ package_distributions = _PACKAGE_DISTRIBUTIONS
+ modules_found = set(_DEFAULT_REQUIRED_PACKAGES)
+ inspect_getmembers_kwargs = inspect_getmembers_kwargs or {}
+ for _, attr in inspect.getmembers(obj, **inspect_getmembers_kwargs):
+ if not attr or inspect.isbuiltin(attr) or not hasattr(attr, "__module__"):
+ continue
+ module_name = (attr.__module__ or "").split(".")[0]
+ if module_name and module_name not in ignore_modules: # type: ignore[operator]
+ for module in package_distributions.get(module_name, []):
+ modules_found.add(module)
+ return {module: importlib_metadata.version(module) for module in modules_found}
+
+
+def _to_dict(message: proto.Message) -> Dict[str, Any]:
+ """Converts the contents of the protobuf message to JSON format.
+
+ Args:
+ message (proto.Message):
+ Required. The proto message to be converted to a JSON dictionary.
+
+ Returns:
+ dict[str, Any]: A dictionary containing the contents of the proto.
+ """
+ try:
+ # Best effort attempt to convert the message into a JSON dictionary.
+ result: Dict[str, Any] = json.loads(
+ json_format.MessageToJson(
+ message._pb,
+ preserving_proto_field_name=True,
+ )
+ )
+ except AttributeError:
+ result: Dict[str, Any] = json.loads( # type: ignore[no-redef]
+ json_format.MessageToJson(
+ message,
+ preserving_proto_field_name=True,
+ )
+ )
+ return result
+
+
+def _to_proto(
+ obj: Union[Dict[str, Any], proto.Message],
+ message: Optional[proto.Message] = None,
+) -> proto.Message:
+ """Parses a JSON-like object into a message.
+
+ If the object is already a message, this will return the object as-is. If
+ the object is a JSON Dict, this will parse and merge the object into the
+ message.
+
+ Args:
+ obj (Union[dict[str, Any], proto.Message]):
+ Required. The object to convert to a proto message.
+ message (proto.Message):
+ Optional. A protocol buffer message to merge the obj into. It
+ defaults to Struct() if unspecified.
+
+ Returns:
+ proto.Message: The same message passed as argument.
+ """
+ if message is None:
+ message = struct_pb2.Struct()
+ if isinstance(obj, (proto.Message, struct_pb2.Struct)):
+ return obj
+ try:
+ json_format.ParseDict(obj, message._pb)
+ except AttributeError:
+ json_format.ParseDict(obj, message)
+ return message
+
+
+def _upload_agent_engine(
+ *,
+ agent: _AgentEngineInterface,
+ gcs_bucket: _StorageBucket,
+ gcs_dir_name: str,
+) -> None:
+ """Uploads the agent engine to GCS."""
+ cloudpickle = _import_cloudpickle_or_raise()
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_BLOB_FILENAME}")
+ with blob.open("wb") as f:
+ try:
+ cloudpickle.dump(agent, f)
+ except Exception as e:
+ url = "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#deployment-considerations"
+ error_msg = f"Failed to serialize agent engine. Visit {url} for details."
+ if "google._upb._message" in str(e) or "Descriptor" in str(e):
+ error_msg += (
+ " This is often caused by protobuf objects (like Part, AgentCard) "
+ "being imported at the global module level. Please move these "
+ "imports inside the functions or methods where they are used. "
+ "Alternatively, you can import the entire module: "
+ "`from a2a import types`."
+ )
+ raise TypeError(error_msg) from e
+ with blob.open("rb") as f:
+ try:
+ _ = cloudpickle.load(f)
+ except Exception as e:
+ raise TypeError("Agent engine serialized to an invalid format") from e
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
+ logger.info(f"Wrote to {dir_name}/{_BLOB_FILENAME}")
+
+
+def _upload_requirements(
+ *,
+ requirements: Sequence[str],
+ gcs_bucket: _StorageBucket,
+ gcs_dir_name: str,
+) -> None:
+ """Uploads the requirements file to GCS."""
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_REQUIREMENTS_FILE}")
+ blob.upload_from_string("\n".join(requirements))
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
+ logger.info(f"Writing to {dir_name}/{_REQUIREMENTS_FILE}")
+
+
+def _upload_extra_packages(
+ *,
+ extra_packages: Sequence[str],
+ gcs_bucket: _StorageBucket,
+ gcs_dir_name: str,
+) -> None:
+ """Uploads extra packages to GCS."""
+ logger.info("Creating in-memory tarfile of extra_packages")
+ tar_fileobj = io.BytesIO()
+ with tarfile.open(fileobj=tar_fileobj, mode="w|gz") as tar:
+ for file in extra_packages:
+ tar.add(file)
+ tar_fileobj.seek(0)
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_EXTRA_PACKAGES_FILE}")
+ blob.upload_from_string(tar_fileobj.read())
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
+ logger.info(f"Writing to {dir_name}/{_EXTRA_PACKAGES_FILE}")
+
+
+def _create_base64_encoded_tarball(
+ *,
+ source_packages: Sequence[str],
+) -> str:
+ """Creates a base64 encoded tarball from the source packages."""
+ logger.info("Creating in-memory tarfile of source_packages")
+ tar_fileobj = io.BytesIO()
+ project_dir = os.path.realpath(os.getcwd())
+ with tarfile.open(fileobj=tar_fileobj, mode="w|gz") as tar:
+ for file in source_packages:
+ real_file_path = os.path.realpath(file)
+ if real_file_path != project_dir and not real_file_path.startswith(
+ project_dir + os.sep
+ ):
+ raise ValueError(
+ f"File path '{file}' is outside the project directory "
+ f"'{project_dir}'."
+ )
+ tar.add(file)
+ tar_fileobj.seek(0)
+ tarball_bytes = tar_fileobj.read()
+ return base64.b64encode(tarball_bytes).decode("utf-8")
+
+
+def _validate_packages_or_raise(
+ *,
+ packages: Sequence[str],
+ build_options: Optional[Dict[str, Sequence[str]]] = None,
+) -> Sequence[str]:
+ """Tries to validates the packages."""
+ packages = packages or []
+ if build_options and _INSTALLATION_SUBDIR in build_options:
+ _validate_installation_scripts_or_raise(
+ script_paths=build_options[_INSTALLATION_SUBDIR],
+ packages=packages,
+ )
+ for package in packages:
+ if not os.path.exists(package):
+ raise FileNotFoundError(f"Package specified but not found: {package=}")
+ return packages
+
+
+def _validate_installation_scripts_or_raise(
+ *,
+ script_paths: Sequence[str],
+ packages: Sequence[str],
+) -> None:
+ """Validates the installation scripts' path explicitly provided by the user.
+
+ Args:
+ script_paths (Sequence[str]):
+ Required. The paths to the installation scripts.
+ packages (Sequence[str]):
+ Required. The user-provided packages.
+
+ Raises:
+ ValueError: If a user-defined script is not under the expected
+ subdirectory, or not in `packages`, or if a package is
+ in the installation scripts subdirectory, but is not specified as an
+ installation script.
+ """
+ for script_path in script_paths:
+ if not script_path.startswith(_INSTALLATION_SUBDIR):
+ logger.warning(
+ f"User-defined installation script '{script_path}' is not in "
+ f"the expected '{_INSTALLATION_SUBDIR}' subdirectory. "
+ f"Ensure it is placed in '{_INSTALLATION_SUBDIR}' within your "
+ f"'extra_packages' or 'source_packages'."
+ )
+ raise ValueError(
+ f"Required installation script '{script_path}' "
+ f"is not under '{_INSTALLATION_SUBDIR}'"
+ )
+
+ if script_path not in packages:
+ logger.warning(
+ f"User-defined installation script '{script_path}' is not in "
+ f"'extra_packages' or 'source_packages'. Ensure it is added to "
+ f"'extra_packages' or 'source_packages'."
+ )
+ raise ValueError(
+ f"User-defined installation script '{script_path}' "
+ f"does not exist in 'extra_packages' or 'source_packages'."
+ )
+
+ for package in packages:
+ if package.startswith(_INSTALLATION_SUBDIR) and package not in script_paths:
+ logger.warning(
+ f"Package '{package}' is in the installation "
+ "scripts subdirectory, but is not specified as an installation "
+ "script in `build_options`. "
+ "Ensure it is added to installation_scripts for "
+ "automatic execution."
+ )
+ raise ValueError(
+ f"Package '{package}' is in the installation "
+ "scripts subdirectory, but is not specified as an installation "
+ "script in `build_options`."
+ )
+ return
+
+
+def _validate_staging_bucket_or_raise(*, staging_bucket: str) -> str:
+ """Tries to validate the staging bucket."""
+ if not staging_bucket:
+ raise ValueError(
+ "Please provide a `staging_bucket` in `client.agent_engines.create(...)`."
+ )
+ if not staging_bucket.startswith("gs://"):
+ raise ValueError(f"{staging_bucket=} must start with `gs://`")
+ return staging_bucket
+
+
+def _validate_requirements_or_warn(
+ *,
+ obj: Any,
+ requirements: List[str],
+) -> List[str]:
+ """Compiles the requirements into a list of requirements."""
+ requirements = requirements.copy()
+ try:
+ current_requirements = _scan_requirements(obj=obj)
+ logger.info(f"Identified the following requirements: {current_requirements}")
+ constraints = _parse_constraints(constraints=requirements)
+ missing_requirements = _compare_requirements(
+ requirements=current_requirements,
+ constraints=constraints,
+ )
+ for warning_type, warnings in missing_requirements["warnings"].items():
+ if warnings:
+ logger.warning(
+ f"The following requirements are {warning_type}: {warnings}"
+ )
+ for action_type, actions in missing_requirements["actions"].items():
+ if actions and action_type == _ACTION_APPEND:
+ for action in actions: # type: ignore[attr-defined]
+ requirements.append(action)
+ logger.info(f"The following requirements are appended: {actions}")
+ except Exception as e:
+ logger.warning(f"Failed to compile requirements: {e}")
+ return requirements
+
+
+def _validate_requirements_or_raise(
+ *,
+ agent: Any,
+ requirements: Optional[Sequence[str]] = None,
+) -> Sequence[str]:
+ """Tries to validate the requirements."""
+ if requirements is None:
+ requirements = []
+ elif isinstance(requirements, str):
+ try:
+ logger.info(f"Reading requirements from {requirements=}")
+ with open(requirements) as f:
+ requirements = f.read().splitlines()
+ logger.info(f"Read the following lines: {requirements}")
+ except IOError as err:
+ raise IOError(f"Failed to read requirements from {requirements=}") from err
+ requirements = _validate_requirements_or_warn(
+ obj=agent,
+ requirements=requirements,
+ )
+ logger.info(f"The final list of requirements: {requirements}")
+ return requirements
+
+
+def _validate_agent_or_raise(
+ *,
+ agent: _AgentEngineInterface,
+) -> _AgentEngineInterface:
+ """Tries to validate the agent engine.
+
+ The agent engine must have one of the following:
+ * a callable method named `query`
+ * a callable method named `stream_query`
+ * a callable method named `async_stream_query`
+ * a callable method named `bidi_stream_query`
+ * a callable method named `register_operations`
+
+ Args:
+ agent: The agent to be validated.
+
+ Returns:
+ The validated agent engine.
+
+ Raises:
+ TypeError: If `agent_engine` has no callable method named `query`,
+ `stream_query` or `register_operations`.
+ ValueError: If `agent_engine` has an invalid `query`, `stream_query` or
+ `register_operations` signature.
+ """
+ try:
+ from google.adk.agents import BaseAgent
+
+ if isinstance(agent, BaseAgent):
+ logger.info("Deploying google.adk.agents.Agent as an application.")
+ from agentplatform import agent_engines
+
+ agent = agent_engines.AdkApp(agent=agent)
+ except Exception:
+ pass
+ is_queryable = isinstance(agent, Queryable) and callable(agent.query)
+ is_async_queryable = isinstance(agent, AsyncQueryable) and callable(
+ agent.async_query
+ )
+ is_stream_queryable = isinstance(agent, StreamQueryable) and callable(
+ agent.stream_query
+ )
+ is_async_stream_queryable = isinstance(agent, AsyncStreamQueryable) and callable(
+ agent.async_stream_query
+ )
+ is_bidi_stream_queryable = isinstance(agent, BidiStreamQueryable) and callable(
+ agent.bidi_stream_query
+ )
+ is_operation_registrable = isinstance(agent, OperationRegistrable) and callable(
+ agent.register_operations
+ )
+
+ if not (
+ is_queryable
+ or is_async_queryable
+ or is_stream_queryable
+ or is_operation_registrable
+ or is_bidi_stream_queryable
+ or is_async_stream_queryable
+ ):
+ raise TypeError(
+ "agent_engine has none of the following callable methods: "
+ "`query`, `async_query`, `stream_query`, `async_stream_query`, "
+ "`bidi_stream_query`, or `register_operations`."
+ )
+
+ if is_queryable:
+ try:
+ inspect.signature(getattr(agent, "query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid query signature. This might be due to a missing "
+ "`self` argument in the agent.query method."
+ ) from err
+
+ if is_async_queryable:
+ try:
+ inspect.signature(getattr(agent, "async_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid async_query signature. This might be due to a missing "
+ "`self` argument in the agent.async_query method."
+ ) from err
+
+ if is_stream_queryable:
+ try:
+ inspect.signature(getattr(agent, "stream_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid stream_query signature. This might be due to a missing"
+ " `self` argument in the agent.stream_query method."
+ ) from err
+
+ if is_async_stream_queryable:
+ try:
+ inspect.signature(getattr(agent, "async_stream_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid async_stream_query signature. This might be due to a "
+ " missing `self` argument in the agent.async_stream_query method."
+ ) from err
+
+ if is_bidi_stream_queryable:
+ try:
+ inspect.signature(getattr(agent, "bidi_stream_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid bidi_stream_query signature. This might be due to a "
+ " missing `self` argument in the agent.bidi_stream_query method."
+ ) from err
+
+ if is_operation_registrable:
+ try:
+ inspect.signature(getattr(agent, "register_operations"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid register_operations signature. This might be due to a "
+ "missing `self` argument in the agent.register_operations method."
+ ) from err
+
+ if isinstance(agent, Cloneable):
+ # Avoid undeployable states.
+ agent = agent.clone()
+ return agent
+
+
+def _wrap_agent_operation(*, agent: Any, operation: str) -> Callable[..., Any]:
+ """Wraps an agent operation into a method (works for all API modes)."""
+
+ def _method(self, **kwargs) -> Any: # type: ignore[no-untyped-def]
+ if not self._tmpl_attrs.get("agent"):
+ self.set_up()
+ return getattr(self._tmpl_attrs["agent"], operation)(**kwargs)
+
+ _method.__name__ = operation
+ _method.__doc__ = getattr(agent, operation).__doc__
+ return _method
+
+
+def _wrap_query_operation(*, method_name: str) -> Callable[..., Any]:
+ """Wraps an Agent Engine method, creating a callable for `query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method using the `query` API. It handles the creation of
+ the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `query` API.
+ """
+
+ def _method(self: genai_types.AgentEngine, **kwargs) -> Any: # type: ignore[no-untyped-def]
+ if not self.api_client:
+ raise ValueError("api_client is not initialized.")
+ if not self.api_resource:
+ raise ValueError("api_resource is not initialized.")
+ response = self.api_client._query(
+ name=self.api_resource.name,
+ config={
+ "class_method": method_name,
+ "input": kwargs,
+ "include_all_fields": True,
+ },
+ )
+ return response.output
+
+ return _method
+
+
+def _wrap_async_query_operation(
+ *, method_name: str
+) -> Callable[..., Coroutine[Any, Any, Any]]:
+ """Wraps an Agent Engine method, creating an async callable for `query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method asynchronously using the `query` API. It handles the
+ creation of the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `query` API.
+ """
+
+ async def _method(
+ self: genai_types.AgentEngine, **kwargs: Any
+ ) -> Union[Coroutine[Any, Any, Any], Any]:
+ if not self.api_async_client:
+ raise ValueError("api_async_client is not initialized.")
+ if not self.api_resource:
+ raise ValueError("api_resource is not initialized.")
+ response = await self.api_async_client._query(
+ name=self.api_resource.name,
+ config={
+ "class_method": method_name,
+ "input": kwargs,
+ "include_all_fields": True,
+ },
+ )
+ return response.output
+
+ return _method
+
+
+def _wrap_stream_query_operation(*, method_name: str) -> Callable[..., Iterator[Any]]:
+ """Wraps an Agent Engine method, creating a callable for `stream_query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method using the `stream_query` API. It handles the
+ creation of the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `stream_query` API.
+ """
+
+ def _method(self: genai_types.AgentEngine, **kwargs) -> Iterator[Any]: # type: ignore[no-untyped-def]
+ if not self.api_client:
+ raise ValueError("api_client is not initialized.")
+ if not self.api_resource:
+ raise ValueError("api_resource is not initialized.")
+ for http_response in self.api_client._stream_query(
+ name=self.api_resource.name,
+ config={
+ "class_method": method_name,
+ "input": kwargs,
+ "include_all_fields": True,
+ },
+ ):
+ for line in _yield_parsed_json(http_response=http_response):
+ if line is not None:
+ yield line
+
+ return _method
+
+
+def _wrap_async_stream_query_operation(
+ *, method_name: str
+) -> Callable[..., AsyncIterator[Any]]:
+ """Wraps an Agent Engine method, creating an async callable for `stream_query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method using the `stream_query` API. It handles the
+ creation of the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `stream_query` API.
+ """
+
+ async def _method(self: genai_types.AgentEngine, **kwargs) -> AsyncIterator[Any]: # type: ignore[no-untyped-def]
+ if not self.api_client:
+ raise ValueError("api_client is not initialized.")
+ if not self.api_resource:
+ raise ValueError("api_resource is not initialized.")
+ async for http_response in self.api_client._async_stream_query(
+ name=self.api_resource.name,
+ config={
+ "class_method": method_name,
+ "input": kwargs,
+ "include_all_fields": True,
+ },
+ ):
+ for line in _yield_parsed_json(http_response=http_response):
+ if line is not None:
+ yield line
+
+ return _method
+
+
+def _wrap_a2a_operation(method_name: str, agent_card: str) -> Callable[..., list[Any]]:
+ """Wraps an Agent Engine method, creating a callable for A2A API.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ agent_card: The agent card to use for the A2A API call.
+ Example:
+ {'additionalInterfaces': None,
+ 'capabilities': {'extensions': None,
+ 'pushNotifications': None,
+ 'stateTransitionHistory': None,
+ 'streaming': False},
+ 'defaultInputModes': ['text'],
+ 'defaultOutputModes': ['text'],
+ 'description': (
+ 'A helpful assistant agent that can answer questions.'
+ ),
+ 'documentationUrl': None,
+ 'iconUrl': None,
+ 'name': 'Q&A Agent',
+ 'preferredTransport': 'JSONRPC',
+ 'protocolVersion': '0.3.0',
+ 'provider': None,
+ 'security': None,
+ 'securitySchemes': None,
+ 'signatures': None,
+ 'skills': [{
+ 'description': (
+ 'A helpful assistant agent that can answer questions.'
+ ),
+ 'examples': ['Who is leading 2025 F1 Standings?',
+ 'Where can i find an active volcano?'],
+ 'id': 'question_answer',
+ 'inputModes': None,
+ 'name': 'Q&A Agent',
+ 'outputModes': None,
+ 'security': None,
+ 'tags': ['Question-Answer']}],
+ 'supportsAuthenticatedExtendedCard': True,
+ 'url': 'http://localhost:8080/',
+ 'version': '1.0.0'}
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the A2A API.
+ """
+
+ async def _method(self, **kwargs) -> Any: # type: ignore[no-untyped-def]
+ """Wraps an Agent Engine method, creating a callable for A2A API."""
+ if not self.api_client:
+ raise ValueError("api_client is not initialized.")
+ if not self.api_resource:
+ raise ValueError("api_resource is not initialized.")
+ a2a_agent_card = AgentCard(**json.loads(agent_card))
+ # A2A + AE integration currently only supports Rest API.
+ if (
+ a2a_agent_card.preferred_transport
+ and a2a_agent_card.preferred_transport != TransportProtocol.http_json
+ ):
+ raise ValueError(
+ "Only HTTP+JSON is supported for preferred transport on agent card "
+ )
+
+ # Set preferred transport to HTTP+JSON if not set.
+ if not hasattr(a2a_agent_card, "preferred_transport"):
+ a2a_agent_card.preferred_transport = TransportProtocol.http_json
+
+ if not hasattr(a2a_agent_card.capabilities, "streaming"):
+ a2a_agent_card.capabilities.streaming = False
+
+ # agent_card is set on the class_methods before set_up is invoked.
+ # Ensure that the agent_card url is set correctly before the client is created.
+ base_url = self.api_client._api_client._http_options.base_url.rstrip("/")
+ api_version = self.api_client._api_client._http_options.api_version
+ a2a_agent_card.url = f"{base_url}/{api_version}/{self.api_resource.name}/a2a"
+
+ # Using a2a client, inject the auth token from the global config.
+ config = ClientConfig(
+ supported_transports=[
+ TransportProtocol.http_json,
+ ],
+ use_client_preference=True,
+ httpx_client=httpx.AsyncClient(
+ headers={
+ "Authorization": (
+ f"Bearer {self.api_client._api_client._credentials.token}"
+ )
+ },
+ timeout=(
+ self.api_client._api_client._http_options.timeout / 1000.0
+ if self.api_client._api_client._http_options.timeout
+ else None
+ ),
+ ),
+ )
+ factory = ClientFactory(config)
+ client = factory.create(a2a_agent_card)
+
+ if method_name == "on_message_send":
+ response = client.send_message(Message(**kwargs))
+ chunks = []
+ async for chunk in response:
+ chunks.append(chunk)
+ return chunks
+ elif method_name == "on_get_task":
+ response = await client.get_task(TaskQueryParams(**kwargs))
+ elif method_name == "on_cancel_task":
+ response = await client.cancel_task(TaskIdParams(**kwargs))
+ elif method_name == "handle_authenticated_agent_card":
+ response = await client.get_card()
+ else:
+ raise ValueError(f"Unknown method name: {method_name}")
+
+ return response
+
+ return _method # type: ignore[return-value]
+
+
+def _yield_parsed_json(http_response: google_genai_types.HttpResponse) -> Iterator[Any]:
+ """Converts the body of the HTTP Response message to JSON format.
+
+ Args:
+ http_response (google.genai.types.HttpResponse):
+ Required. The httpbody body to be converted to JSON object(s).
+
+ Yields:
+ Any: A JSON object or line of the original body or None.
+ """
+ if not http_response.body:
+ yield None
+ return
+
+ # Handle the case of multiple dictionaries delimited by newlines.
+ for line in http_response.body.split("\n"):
+ if line:
+ try:
+ line = json.loads(line)
+ except Exception as e:
+ logger.warning(f"failed to parse json: {line}. Exception: {e}")
+ yield line
+
+
+def _validate_resource_limits_or_raise(resource_limits: dict[str, str]) -> None:
+ """Validates the resource limits.
+
+ Checks that the resource limits are a dict with 'cpu' and 'memory' keys.
+ Checks that the 'cpu' value is one of 1, 2, 4, 6, 8.
+ Checks that the 'memory' value is a string ending with 'Gi'.
+ Checks that the memory size is smaller than 32Gi.
+ Checks that the memory size requires at least the specified number of CPUs.
+
+ Args:
+ resource_limits: The resource limits to be validated.
+
+ Raises:
+ TypeError: If the resource limits are not a dict.
+ KeyError: If the resource limits do not contain 'cpu' and 'memory' keys.
+ ValueError: If the 'cpu' value is not one of 1, 2, 4, 6, 8.
+ ValueError: If the 'memory' value is not a string ending with 'Gi'.
+ ValueError: If the memory size is too large.
+ ValueError: If the memory size requires more CPUs than the specified
+ 'cpu' value.
+ """
+ if not isinstance(resource_limits, dict):
+ raise TypeError(f"resource_limits must be a dict. Got {type(resource_limits)}")
+ if "cpu" not in resource_limits or "memory" not in resource_limits:
+ raise KeyError("resource_limits must contain 'cpu' and 'memory' keys.")
+
+ cpu = int(resource_limits["cpu"])
+ memory_str = resource_limits["memory"]
+
+ if cpu not in [1, 2, 4, 6, 8]:
+ raise ValueError(
+ "resource_limits['cpu'] must be one of 1, 2, 4, 6, 8. Got" f" {cpu}"
+ )
+
+ if not isinstance(memory_str, str) or not memory_str.endswith("Gi"):
+ raise ValueError(
+ "resource_limits['memory'] must be a string ending with 'Gi'."
+ f" Got {memory_str}"
+ )
+
+ try:
+ memory_gb = int(memory_str[:-2])
+ except ValueError:
+ raise ValueError(
+ f"Invalid memory value: {memory_str}. Must be an integer"
+ " followed by 'Gi'."
+ )
+
+ # https://cloud.google.com/run/docs/configuring/memory-limits
+ if memory_gb > 32:
+ raise ValueError(
+ f"Memory size of {memory_str} is too large. Must be smaller than 32Gi."
+ )
+ if memory_gb > 24:
+ min_cpu = 8
+ elif memory_gb > 16:
+ min_cpu = 6
+ elif memory_gb > 8:
+ min_cpu = 4
+ elif memory_gb > 4:
+ min_cpu = 2
+ else:
+ min_cpu = 1
+
+ if cpu < min_cpu:
+ raise ValueError(
+ f"Memory size of {memory_str} requires at least {min_cpu} CPUs."
+ f" Got {cpu}"
+ )
+
+
+def _is_adk_agent(agent_engine: _AgentEngineInterface) -> bool:
+ """Checks if the agent engine is an ADK agent.
+
+ Args:
+ agent_engine: The agent engine to check.
+
+ Returns:
+ True if the agent engine is an ADK agent, False otherwise.
+ """
+
+ from agentplatform.agent_engines.templates import adk
+
+ return isinstance(agent_engine, adk.AdkApp)
+
+
+def _add_telemetry_enablement_env(
+ env_vars: Optional[Dict[str, Union[str, Any]]]
+) -> Optional[Dict[str, Union[str, Any]]]:
+ """Adds telemetry enablement env var to the env vars.
+
+ This is in order to achieve default-on telemetry.
+ If the telemetry enablement env var is already set, we do not override it.
+
+ Args:
+ env_vars: The env vars to add the telemetry enablement env var to.
+
+ Returns:
+ The env vars with the telemetry enablement env var added.
+ """
+
+ GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY = (
+ "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
+ )
+ env_to_add = {GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY: "unspecified"}
+
+ if env_vars is None:
+ return env_to_add
+
+ if not isinstance(env_vars, dict):
+ raise TypeError(f"env_vars must be a dict, but got {type(env_vars)}.")
+
+ if GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY in env_vars:
+ return env_vars
+
+ return env_vars | env_to_add
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_bigquery_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_bigquery_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..94813df432bb427e9d1248b2fb1b417b0ff9cb84
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_bigquery_utils.py
@@ -0,0 +1,49 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import logging
+
+from google.cloud import bigquery
+from google.genai._api_client import BaseApiClient
+import pandas as pd
+
+
+logger = logging.getLogger(__name__)
+
+
+class BigQueryUtils:
+ """Handles BigQuery operations."""
+
+ def __init__(self, api_client: BaseApiClient):
+ self.api_client = api_client
+ self.bigquery_client = bigquery.Client(
+ project=self.api_client.project,
+ credentials=self.api_client._credentials,
+ )
+
+ def load_bigquery_to_dataframe(self, table_uri: str) -> "pd.DataFrame":
+ """Loads data from a BigQuery table into a DataFrame."""
+ table = self.bigquery_client.get_table(table_uri)
+ return self.bigquery_client.list_rows(table).to_dataframe()
+
+ def upload_dataframe_to_bigquery(
+ self, df: "pd.DataFrame", bq_table_uri: str
+ ) -> None:
+ """Uploads a Pandas DataFrame to a BigQuery table."""
+ job = self.bigquery_client.load_table_from_dataframe(df, bq_table_uri)
+ job.result()
+ logger.info(
+ f"DataFrame successfully uploaded to BigQuery table: {bq_table_uri}"
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_datasets_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_datasets_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b0774eeaa2f1eb5a1efe5d34f5f415dad3e1458
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_datasets_utils.py
@@ -0,0 +1,280 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Utility functions for multimodal dataset."""
+
+import asyncio
+import datetime
+from typing import Any, Type, TypeVar
+import uuid
+
+import google.auth.credentials
+from agentplatform._genai.types import common
+from google.genai import _common
+
+
+METADATA_SCHEMA_URI = (
+ "gs://google-cloud-aiplatform/schema/dataset/metadata/multimodal_1.0.0.yaml"
+)
+_BQ_MULTIREGIONS = {"us", "eu"}
+_DEFAULT_BQ_DATASET_PREFIX = "vertex_datasets"
+_DEFAULT_BQ_TABLE_PREFIX = "multimodal_dataset"
+
+T = TypeVar("T", bound=_common.BaseModel)
+
+
+def create_from_response(
+ model_type: Type[T],
+ response: dict[str, Any],
+ config: Any | None = None,
+) -> T:
+ """Creates a model from a response."""
+ kwargs = (
+ {
+ "config": {
+ "response_schema": getattr(config, "response_schema", None),
+ "response_json_schema": getattr(config, "response_json_schema", None),
+ "include_all_fields": getattr(config, "include_all_fields", None),
+ }
+ }
+ if config
+ else {}
+ )
+ return model_type._from_response(response=response, kwargs=kwargs)
+
+
+def validate_multimodal_dataset_bigquery_uri(
+ multimodal_dataset: common.MultimodalDataset,
+) -> None:
+ """Validates that a multimodal dataset has a bigquery uri or raises ValueError."""
+ if (
+ not hasattr(multimodal_dataset, "metadata")
+ or multimodal_dataset.metadata is None
+ ):
+ raise ValueError("Multimodal dataset metadata is required.")
+ if (
+ not hasattr(multimodal_dataset.metadata, "input_config")
+ or multimodal_dataset.metadata.input_config is None
+ ):
+ raise ValueError("Multimodal dataset input config is required.")
+ if (
+ not hasattr(multimodal_dataset.metadata.input_config, "bigquery_source")
+ or multimodal_dataset.metadata.input_config.bigquery_source is None
+ ):
+ raise ValueError("Multimodal dataset input config bigquery source is required.")
+ if (
+ not hasattr(multimodal_dataset.metadata.input_config.bigquery_source, "uri")
+ or multimodal_dataset.metadata.input_config.bigquery_source.uri is None
+ ):
+ raise ValueError(
+ "Multimodal dataset input config bigquery source uri is required."
+ )
+ if not str(multimodal_dataset.metadata.input_config.bigquery_source.uri).startswith(
+ "bq://"
+ ):
+ raise ValueError(
+ "Multimodal dataset bigquery source uri must start with 'bq://'."
+ )
+
+
+def _try_import_bigframes() -> Any:
+ """Tries to import `bigframes`."""
+ try:
+ import bigframes
+ import bigframes.pandas
+ import bigframes.bigquery
+
+ return bigframes
+ except ImportError as exc:
+ raise ImportError(
+ "`bigframes` is not installed. Please call 'pip install bigframes'."
+ ) from exc
+
+
+def _try_import_bigquery() -> Any:
+ """Tries to import `bigquery`."""
+ try:
+ from google.cloud import bigquery
+
+ return bigquery
+ except ImportError as exc:
+ raise ImportError(
+ "`bigquery` is not installed. Please call 'pip install"
+ " google-cloud-bigquery'."
+ ) from exc
+
+
+def _bq_dataset_location_allowed(
+ vertex_location: str, bq_dataset_location: str
+) -> bool:
+ if bq_dataset_location == vertex_location:
+ return True
+ if bq_dataset_location in _BQ_MULTIREGIONS:
+ return vertex_location.startswith(bq_dataset_location)
+ return False
+
+
+def _normalize_and_validate_table_id(
+ *,
+ table_id: str,
+ project: str,
+ location: str,
+ credentials: google.auth.credentials.Credentials,
+) -> str:
+ bigquery = _try_import_bigquery()
+
+ table_ref = bigquery.TableReference.from_string(table_id, default_project=project)
+ if table_ref.project != project:
+ raise ValueError(
+ "The BigQuery table "
+ f"`{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}`"
+ " must be in the same project as the multimodal dataset."
+ f" The multimodal dataset is in `{project}`, but the BigQuery table"
+ f" is in `{table_ref.project}`."
+ )
+
+ dataset_ref = bigquery.DatasetReference(
+ project=table_ref.project, dataset_id=table_ref.dataset_id
+ )
+ client = bigquery.Client(project=project, credentials=credentials)
+ bq_dataset = client.get_dataset(dataset_ref=dataset_ref)
+ if not _bq_dataset_location_allowed(location, bq_dataset.location):
+ raise ValueError(
+ "The BigQuery dataset"
+ f" `{dataset_ref.project}.{dataset_ref.dataset_id}` must be in the"
+ " same location as the multimodal dataset. The multimodal dataset"
+ f" is in `{location}`, but the BigQuery dataset is in"
+ f" `{bq_dataset.location}`."
+ )
+ return f"{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}"
+
+
+async def _normalize_and_validate_table_id_async(
+ *,
+ table_id: str,
+ project: str,
+ location: str,
+ credentials: google.auth.credentials.Credentials,
+) -> str:
+ bigquery = _try_import_bigquery()
+
+ table_ref = bigquery.TableReference.from_string(table_id, default_project=project)
+ if table_ref.project != project:
+ raise ValueError(
+ "The BigQuery table "
+ f"`{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}`"
+ " must be in the same project as the multimodal dataset."
+ f" The multimodal dataset is in `{project}`, but the BigQuery table"
+ f" is in `{table_ref.project}`."
+ )
+
+ dataset_ref = bigquery.DatasetReference(
+ project=table_ref.project, dataset_id=table_ref.dataset_id
+ )
+ client = bigquery.Client(project=project, credentials=credentials)
+ bq_dataset = await asyncio.to_thread(client.get_dataset, dataset_ref=dataset_ref)
+ if not _bq_dataset_location_allowed(location, bq_dataset.location):
+ raise ValueError(
+ "The BigQuery dataset"
+ f" `{dataset_ref.project}.{dataset_ref.dataset_id}` must be in the"
+ " same location as the multimodal dataset. The multimodal dataset"
+ f" is in `{location}`, but the BigQuery dataset is in"
+ f" `{bq_dataset.location}`."
+ )
+ return f"{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}"
+
+
+def _create_default_bigquery_dataset_if_not_exists(
+ *,
+ project: str,
+ location: str,
+ credentials: google.auth.credentials.Credentials,
+) -> str:
+ bigquery = _try_import_bigquery()
+
+ bigquery_client = bigquery.Client(project=project, credentials=credentials)
+ location_str = location.lower().replace("-", "_")
+ dataset_id = bigquery.DatasetReference(
+ project, f"{_DEFAULT_BQ_DATASET_PREFIX}_{location_str}"
+ )
+ dataset = bigquery.Dataset(dataset_ref=dataset_id)
+ dataset.location = location
+ bigquery_client.create_dataset(dataset, exists_ok=True)
+ return f"{dataset_id.project}.{dataset_id.dataset_id}"
+
+
+async def _create_default_bigquery_dataset_if_not_exists_async(
+ *,
+ project: str,
+ location: str,
+ credentials: google.auth.credentials.Credentials,
+) -> str:
+ bigquery = _try_import_bigquery()
+
+ bigquery_client = bigquery.Client(project=project, credentials=credentials)
+ location_str = location.lower().replace("-", "_")
+ dataset_id = bigquery.DatasetReference(
+ project, f"{_DEFAULT_BQ_DATASET_PREFIX}_{location_str}"
+ )
+ dataset = bigquery.Dataset(dataset_ref=dataset_id)
+ dataset.location = location
+ await asyncio.to_thread(bigquery_client.create_dataset, dataset, exists_ok=True)
+ return f"{dataset_id.project}.{dataset_id.dataset_id}"
+
+
+def _generate_target_table_id(dataset_id: str) -> str:
+ return f"{dataset_id}.{_DEFAULT_BQ_TABLE_PREFIX}_{str(uuid.uuid4())}"
+
+
+def generate_multimodal_dataset_display_name() -> str:
+ """Generates a display name with a timestamp."""
+ return f"MultimodalDataset {datetime.datetime.now().isoformat(sep=' ')}"
+
+
+def save_dataframe_to_bigquery(
+ dataframe: "bigframes.pandas.DataFrame", # type: ignore # noqa: F821
+ target_table_id: str,
+ bq_client: "bigquery.Client", # type: ignore # noqa: F821
+) -> None:
+ # `to_gbq` does not support cross-region use cases. We use `copy_table` as a workaround.
+ temp_table_id = dataframe.to_gbq()
+ copy_job = bq_client.copy_table(
+ sources=temp_table_id,
+ destination=target_table_id,
+ )
+ copy_job.result()
+ bq_client.delete_table(temp_table_id)
+
+
+async def save_dataframe_to_bigquery_async(
+ dataframe: "bigframes.pandas.DataFrame", # type: ignore # noqa: F821
+ target_table_id: str,
+ bq_client: "bigquery.Client", # type: ignore # noqa: F821
+) -> None:
+ # `to_gbq` does not support cross-region use cases. We use `copy_table` as a workaround.
+ temp_table_id = await asyncio.to_thread(dataframe.to_gbq)
+ copy_job = await asyncio.to_thread(
+ bq_client.copy_table,
+ sources=temp_table_id,
+ destination=target_table_id,
+ )
+ await asyncio.to_thread(copy_job.result)
+ await asyncio.to_thread(bq_client.delete_table, temp_table_id)
+
+
+def resolve_dataset_name(resource_name_or_id: str, project: str, location: str) -> str:
+ """Resolves a dataset name or ID to a full resource name."""
+ if "/" not in resource_name_or_id:
+ return f"projects/{project}/locations/{location}/datasets/{resource_name_or_id}"
+ return resource_name_or_id
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..4929d716ad092a0ae9fbf599bbb60a49e12551d2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_common.py
@@ -0,0 +1,2989 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Common utilities for evals."""
+
+import asyncio
+import base64
+import collections
+import concurrent.futures
+import contextlib
+import datetime
+import json
+import logging
+import os
+import threading
+import time
+from typing import Any, Callable, Literal, Optional, Union, cast
+import uuid
+
+from google.api_core import exceptions as api_exceptions
+import agentplatform
+from google.genai import types as genai_types
+from google.genai._api_client import BaseApiClient
+from google.genai.models import Models
+import pandas as pd
+from tqdm import tqdm
+from pydantic import ValidationError
+
+from . import _evals_constant
+from . import _evals_data_converters
+from . import _evals_metric_handlers
+from . import _evals_metric_loaders
+from . import _evals_utils
+from . import _gcs_utils
+from . import evals
+from . import types
+from . import _transformers as t
+
+logger = logging.getLogger(__name__)
+
+try:
+ import litellm
+except ImportError:
+ litellm = None
+
+
+_thread_local_data = threading.local()
+
+MAX_WORKERS = 100
+AGENT_MAX_WORKERS = 20
+CONTENT = _evals_constant.CONTENT
+PARTS = _evals_constant.PARTS
+USER_AUTHOR = _evals_constant.USER_AUTHOR
+AGENT_DATA = _evals_constant.AGENT_DATA
+
+
+@contextlib.contextmanager
+def _temp_logger_level(logger_name: str, level: int) -> None: # type: ignore[misc]
+ """Temporarily sets the level of a logger."""
+ logger_instance = logging.getLogger(logger_name)
+ original_level = logger_instance.getEffectiveLevel()
+ logger_instance.setLevel(level)
+ try:
+ yield
+ finally:
+ logger_instance.setLevel(original_level)
+
+
+def _get_api_client_with_location(
+ api_client: BaseApiClient, location: Optional[str]
+) -> BaseApiClient:
+ """Returns a new API client with the specified location."""
+ if not location or location == api_client.location:
+ return api_client
+
+ logger.info(
+ "Model endpoint location set to %s, overriding client location %s for"
+ " this API call.",
+ location,
+ api_client.location,
+ )
+ return agentplatform.Client( # type: ignore[no-any-return]
+ project=api_client.project,
+ location=location,
+ credentials=api_client._credentials,
+ http_options=api_client._http_options,
+ )._api_client
+
+
+def _get_agent_engine_instance(
+ agent_name: str, api_client: BaseApiClient
+) -> Union[types.AgentEngine, Any]:
+ """Gets or creates an agent engine instance for the current thread."""
+ if not hasattr(_thread_local_data, "agent_engine_instances"):
+ _thread_local_data.agent_engine_instances = {}
+ if agent_name not in _thread_local_data.agent_engine_instances:
+ client = agentplatform.Client(
+ project=api_client.project,
+ location=api_client.location,
+ )
+ _thread_local_data.agent_engine_instances[agent_name] = (
+ client.agent_engines.get(name=agent_name)
+ )
+ return _thread_local_data.agent_engine_instances[agent_name]
+
+
+def _generate_content_with_retry(
+ api_client: BaseApiClient,
+ model: str,
+ contents: Union[genai_types.ContentListUnion, genai_types.ContentListUnionDict],
+ config: Optional[genai_types.GenerateContentConfig] = None,
+ max_retries: int = 3,
+) -> Union[genai_types.GenerateContentResponse, dict[str, Any]]:
+ """Generates content using the model's generate_content with retries."""
+ models_module = Models(api_client_=api_client)
+
+ for attempt in range(max_retries):
+ try:
+ response = models_module.generate_content(
+ model=model,
+ contents=contents,
+ config=config,
+ )
+ if not response.candidates:
+ logger.warning(
+ "Prompt blocked. Attempt %d/%d. Feedback: %s. Prompt: %s.",
+ attempt + 1,
+ max_retries,
+ response.prompt_feedback,
+ contents,
+ )
+ if attempt == max_retries - 1:
+ feedback_dict = {}
+ if response.prompt_feedback:
+ feedback_dict = response.prompt_feedback.model_dump(
+ mode="json", exclude_none=True
+ )
+ return {
+ "error": "Prompt blocked after retries",
+ "prompt_feedback": feedback_dict,
+ }
+ else:
+ candidate = response.candidates[0]
+ if candidate.finish_reason not in (
+ genai_types.FinishReason.STOP,
+ genai_types.FinishReason.MAX_TOKENS,
+ genai_types.FinishReason.FINISH_REASON_UNSPECIFIED,
+ ):
+ logger.warning(
+ "Generate content did not finish successfully."
+ "Finish reason: %s. Finish message: %s."
+ "Retry attempt: %d/%d",
+ candidate.finish_reason,
+ candidate.finish_message,
+ attempt + 1,
+ max_retries,
+ )
+ if attempt == max_retries - 1:
+ return {
+ "error": (
+ "Generate content unsuccessful after retries:"
+ f" {candidate.finish_reason}"
+ ),
+ "finish_reason": str(candidate.finish_reason),
+ "finish_message": candidate.finish_message or "",
+ }
+ else:
+ return response
+ except api_exceptions.ResourceExhausted as e:
+ logger.warning(
+ "Resource Exhausted error on attempt %d/%d: %s. Retrying in %s"
+ " seconds...",
+ attempt + 1,
+ max_retries,
+ e,
+ 2**attempt,
+ )
+ if attempt == max_retries - 1:
+ return {"error": f"Resource exhausted after retries: {e}"}
+ time.sleep(2**attempt)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Unexpected error during generate_content on attempt %d/%d: %s",
+ attempt + 1,
+ max_retries,
+ e,
+ )
+
+ if attempt == max_retries - 1:
+ return {"error": f"Failed after retries: {e}"}
+ time.sleep(1)
+ return {"error": f"Failed to generate content after {max_retries} retries"}
+
+
+def _build_generate_content_config(
+ request_dict: Union[dict[str, Any], str],
+ global_config: Optional[genai_types.GenerateContentConfig] = None,
+) -> genai_types.GenerateContentConfig:
+ """Builds a GenerateContentConfig from the request dictionary or provided config."""
+ if global_config:
+ # If a global config is provided, apply it as a base config. Parts of
+ # the global config can be overridden by providing configs in the
+ # request.
+ merged_config_dict = global_config.model_dump(exclude_none=True)
+ else:
+ merged_config_dict = {}
+
+ if not isinstance(request_dict, dict):
+ return genai_types.GenerateContentConfig(**merged_config_dict)
+
+ for key in [
+ "system_instruction",
+ "tools",
+ "tools_config",
+ "safety_settings",
+ "labels",
+ ]:
+ if key in request_dict:
+ merged_config_dict[key] = request_dict[key]
+ if "generation_config" in request_dict and isinstance(
+ request_dict["generation_config"], dict
+ ):
+ merged_config_dict.update(request_dict["generation_config"])
+ if "labels" in request_dict:
+ merged_config_dict["labels"] = request_dict["labels"]
+
+ return genai_types.GenerateContentConfig(**merged_config_dict)
+
+
+def _extract_contents_for_inference(
+ request_dict_or_raw_text: Any,
+) -> Any:
+ """Extracts contents from a request dictionary or returns the raw text."""
+ if not request_dict_or_raw_text:
+ raise ValueError("Prompt cannot be empty.")
+ if isinstance(request_dict_or_raw_text, dict):
+ contents_for_fn = request_dict_or_raw_text.get("contents", None)
+ if not contents_for_fn:
+ raise ValueError("Contents in the request cannot be empty.")
+ return contents_for_fn
+ else:
+ return request_dict_or_raw_text
+
+
+def _eval_cases_to_dataframe(
+ eval_cases: list[types.EvalCase],
+) -> pd.DataFrame:
+ """Converts a list of EvalCase objects to a pandas DataFrame.
+
+ Each EvalCase is converted to a row in the DataFrame. Structured fields
+ like ``agent_data`` are preserved as-is (not flattened) so that downstream
+ agent execution paths can consume them directly.
+
+ Args:
+ eval_cases: The list of EvalCase objects to convert.
+
+ Returns:
+ A DataFrame with one row per EvalCase.
+ """
+ rows = []
+ for case in eval_cases:
+ row: dict[str, Any] = {}
+ if case.prompt:
+ row[_evals_constant.PROMPT] = _evals_data_converters._get_content_text(
+ case.prompt
+ )
+
+ if case.responses and len(case.responses) > 0 and case.responses[0].response:
+ row[_evals_constant.RESPONSE] = _evals_data_converters._get_content_text(
+ case.responses[0].response
+ )
+
+ if case.reference and case.reference.response:
+ row[_evals_constant.REFERENCE] = _evals_data_converters._get_content_text(
+ case.reference.response
+ )
+
+ if case.agent_data:
+ row[AGENT_DATA] = case.agent_data
+
+ if case.intermediate_events:
+ row[_evals_constant.INTERMEDIATE_EVENTS] = [
+ {CONTENT: event.content}
+ for event in case.intermediate_events
+ if event.content
+ ]
+
+ if case.conversation_history:
+ history_parts = []
+ for msg in case.conversation_history:
+ if msg.content:
+ role = msg.content.role or "user"
+ text = _evals_data_converters._get_content_text(msg.content)
+ history_parts.append(f"{role}: {text}")
+ if history_parts:
+ row[_evals_constant.CONVERSATION_HISTORY] = "\n".join(history_parts)
+
+ if case.user_scenario:
+ if case.user_scenario.starting_prompt:
+ row[_evals_constant.STARTING_PROMPT] = (
+ case.user_scenario.starting_prompt
+ )
+ if case.user_scenario.conversation_plan:
+ row[_evals_constant.CONVERSATION_PLAN] = (
+ case.user_scenario.conversation_plan
+ )
+
+ rows.append(row)
+ return pd.DataFrame(rows)
+
+
+def _extract_prompt_from_agent_data(
+ agent_data: types.evals.AgentData,
+) -> tuple[genai_types.Content, list[types.evals.AgentEvent]]:
+ """Extracts the last user message and prior events from agent_data.
+
+ The last event across all turns must be authored by ``"user"``; it is
+ treated as the current prompt that the agent should respond to.
+ Everything before it is returned as conversation history.
+
+ Args:
+ agent_data: The AgentData containing conversation turns.
+
+ Returns:
+ A tuple of ``(last_user_content, history_events)`` where
+ ``last_user_content`` is the ``Content`` of the final user event
+ and ``history_events`` is the ordered list of all prior
+ ``AgentEvent`` objects.
+
+ Raises:
+ ValueError: If ``agent_data`` has no turns, no events, or the last
+ event is not a user event.
+ """
+ if not agent_data.turns:
+ raise ValueError("agent_data must have at least one turn.")
+
+ all_events: list[types.evals.AgentEvent] = []
+ for turn in agent_data.turns:
+ if turn.events:
+ all_events.extend(turn.events)
+
+ if not all_events:
+ raise ValueError("agent_data turns contain no events.")
+
+ last_event = all_events[-1]
+ if last_event.author != USER_AUTHOR:
+ raise ValueError(
+ "agent_data must end with a user event, but the last event has"
+ f" author='{last_event.author}'."
+ )
+
+ if not last_event.content:
+ raise ValueError("The last user event in agent_data has no content.")
+
+ return last_event.content, all_events[:-1]
+
+
+def _is_n_plus_1_inference(
+ agent_data: Union[types.evals.AgentData, dict[str, Any]],
+) -> bool:
+ """Returns True if agent_data represents an N+1 inference case.
+
+ An N+1 case means the trace is incomplete: N prior conversation turns
+ exist plus 1 final user query that the agent should respond to. This
+ is detected by checking whether the very last event across all turns
+ is authored by ``"user"``.
+
+ Returns ``False`` for completed traces (last event from the agent),
+ empty traces, or invalid data.
+ """
+ if isinstance(agent_data, dict):
+ try:
+ agent_data = types.evals.AgentData.model_validate(agent_data)
+ except Exception: # pylint: disable=broad-exception-caught
+ return False
+ if not isinstance(agent_data, types.evals.AgentData):
+ return False
+ if not agent_data.turns:
+ return False
+ all_events: list[types.evals.AgentEvent] = []
+ for turn in agent_data.turns or []:
+ if turn.events:
+ all_events.extend(turn.events)
+ if not all_events:
+ return False
+ return all_events[-1].author == USER_AUTHOR
+
+
+def _extract_response_from_completed_trace(
+ agent_data: types.evals.AgentData,
+) -> list[dict[str, Any]]:
+ """Extracts all events from a completed agent trace as event dicts.
+
+ For BYOD (bring-your-own-data) use cases where the agent trace is
+ already complete, this returns all events formatted as a list of
+ dicts compatible with ``_process_single_turn_agent_response``. The
+ last element is the final agent response; preceding elements become
+ intermediate events.
+ """
+ event_dicts: list[dict[str, Any]] = []
+ for turn in agent_data.turns or []:
+ if not turn.events:
+ continue
+ for event in turn.events:
+ d: dict[str, Any] = {"author": event.author or "agent"}
+ if event.content:
+ d[CONTENT] = event.content.model_dump(exclude_none=True)
+ event_dicts.append(d)
+ return event_dicts
+
+
+def _resolve_dataset(
+ api_client: BaseApiClient,
+ dataset: Union[types.EvaluationRunDataSource, types.EvaluationDataset],
+ dest: str,
+ parsed_agent_info: Optional[types.evals.AgentInfo] = None,
+) -> types.EvaluationRunDataSource:
+ """Resolves dataset for the evaluation run."""
+ if isinstance(dataset, types.EvaluationDataset):
+ candidate_name = _get_candidate_name(dataset, parsed_agent_info)
+ eval_df = dataset.eval_dataset_df
+ if eval_df is None and dataset.eval_cases:
+ eval_df = _eval_cases_to_dataframe(dataset.eval_cases)
+
+ eval_set = _create_evaluation_set_from_dataframe(
+ api_client,
+ dest,
+ eval_df,
+ candidate_name,
+ parsed_agent_info=parsed_agent_info,
+ )
+ dataset = types.EvaluationRunDataSource(evaluation_set=eval_set.name)
+ return dataset
+
+
+def _get_default_prompt_template(
+ api_client: BaseApiClient,
+ inference_config: types.EvaluationRunInferenceConfigOrDict,
+ dataset: types.EvaluationRunDataSource,
+) -> Any:
+ """Resolves prompt template data for the evaluation run."""
+ if isinstance(inference_config, dict):
+ if inference_config.get("prompt_template"):
+ return inference_config["prompt_template"]
+ elif inference_config.prompt_template:
+ return inference_config.prompt_template
+
+ try:
+ evals_module = evals.Evals(api_client_=api_client)
+ eval_set = evals_module.get_evaluation_set(name=dataset.evaluation_set)
+ if eval_set and eval_set.evaluation_items:
+ eval_item = evals_module.get_evaluation_item(
+ name=eval_set.evaluation_items[0]
+ )
+ if (
+ eval_item
+ and eval_item.evaluation_request
+ and eval_item.evaluation_request.prompt
+ and eval_item.evaluation_request.prompt.prompt_template_data
+ ):
+ if (
+ "prompt"
+ in eval_item.evaluation_request.prompt.prompt_template_data.values
+ ):
+ return "{prompt}"
+ except Exception as e:
+ logger.warning("Failed to get prompt template from evaluation set: %s", e)
+ return None
+
+
+def _resolve_inference_configs(
+ api_client: BaseApiClient,
+ dataset: types.EvaluationRunDataSource,
+ inference_configs: Optional[
+ dict[str, types.EvaluationRunInferenceConfigOrDict]
+ ] = None,
+ parsed_agent_info: Optional[types.evals.AgentInfo] = None,
+) -> Optional[dict[str, types.EvaluationRunInferenceConfigOrDict]]:
+ """Resolves inference configs for the evaluation run."""
+ # Resolve agent config
+ if parsed_agent_info and parsed_agent_info.name:
+ if inference_configs is None:
+ inference_configs = {}
+
+ # We might have used "candidate-1" as a placeholder key in the caller,
+ # let's migrate it to the agent name, or if it doesn't exist, just create it.
+ if "candidate-1" in inference_configs:
+ inference_configs[parsed_agent_info.name] = inference_configs.pop(
+ "candidate-1"
+ )
+
+ if parsed_agent_info.name not in inference_configs:
+ inference_configs[parsed_agent_info.name] = (
+ types.EvaluationRunInferenceConfig(
+ agent_configs=parsed_agent_info.agents
+ )
+ )
+ else:
+ config = inference_configs[parsed_agent_info.name]
+ if isinstance(config, dict):
+ config["agent_configs"] = parsed_agent_info.agents
+ else:
+ config.agent_configs = parsed_agent_info.agents
+
+ # Resolve prompt template data
+ if inference_configs:
+ for inference_config in inference_configs.values():
+ prompt_template_val = (
+ inference_config.get("prompt_template")
+ if isinstance(inference_config, dict)
+ else inference_config.prompt_template
+ )
+ if not prompt_template_val:
+ default_prompt_template = _get_default_prompt_template(
+ api_client, inference_config, dataset
+ )
+ if default_prompt_template:
+ prompt_template_to_set = default_prompt_template
+ if not isinstance(
+ default_prompt_template, types.EvaluationRunPromptTemplate
+ ):
+ prompt_template_to_set = types.EvaluationRunPromptTemplate(
+ prompt_template=default_prompt_template
+ )
+ if isinstance(inference_config, dict):
+ inference_config["prompt_template"] = (
+ prompt_template_to_set.model_dump(exclude_none=True)
+ )
+ else:
+ inference_config.prompt_template = (
+ prompt_template_to_set.model_dump(exclude_none=True)
+ )
+ return inference_configs
+
+
+def _add_evaluation_run_labels(
+ labels: Optional[dict[str, str]] = None,
+ agent: Optional[str] = None,
+) -> Optional[dict[str, str]]:
+ """Adds labels to the evaluation run."""
+ if agent:
+ labels = labels or {}
+ labels["vertex-ai-evaluation-agent-engine-id"] = agent.split(
+ "reasoningEngines/"
+ )[-1]
+ return labels
+
+
+def _get_candidate_name(
+ dataset: types.EvaluationDataset,
+ parsed_agent_info: Optional[types.evals.AgentInfo] = None,
+) -> Optional[str]:
+ """Internal helper to get candidate name."""
+ if parsed_agent_info is not None and (
+ dataset.candidate_name
+ and parsed_agent_info
+ and parsed_agent_info.name
+ and dataset.candidate_name != parsed_agent_info.name
+ ):
+ logger.warning(
+ "Evaluation dataset candidate_name and agent_info.name are different. Please make sure this is intended."
+ )
+ elif dataset.candidate_name is None and parsed_agent_info:
+ return parsed_agent_info.name
+ return dataset.candidate_name or None
+
+
+def _execute_inference_concurrently(
+ api_client: BaseApiClient,
+ prompt_dataset: pd.DataFrame,
+ progress_desc: str,
+ model_or_fn: Optional[Union[str, Callable[[Any], Any]]] = None,
+ gemini_config: Optional[genai_types.GenerateContentConfig] = None,
+ inference_fn: Optional[Callable[..., Any]] = None,
+ agent_engine: Optional[Union[str, types.AgentEngine]] = None,
+ agent: Optional["LlmAgent"] = None, # type: ignore # noqa: F821
+ user_simulator_config: Optional[types.evals.UserSimulatorConfig] = None,
+) -> list[
+ Union[
+ genai_types.GenerateContentResponse,
+ dict[str, Any],
+ list[dict[str, Any]],
+ ]
+]:
+ """Internal helper to run inference with concurrency."""
+ logger.info(
+ "Generating responses for %d prompts using model or function: %s",
+ len(prompt_dataset),
+ model_or_fn,
+ )
+ responses: list[
+ Union[
+ genai_types.GenerateContentResponse,
+ dict[str, Any],
+ list[dict[str, Any]],
+ None,
+ ]
+ ] = [None] * len(prompt_dataset)
+ tasks = []
+
+ # When running with an agent and agent_data is present, we extract the
+ # prompt from the structured agent_data rather than requiring a flat
+ # prompt/request column.
+ has_agent_data = (
+ agent is not None or agent_engine is not None
+ ) and AGENT_DATA in prompt_dataset.columns
+
+ primary_prompt_column: Optional[str] = None
+ if "request" in prompt_dataset.columns:
+ primary_prompt_column = "request"
+ elif "prompt" in prompt_dataset.columns:
+ primary_prompt_column = "prompt"
+ elif "starting_prompt" in prompt_dataset.columns:
+ primary_prompt_column = "starting_prompt"
+ elif not has_agent_data:
+ raise ValueError(
+ "Dataset must contain either 'prompt', 'request', or"
+ " 'starting_prompt'."
+ f" Found: {prompt_dataset.columns.tolist()}"
+ )
+
+ max_workers = AGENT_MAX_WORKERS if agent_engine or agent else MAX_WORKERS
+ with tqdm(total=len(prompt_dataset), desc=progress_desc) as pbar:
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
+ for index, row in prompt_dataset.iterrows():
+ try:
+ if (
+ has_agent_data
+ and AGENT_DATA in row.index
+ and row.get(AGENT_DATA) is not None
+ ):
+ agent_data_obj = row[AGENT_DATA]
+ if isinstance(agent_data_obj, dict):
+ agent_data_obj = types.evals.AgentData.model_validate(
+ agent_data_obj
+ )
+ if _is_n_plus_1_inference(agent_data_obj):
+ last_user_content, _ = _extract_prompt_from_agent_data(
+ agent_data_obj
+ )
+ contents = _evals_data_converters._get_content_text(
+ last_user_content
+ )
+ else:
+ logger.info(
+ "Row %s has a completed agent trace"
+ " (last event is not from user)."
+ " Skipping inference and using existing"
+ " agent response.",
+ index,
+ )
+ responses[index] = _extract_response_from_completed_trace(
+ agent_data_obj
+ )
+ pbar.update(1)
+ continue
+ else:
+ if primary_prompt_column is None:
+ raise ValueError(
+ "Row has no agent_data and dataset has no"
+ " 'prompt', 'request', or 'starting_prompt'"
+ " column."
+ )
+ request_dict_or_raw_text = row[primary_prompt_column]
+ contents = _extract_contents_for_inference(
+ request_dict_or_raw_text
+ )
+ except ValueError as e:
+ error_message = (
+ f"Failed to extract contents for prompt at index"
+ f" {index}: {e}. Skipping prompt."
+ )
+ logger.error(error_message)
+ responses[index] = {"error": error_message}
+ pbar.update(1)
+ continue
+
+ if agent_engine or agent:
+
+ def agent_run_wrapper( # type: ignore[no-untyped-def]
+ row_arg,
+ contents_arg,
+ agent_engine_arg,
+ agent_arg,
+ inference_fn_arg,
+ api_client_arg,
+ user_simulator_config_arg,
+ ) -> Any:
+ if agent_engine_arg:
+ if isinstance(agent_engine_arg, str):
+ agent_engine_instance = _get_agent_engine_instance(
+ agent_engine_arg, api_client_arg
+ )
+ else:
+ agent_engine_instance = agent_engine_arg
+
+ return inference_fn_arg(
+ row=row_arg,
+ contents=contents_arg,
+ agent_engine=agent_engine_instance,
+ )
+ elif agent_arg:
+ return inference_fn_arg(
+ row=row_arg,
+ contents=contents_arg,
+ user_simulator_config=user_simulator_config_arg,
+ agent=agent_arg,
+ )
+
+ future = executor.submit(
+ agent_run_wrapper,
+ row,
+ contents,
+ agent_engine,
+ agent,
+ inference_fn,
+ api_client,
+ user_simulator_config,
+ )
+ elif isinstance(model_or_fn, str):
+ generation_content_config = _build_generate_content_config(
+ request_dict_or_raw_text,
+ gemini_config,
+ )
+ future = executor.submit(
+ inference_fn,
+ api_client=api_client,
+ model=model_or_fn,
+ contents=contents,
+ config=generation_content_config,
+ )
+ else:
+ future = executor.submit(model_or_fn, contents)
+ future.add_done_callback(lambda _: pbar.update(1))
+ tasks.append((future, index))
+
+ for future, index in tasks:
+ try:
+ result = future.result()
+ responses[index] = result
+ except Exception as e:
+ logger.error(
+ "Error processing prompt at index %d: %s",
+ index,
+ e,
+ )
+ responses[index] = {"error": f"Inference task failed: {e}"}
+ return responses # type: ignore[return-value]
+
+
+def _run_gemini_inference(
+ api_client: BaseApiClient,
+ model: str,
+ prompt_dataset: pd.DataFrame,
+ config: Optional[genai_types.GenerateContentConfig] = None,
+) -> list[
+ Union[
+ genai_types.GenerateContentResponse,
+ dict[str, Any],
+ list[dict[str, Any]],
+ ]
+]:
+ """Internal helper to run inference using Gemini model with concurrency."""
+ return _execute_inference_concurrently(
+ api_client=api_client,
+ model_or_fn=model,
+ prompt_dataset=prompt_dataset,
+ progress_desc="Gemini Inference",
+ gemini_config=config,
+ inference_fn=_generate_content_with_retry,
+ )
+
+
+def _run_custom_inference(
+ model_fn: Callable[[Any], Any],
+ prompt_dataset: pd.DataFrame,
+) -> list[Any]:
+ """Internal helper to run inference using a custom function with concurrency."""
+ return _execute_inference_concurrently(
+ api_client=None,
+ model_or_fn=model_fn,
+ prompt_dataset=prompt_dataset,
+ progress_desc="Custom Inference",
+ )
+
+
+def _convert_prompt_row_to_litellm_messages(
+ row: pd.Series,
+) -> list[dict[str, Any]]:
+ """Converts a DataFrame row into LiteLLM's messages format by detecting the input schema."""
+ messages: list[dict[str, Any]] = []
+ row_dict = row.to_dict()
+
+ # Case 1: The row is an OpenAI request body itself.
+ if "messages" in row_dict and isinstance(row_dict.get("messages"), list):
+ return row_dict["messages"] # type: ignore[no-any-return]
+
+ # Case 2: The row contains a 'request' key with an OpenAI request body.
+ elif "request" in row_dict and isinstance(row_dict.get("request"), dict):
+ request_body = row_dict["request"]
+ if "messages" in request_body and isinstance(
+ request_body.get("messages"), list
+ ):
+ return request_body["messages"] # type: ignore[no-any-return]
+
+ # Case 3: The 'request' key is in Gemini 'contents' format.
+ elif "contents" in request_body and isinstance(
+ request_body.get("contents"), list
+ ):
+ for content in request_body["contents"]:
+ role = content.get("role", USER_AUTHOR)
+ text_parts = [part.get("text", "") for part in content.get("parts", [])]
+ messages.append({"role": role, "content": " ".join(text_parts)})
+ return messages
+
+ # Case 4: Fallback to a simple 'prompt' key with a raw string.
+ elif "prompt" in row_dict and isinstance(row_dict.get("prompt"), str):
+ return [{"role": USER_AUTHOR, "content": row_dict["prompt"]}]
+
+ raise ValueError(
+ "Could not determine prompt/messages format from input row. Expected"
+ " OpenAI request body with a 'messages' key, or a 'request' key with"
+ " OpenAI request body, or Gemini request body with a 'contents' key, or"
+ f" a 'prompt' key with a raw string. Found keys: {list(row_dict.keys())}"
+ )
+
+
+def _call_litellm_completion(
+ model: str, messages: list[dict[str, Any]]
+) -> dict[str, Any]:
+ """Wrapper for a single litellm.completion call."""
+ try:
+ response = litellm.completion(model=model, messages=messages)
+ return response.model_dump() # type: ignore[no-any-return]
+ except Exception as e:
+ logger.error("LiteLLM completion failed for model %s: %s", model, e)
+ return {"error": str(e)}
+
+
+def _run_litellm_inference(
+ model: str, prompt_dataset: pd.DataFrame
+) -> list[Optional[dict[str, Any]]]:
+ """Runs inference using LiteLLM with concurrency."""
+ logger.info(
+ "Generating responses for %d prompts using LiteLLM for third party model: %s",
+ len(prompt_dataset),
+ model,
+ )
+ responses: list[Optional[dict[str, Any]]] = [None] * len(prompt_dataset)
+ tasks = []
+
+ with tqdm(total=len(prompt_dataset), desc=f"LiteLLM Inference ({model})") as pbar:
+ with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
+ for index, row in prompt_dataset.iterrows():
+ messages = _convert_prompt_row_to_litellm_messages(row)
+ future = executor.submit(
+ _call_litellm_completion, model=model, messages=messages
+ )
+ future.add_done_callback(lambda _: pbar.update(1))
+ tasks.append((future, index))
+
+ for future, index in tasks:
+ try:
+ result = future.result()
+ responses[index] = result
+ except Exception as e:
+ logger.error("Error processing prompt at index %d: %s", index, e)
+ responses[index] = {"error": f"LiteLLM task failed: {e}"}
+
+ return responses
+
+
+def _is_litellm_vertex_maas_model(model: str) -> bool:
+ """Checks if the model is a Vertex MAAS model to be handled by LiteLLM."""
+ return any(
+ model.startswith(prefix)
+ for prefix in _evals_constant.SUPPORTED_VERTEX_MAAS_MODEL_PREFIXES
+ )
+
+
+def _is_litellm_model(model: str) -> bool:
+ """Checks if the model name corresponds to a valid LiteLLM model name."""
+ if litellm is None:
+ return False
+
+ try:
+ litellm.get_llm_provider(model)
+ return True
+ except ValueError:
+ return False
+
+
+def _is_gemini_model(model: str) -> bool:
+ """Checks if the model name corresponds to a Gemini/Vertex AI model."""
+ return (
+ model.startswith("gemini-")
+ or model.startswith("projects/")
+ or model.startswith("models/")
+ or model.startswith("publishers/")
+ or model.startswith("tunedModels/")
+ )
+
+
+def _run_inference_internal(
+ api_client: BaseApiClient,
+ model: Union[Callable[[Any], Any], str],
+ prompt_dataset: pd.DataFrame,
+ config: Optional[genai_types.GenerateContentConfig] = None,
+) -> pd.DataFrame:
+ """Runs inference on a given dataset using the specified model or function."""
+
+ if isinstance(model, str) and _is_gemini_model(model):
+ if (
+ "prompt" not in prompt_dataset.columns
+ and "request" not in prompt_dataset.columns
+ and "starting_prompt" not in prompt_dataset.columns
+ ):
+ raise ValueError(
+ "Prompt dataset for Gemini model must contain either 'prompt',"
+ " 'request' or 'starting_prompt' column for inference. "
+ f"Found columns: {prompt_dataset.columns.tolist()}"
+ )
+
+ logger.info("Running inference with Gemini model name: %s", model)
+ raw_responses = _run_gemini_inference(
+ api_client=api_client,
+ model=model,
+ prompt_dataset=prompt_dataset,
+ config=config,
+ )
+ processed_responses = []
+ for resp_item in raw_responses:
+ if isinstance(resp_item, genai_types.GenerateContentResponse):
+ text_response = resp_item.text
+ processed_responses.append(
+ text_response
+ if text_response is not None
+ else json.dumps({"error": "Empty response text"})
+ )
+ elif isinstance(resp_item, dict) and "error" in resp_item:
+ processed_responses.append(json.dumps(resp_item))
+ else:
+ error_payload = {
+ "error": "Unexpected response type from Gemini inference",
+ "response_type": str(type(resp_item)),
+ "details": str(resp_item),
+ }
+ processed_responses.append(json.dumps(error_payload))
+ responses = processed_responses
+ elif callable(model):
+ logger.info("Running inference with custom callable function.")
+ custom_responses_raw = _run_custom_inference(
+ model_fn=model, prompt_dataset=prompt_dataset
+ )
+ processed_custom_responses = []
+ for resp_item in custom_responses_raw:
+ if isinstance(resp_item, str):
+ processed_custom_responses.append(resp_item)
+ elif isinstance(resp_item, dict) and "error" in resp_item:
+ processed_custom_responses.append(json.dumps(resp_item))
+ else:
+ try:
+ processed_custom_responses.append(json.dumps(resp_item))
+ except TypeError:
+ processed_custom_responses.append(str(resp_item))
+ responses = processed_custom_responses
+ elif isinstance(model, str):
+ if litellm is None:
+ raise ImportError(
+ "The 'litellm' library is required to use this model."
+ " Please install it using 'pip install"
+ " google-cloud-aiplatform[evaluation]'."
+ )
+
+ processed_model_id = model
+ if model.startswith("vertex_ai/"):
+ # Already correctly prefixed for LiteLLM's Vertex AI provider
+ pass
+ elif _is_litellm_vertex_maas_model(model):
+ processed_model_id = f"vertex_ai/{model}"
+ logger.info(
+ "Detected Vertex AI Model Garden managed MaaS model. "
+ "Using LiteLLM ID: %s",
+ processed_model_id,
+ )
+ elif _is_litellm_model(model):
+ # Other LiteLLM supported model
+ logger.info("Running inference with LiteLLM for model: %s", model)
+ else:
+ # Unsupported model string
+ raise TypeError(
+ f"Unsupported string model name: {model}. Expecting a Gemini model"
+ " name (e.g., 'gemini-2.5-pro', 'projects/.../models/...') or a"
+ " LiteLLM supported model name (e.g., 'openai/gpt-4o')."
+ " If using a third-party model via LiteLLM, ensure the"
+ " necessary environment variables are set (e.g., for OpenAI:"
+ " `os.environ['OPENAI_API_KEY'] = 'Your API Key'`). See"
+ " LiteLLM documentation for details:"
+ " https://docs.litellm.ai/docs/set_keys#environment-variables"
+ )
+
+ logger.info("Running inference via LiteLLM for model: %s", processed_model_id)
+ raw_responses = _run_litellm_inference( # type: ignore[assignment]
+ model=processed_model_id, prompt_dataset=prompt_dataset
+ )
+ processed_llm_responses = []
+ for response_dict in raw_responses:
+ if not isinstance(response_dict, dict):
+ processed_llm_responses.append(
+ json.dumps(
+ {
+ "error": "Invalid LiteLLM response format",
+ "details": str(response_dict),
+ }
+ )
+ )
+ continue
+
+ if "error" in response_dict:
+ processed_llm_responses.append(json.dumps(response_dict))
+ continue
+
+ if (
+ "choices" in response_dict
+ and isinstance(response_dict["choices"], list)
+ and len(response_dict["choices"]) > 0
+ ):
+ first_choice = response_dict["choices"][0]
+ if "message" in first_choice and isinstance(
+ first_choice["message"], dict
+ ):
+ message = first_choice["message"]
+ if "content" in message and isinstance(message["content"], str):
+ processed_llm_responses.append(message["content"])
+ else:
+ processed_llm_responses.append(
+ json.dumps(
+ {
+ "error": "LiteLLM response missing 'content' in message",
+ "details": response_dict,
+ }
+ )
+ )
+ else:
+ processed_llm_responses.append(
+ json.dumps(
+ {
+ "error": "LiteLLM response missing 'message' in first choice",
+ "details": response_dict,
+ }
+ )
+ )
+ else:
+ processed_llm_responses.append(
+ json.dumps(
+ {
+ "error": "LiteLLM response missing 'choices'",
+ "details": response_dict,
+ }
+ )
+ )
+ responses = processed_llm_responses
+ else:
+ raise TypeError(
+ f"Unsupported model type: {type(model)}. Expecting string (model"
+ " name) or Callable."
+ )
+
+ if len(responses) != len(prompt_dataset):
+ raise RuntimeError(
+ "Critical prompt/response count mismatch: %d prompts vs %d"
+ " responses. This indicates an issue in response collection."
+ % (len(prompt_dataset), len(responses))
+ )
+
+ results_df_responses_only = pd.DataFrame(
+ {
+ _evals_constant.RESPONSE: responses,
+ }
+ )
+
+ prompt_dataset_indexed = prompt_dataset.reset_index(drop=True)
+
+ # Drop existing 'response' column to prevent duplicate column names when
+ # re-running inference on a dataset that already has responses.
+ if _evals_constant.RESPONSE in prompt_dataset_indexed.columns:
+ logger.warning(
+ "A column named '%s' already exists in the prompt dataset. "
+ "The existing column will be dropped and replaced with the new "
+ "inference results.",
+ _evals_constant.RESPONSE,
+ )
+ prompt_dataset_indexed = prompt_dataset_indexed.drop(
+ columns=[_evals_constant.RESPONSE]
+ )
+
+ results_df_responses_only_indexed = results_df_responses_only.reset_index(drop=True)
+
+ results_df = pd.concat(
+ [prompt_dataset_indexed, results_df_responses_only_indexed], axis=1
+ )
+
+ return results_df
+
+
+async def _run_adk_user_simulation(
+ row: pd.Series,
+ agent: "LlmAgent", # type: ignore # noqa: F821
+ config: Optional[types.evals.UserSimulatorConfig] = None,
+) -> list[dict[str, Any]]:
+ """Runs a multi-turn user simulation using ADK's EvaluationGenerator."""
+ # Lazy-import ADK dependencies to avoid top-level import failures when
+ # google-adk is not installed.
+ from google.adk.evaluation.conversation_scenarios import ConversationScenario
+ from google.adk.evaluation.eval_case import SessionInput as ADK_SessionInput
+ from google.adk.evaluation.evaluation_generator import EvaluationGenerator
+ from google.adk.evaluation.simulation.llm_backed_user_simulator import (
+ LlmBackedUserSimulator,
+ )
+ from google.adk.evaluation.simulation.llm_backed_user_simulator import (
+ LlmBackedUserSimulatorConfig,
+ )
+
+ starting_prompt = row.get("starting_prompt")
+ conversation_plan = row.get("conversation_plan")
+ user_persona = "EVALUATOR"
+
+ if not starting_prompt or not conversation_plan:
+ raise ValueError(
+ "User simulation requires 'starting_prompt' and 'conversation_plan'"
+ " columns."
+ )
+
+ scenario = ConversationScenario(
+ starting_prompt=starting_prompt,
+ conversation_plan=conversation_plan,
+ user_persona=user_persona,
+ )
+
+ user_simulator_kwargs: dict[str, Any] = {}
+ if config:
+ if config.model_name:
+ user_simulator_kwargs["model"] = config.model_name
+ if config.model_configuration is not None:
+ user_simulator_kwargs["model_configuration"] = (
+ config.model_configuration.model_dump(exclude_none=True)
+ )
+ if config.max_turn is not None:
+ user_simulator_kwargs["max_allowed_invocations"] = config.max_turn
+
+ user_simulator_config = LlmBackedUserSimulatorConfig(**user_simulator_kwargs)
+ user_simulator = LlmBackedUserSimulator(
+ conversation_scenario=scenario, config=user_simulator_config
+ )
+
+ try:
+ initial_session = _get_session_inputs(row)
+ app_name = initial_session.app_name or "user_simulation_app"
+ user_id = initial_session.user_id or "user_simulation_default_user"
+ state = initial_session.state or {}
+ except (KeyError, TypeError, ValueError):
+ app_name = "user_simulation_app"
+ user_id = "user_simulation_default_user"
+ state = {}
+
+ invocations = await EvaluationGenerator._generate_inferences_from_root_agent( # pylint: disable=protected-access
+ root_agent=agent,
+ user_simulator=user_simulator,
+ reset_func=getattr(agent, "reset_data", None),
+ initial_session=ADK_SessionInput(
+ app_name=app_name,
+ user_id=user_id,
+ state=state,
+ ),
+ )
+
+ turns = []
+ for i, invocation in enumerate(invocations):
+ events = []
+ if invocation.user_content:
+ events.append(
+ {
+ "author": "user",
+ "content": invocation.user_content.model_dump(
+ mode="json", exclude_none=True
+ ),
+ "event_time": datetime.datetime.fromtimestamp(
+ invocation.creation_timestamp, tz=datetime.timezone.utc
+ ),
+ }
+ )
+ if invocation.intermediate_data:
+ if (
+ hasattr(invocation.intermediate_data, "invocation_events")
+ and invocation.intermediate_data.invocation_events
+ ):
+ for ie in invocation.intermediate_data.invocation_events:
+ events.append(
+ {
+ "author": ie.author,
+ "content": (
+ ie.content.model_dump(mode="json", exclude_none=True)
+ if ie.content
+ else None
+ ),
+ "event_time": datetime.datetime.fromtimestamp(
+ invocation.creation_timestamp, tz=datetime.timezone.utc
+ ),
+ }
+ )
+ elif hasattr(invocation.intermediate_data, "tool_uses"):
+ for tool_call in invocation.intermediate_data.tool_uses:
+ events.append(
+ {
+ "author": "tool_call",
+ "content": tool_call.model_dump(
+ mode="json", exclude_none=True
+ ),
+ "event_time": datetime.datetime.fromtimestamp(
+ invocation.creation_timestamp, tz=datetime.timezone.utc
+ ),
+ }
+ )
+
+ if invocation.final_response:
+ events.append(
+ {
+ "author": "agent",
+ "content": invocation.final_response.model_dump(
+ mode="json", exclude_none=True
+ ),
+ "event_time": datetime.datetime.fromtimestamp(
+ invocation.creation_timestamp, tz=datetime.timezone.utc
+ ),
+ }
+ )
+
+ turns.append(
+ {
+ "turn_index": i,
+ "turn_id": invocation.invocation_id or str(uuid.uuid4()),
+ "events": events,
+ }
+ )
+
+ return turns
+
+
+def _apply_prompt_template(
+ df: pd.DataFrame, prompt_template: types.PromptTemplate
+) -> None:
+ """Applies a prompt template to a DataFrame.
+
+ The DataFrame is expected to have columns corresponding to the variables
+ in the prompt_template_str. The result will be in a new 'request' column.
+
+ Args:
+ df: The input DataFrame to modify.
+ prompt_template: The prompt template to apply.
+
+ Returns:
+ None. The DataFrame is modified in place.
+ """
+ missing_vars = [var for var in prompt_template.variables if var not in df.columns]
+ if missing_vars:
+ raise ValueError(
+ "Missing columns in DataFrame for prompt template variables:"
+ f" {', '.join(missing_vars)}. Available columns:"
+ f" {', '.join(df.columns.tolist())}"
+ )
+
+ if "prompt" in df.columns:
+ logger.info(
+ "Templated prompts stored in 'request' and will be used for"
+ " inference.Original 'prompt' column is kept but not used for"
+ " inference."
+ )
+ elif "prompt" not in df.columns and "request" in df.columns:
+ logger.info("The 'request' column will be replaced with templated prompts.")
+
+ templated_prompts = []
+ for _, row in df.iterrows():
+ templated_prompts.append(prompt_template.assemble(**row.to_dict()))
+
+ df["request"] = templated_prompts
+
+
+def _load_dataframe(
+ api_client: BaseApiClient, src: Union[str, pd.DataFrame]
+) -> pd.DataFrame:
+ """Loads and prepares the prompt dataset for inference."""
+ logger.info("Loading prompt dataset from: %s", src)
+ try:
+ loader = _evals_utils.EvalDatasetLoader(api_client=api_client)
+ dataset_list_of_dicts = loader.load(src)
+ if not dataset_list_of_dicts:
+ raise ValueError("Prompt dataset 'prompt_dataset' must not be empty.")
+ return pd.DataFrame(dataset_list_of_dicts)
+ except Exception as e:
+ logger.error("Failed to load prompt dataset from source: %s. Error: %s", src, e)
+ raise e
+
+
+def _execute_inference(
+ *,
+ api_client: BaseApiClient,
+ src: Union[str, pd.DataFrame],
+ model: Optional[Union[Callable[[Any], Any], str]] = None,
+ agent_engine: Optional[Union[str, types.AgentEngine]] = None,
+ agent: Optional["LlmAgent"] = None, # type: ignore # noqa: F821
+ dest: Optional[str] = None,
+ config: Optional[genai_types.GenerateContentConfig] = None,
+ prompt_template: Optional[Union[str, types.PromptTemplateOrDict]] = None,
+ location: Optional[str] = None,
+ user_simulator_config: Optional[types.evals.UserSimulatorConfig] = None,
+ allow_cross_region_model: bool = False,
+) -> pd.DataFrame:
+ """Executes inference on a given dataset using the specified model.
+
+ Args:
+ api_client: The API client.
+ src: The source of the dataset. Can be a string (path to a local file, a
+ GCS path, or a BigQuery table) or a Pandas DataFrame.
+ model: The model to use for inference. Can be a callable function or a
+ string representing a model.
+ agent_engine: The agent engine to use for inference. Can be a resource
+ name string or an `AgentEngine` instance.
+ agent: The local agent to use for inference. Can be an ADK agent instance.
+ dest: The destination to save the inference results. Can be a string
+ representing a file path or a GCS URI.
+ config: The generation configuration for the model.
+ prompt_template: The prompt template to use for inference.
+ location: The location to use for the inference. If not specified, the
+ location configured in the client will be used.
+ user_simulator_config: The configuration for the user simulator in
+ multi-turn agent scraping.
+
+ Returns:
+ A pandas DataFrame containing the inference results.
+ """
+ if not api_client:
+ raise ValueError("'api_client' instance must be provided.")
+ if location:
+ api_client = _get_api_client_with_location(api_client, location)
+
+ if sum(x is not None for x in [model, agent_engine, agent]) != 1:
+ raise ValueError(
+ "Exactly one of model, agent_engine, or agent must be provided."
+ )
+
+ prompt_dataset = _load_dataframe(api_client, src)
+ if prompt_template:
+ logger.info("Applying prompt template...")
+ if isinstance(prompt_template, str):
+ prompt_template = types.PromptTemplate(text=prompt_template)
+ elif isinstance(prompt_template, dict):
+ prompt_template = types.PromptTemplate.model_validate(prompt_template)
+
+ _apply_prompt_template(prompt_dataset, prompt_template)
+
+ if model:
+ start_time = time.time()
+ logger.debug("Starting inference process ...")
+ results_df = _run_inference_internal(
+ api_client=api_client,
+ model=model,
+ prompt_dataset=prompt_dataset,
+ config=config,
+ )
+ end_time = time.time()
+ logger.info("Inference completed in %.2f seconds.", end_time - start_time)
+
+ candidate_name = None
+ if isinstance(model, str):
+ candidate_name = model
+ elif callable(model):
+ candidate_name = getattr(model, "__name__", None)
+
+ results_df = _drop_empty_columns(results_df)
+ evaluation_dataset = types.EvaluationDataset(
+ eval_dataset_df=results_df,
+ candidate_name=candidate_name,
+ )
+ elif agent_engine or agent:
+ candidate_name = None
+ if agent_engine:
+ candidate_name = "agent_engine_0"
+ elif agent:
+ agent_config = types.evals.AgentConfig.from_agent(agent)
+ candidate_name = agent_config.agent_id or "agent_0"
+
+ if (
+ agent_engine
+ and not isinstance(agent_engine, str)
+ and not (
+ hasattr(agent_engine, "api_client")
+ and type(agent_engine).__name__ == "AgentEngine"
+ )
+ ):
+ raise TypeError(
+ f"Unsupported agent_engine type: {type(agent_engine)}. Expecting a"
+ " string (agent engine resource name in"
+ " 'projects/{project_id}/locations/{location_id}/reasoningEngines/{reasoning_engine_id}'"
+ " format) or a types.AgentEngine instance."
+ )
+ if (
+ _evals_constant.INTERMEDIATE_EVENTS in prompt_dataset.columns
+ or _evals_constant.RESPONSE in prompt_dataset.columns
+ ):
+ raise ValueError(
+ "The eval dataset provided for agent run should not contain"
+ f" '{_evals_constant.INTERMEDIATE_EVENTS}' or"
+ f" '{_evals_constant.RESPONSE}' columns, as these columns will be"
+ " generated by the agent run."
+ )
+ start_time = time.time()
+ logger.debug("Starting Agent Run process ...")
+ results_df = _run_agent_internal(
+ api_client=api_client,
+ agent_engine=agent_engine,
+ agent=agent,
+ prompt_dataset=prompt_dataset,
+ user_simulator_config=user_simulator_config,
+ allow_cross_region_model=allow_cross_region_model,
+ )
+ end_time = time.time()
+ logger.info("Agent Run completed in %.2f seconds.", end_time - start_time)
+
+ results_df = _drop_empty_columns(results_df)
+ evaluation_dataset = types.EvaluationDataset(
+ eval_dataset_df=results_df,
+ candidate_name=candidate_name,
+ )
+ else:
+ raise ValueError("Either model, agent_engine or agent must be provided.")
+
+ if dest:
+ file_name = "inference_results.jsonl" if model else "agent_run_results.jsonl"
+ is_gcs_path = dest.startswith(_gcs_utils.GCS_PREFIX)
+
+ if is_gcs_path:
+ full_dest_path = os.path.join(dest, file_name)
+ else:
+ os.makedirs(dest, exist_ok=True)
+ full_dest_path = os.path.join(dest, file_name)
+
+ logger.info("Saving inference / agent run results to: %s", full_dest_path)
+ try:
+ if is_gcs_path:
+ _gcs_utils.GcsUtils(api_client=api_client).upload_dataframe(
+ df=results_df,
+ gcs_destination_blob_path=full_dest_path,
+ file_type="jsonl",
+ )
+ logger.info("Results saved to GCS: %s", full_dest_path)
+ evaluation_dataset.gcs_source = genai_types.GcsSource(
+ uris=[full_dest_path]
+ )
+ else:
+ results_df.to_json(full_dest_path, orient="records", lines=True)
+ logger.info("Results saved locally to: %s", full_dest_path)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error("Failed to save results to %s. Error: %s", full_dest_path, e)
+
+ return evaluation_dataset
+
+
+def _get_dataset_source(
+ ds_item: types.EvaluationDataset,
+) -> Union[str, pd.DataFrame]:
+ """Returns the source of the dataset, either a DataFrame, GCS URI, or BigQuery URI."""
+ if ds_item.eval_dataset_df is not None:
+ return ds_item.eval_dataset_df
+ elif ds_item.gcs_source is not None and ds_item.gcs_source.uris:
+ if len(ds_item.gcs_source.uris) > 1:
+ logger.warning(
+ "Multiple GCS URIs in GcsSource. Using the first one: %s",
+ ds_item.gcs_source.uris[0],
+ )
+ return ds_item.gcs_source.uris[0]
+ elif ds_item.bigquery_source is not None and ds_item.bigquery_source.input_uri:
+ return ds_item.bigquery_source.input_uri
+ else:
+ raise ValueError(
+ "EvaluationDataset item has no valid source"
+ " (eval_dataset_df, gcs_source with uris, or bigquery_source with"
+ " input_uri)."
+ )
+
+
+def _resolve_dataset_inputs(
+ dataset: list[types.EvaluationDataset],
+ dataset_schema: Optional[Literal["GEMINI", "FLATTEN", "OPENAI"]],
+ loader: "_evals_utils.EvalDatasetLoader",
+ agent_info: Optional[types.evals.AgentInfo] = None,
+) -> tuple[types.EvaluationDataset, int]:
+ """Loads and processes single or multiple datasets for evaluation.
+
+ Args:
+ dataset: The dataset(s) to process. Can be a single EvaluationDataset or a
+ list of them.
+ dataset_schema: The schema to use for the dataset(s). If None, it will be
+ auto-detected.
+ loader: An instance of EvalDatasetLoader to load data.
+ agent_info: The agent info of the agent under evaluation.
+
+ Returns:
+ A tuple containing:
+ - processed_eval_dataset: The processed EvaluationDataset containing
+ evaluation cases.
+ - num_response_candidates: The number of response candidates.
+ """
+ if not dataset:
+ raise ValueError("Input dataset list cannot be empty.")
+
+ num_response_candidates = len(dataset)
+ datasets_to_process = dataset
+ logger.info("Processing %s dataset(s).", num_response_candidates)
+
+ if len(datasets_to_process) == 1 and datasets_to_process[0].eval_cases:
+ return datasets_to_process[0], 1
+
+ parsed_evaluation_datasets: list[types.EvaluationDataset] = []
+
+ for i, ds_item in enumerate(datasets_to_process):
+ if not isinstance(ds_item, types.EvaluationDataset):
+ logger.error(
+ "Unexpected item type in dataset list at index %d: %s. Expected"
+ " types.EvaluationDataset.",
+ i,
+ type(ds_item),
+ )
+ raise TypeError(
+ f"Item at index {i} is not an EvaluationDataset: {type(ds_item)}"
+ )
+
+ if ds_item.eval_cases:
+ logger.info("Dataset %d already contains eval_cases.", i)
+ parsed_evaluation_datasets.append(ds_item)
+ continue
+
+ ds_source_for_loader = _get_dataset_source(ds_item)
+ current_loaded_data = loader.load(ds_source_for_loader)
+
+ if dataset_schema:
+ current_schema = _evals_data_converters.EvalDatasetSchema(dataset_schema)
+ else:
+ current_schema = _evals_data_converters.auto_detect_dataset_schema( # type: ignore[assignment]
+ current_loaded_data
+ )
+
+ logger.info(
+ "Dataset %d: Schema: %s. Using %s converter.",
+ i,
+ current_schema,
+ _evals_data_converters.get_dataset_converter(
+ current_schema
+ ).__class__.__name__,
+ )
+ converter = _evals_data_converters.get_dataset_converter(current_schema)
+ parsed_evaluation_datasets.append(converter.convert(current_loaded_data))
+
+ processed_eval_dataset = _evals_data_converters.merge_evaluation_datasets(
+ datasets=parsed_evaluation_datasets,
+ agent_info=agent_info,
+ )
+
+ if not processed_eval_dataset.eval_cases:
+ raise ValueError("No evaluation cases found in the dataset.")
+ return processed_eval_dataset, num_response_candidates
+
+
+def _resolve_evaluation_run_metrics(
+ metrics: Union[list[types.EvaluationRunMetric], list[types.Metric]], api_client: Any
+) -> list[types.EvaluationRunMetric]:
+ """Resolves a list of evaluation run metric instances, loading RubricMetric if necessary."""
+ if not metrics:
+ return []
+ resolved_metrics_list = []
+ for metric_instance in metrics:
+ if isinstance(metric_instance, types.EvaluationRunMetric):
+ resolved_metrics_list.append(metric_instance)
+ elif isinstance(
+ metric_instance, _evals_metric_loaders.LazyLoadedPrebuiltMetric
+ ):
+ try:
+ resolved_metric = metric_instance.resolve(api_client=api_client)
+ if resolved_metric.name:
+ resolved_metrics_list.append(
+ types.EvaluationRunMetric(
+ metric=resolved_metric.name,
+ metric_config=types.UnifiedMetric(
+ predefined_metric_spec=genai_types.PredefinedMetricSpec(
+ metric_spec_name=resolved_metric.name,
+ )
+ ),
+ )
+ )
+ except Exception as e:
+ logger.error(
+ "Failed to resolve RubricMetric %s@%s: %s",
+ metric_instance.name,
+ metric_instance.version,
+ e,
+ )
+ raise
+ elif isinstance(metric_instance, types.Metric):
+ config_dict = t.t_metrics([metric_instance])[0]
+ res_name = getattr(metric_instance, "metric_resource_name", None)
+ resolved_metrics_list.append(
+ types.EvaluationRunMetric(
+ metric=metric_instance.name,
+ metric_config=config_dict if config_dict else None,
+ metric_resource_name=res_name,
+ )
+ )
+ else:
+ try:
+ metric_name_str = str(metric_instance)
+ lazy_metric_instance = getattr(
+ _evals_metric_loaders.RubricMetric, metric_name_str.upper()
+ )
+ if isinstance(
+ lazy_metric_instance, _evals_metric_loaders.LazyLoadedPrebuiltMetric
+ ):
+ resolved_metric = lazy_metric_instance.resolve(
+ api_client=api_client
+ )
+ if resolved_metric.name:
+ resolved_metrics_list.append(
+ types.EvaluationRunMetric(
+ metric=resolved_metric.name,
+ metric_config=types.UnifiedMetric(
+ predefined_metric_spec=genai_types.PredefinedMetricSpec(
+ metric_spec_name=resolved_metric.name,
+ )
+ ),
+ )
+ )
+ else:
+ raise TypeError(
+ f"RubricMetric.{metric_name_str.upper()} cannot be resolved."
+ )
+ except AttributeError as exc:
+ raise TypeError(
+ "Unsupported metric type or invalid RubricMetric name:"
+ f" {metric_instance}"
+ ) from exc
+ return resolved_metrics_list
+
+
+def _resolve_metrics(
+ metrics: list[types.Metric], api_client: Any
+) -> list[types.Metric]:
+ """Resolves a list of metric instances, loading RubricMetric if necessary."""
+ resolved_metrics_list = []
+ for metric_instance in metrics:
+ if isinstance(metric_instance, _evals_metric_loaders.LazyLoadedPrebuiltMetric):
+ try:
+ resolved_metrics_list.append(
+ metric_instance.resolve(api_client=api_client)
+ )
+ except Exception as e:
+ logger.error(
+ "Failed to resolve RubricMetric %s@%s: %s",
+ metric_instance.name,
+ metric_instance.version,
+ e,
+ )
+ raise
+ elif isinstance(metric_instance, types.Metric):
+ resolved_metrics_list.append(metric_instance)
+ else:
+ try:
+ metric_name_str = str(metric_instance)
+ lazy_metric_instance = getattr(
+ _evals_metric_loaders.RubricMetric, metric_name_str.upper()
+ )
+ if isinstance(
+ lazy_metric_instance, _evals_metric_loaders.LazyLoadedPrebuiltMetric
+ ):
+ resolved_metrics_list.append(
+ lazy_metric_instance.resolve(api_client=api_client)
+ )
+ else:
+ raise TypeError(
+ f"RubricMetric.{metric_name_str.upper()} cannot be resolved."
+ )
+ except AttributeError as exc:
+ raise TypeError(
+ "Unsupported metric type or invalid RubricMetric name:"
+ f" {metric_instance}"
+ ) from exc
+ return resolved_metrics_list
+
+
+def _execute_evaluation( # type: ignore[no-untyped-def]
+ *,
+ api_client: Any,
+ dataset: Union[types.EvaluationDataset, list[types.EvaluationDataset]],
+ metrics: list[types.Metric],
+ dataset_schema: Optional[Literal["GEMINI", "FLATTEN", "OPENAI"]] = None,
+ dest: Optional[str] = None,
+ location: Optional[str] = None,
+ evaluation_service_qps: Optional[float] = None,
+ **kwargs,
+) -> types.EvaluationResult:
+ """Evaluates a dataset using the provided metrics.
+
+ Args:
+ api_client: The API client.
+ dataset: The dataset to evaluate.
+ metrics: The metrics to evaluate the dataset against.
+ dataset_schema: The schema of the dataset.
+ dest: The destination to save the evaluation results.
+ location: The location to use for the evaluation. If not specified, the
+ location configured in the client will be used.
+ evaluation_service_qps: The rate limit (queries per second) for calls
+ to the evaluation service. Defaults to 10. Increase this value if
+ your project has a higher EvaluateInstances API quota.
+ **kwargs: Extra arguments to pass to evaluation, such as `agent_info`.
+
+ Returns:
+ The evaluation result.
+ """
+
+ if location:
+ api_client = _get_api_client_with_location(api_client, location)
+
+ logger.info("Preparing dataset(s) and metrics...")
+ if isinstance(dataset, types.EvaluationDataset):
+ dataset_list = [dataset]
+ elif isinstance(dataset, list):
+ for item in dataset:
+ if not isinstance(item, types.EvaluationDataset):
+ raise TypeError(
+ f"Unsupported dataset type: {type(item)}. "
+ "Must be EvaluationDataset."
+ )
+ dataset_list = dataset
+ else:
+ raise TypeError(
+ f"Unsupported dataset type: {type(dataset)}. Must be an"
+ " EvaluationDataset or a list of EvaluationDataset."
+ )
+ original_candidate_names = [
+ ds.candidate_name or f"candidate_{i + 1}" for i, ds in enumerate(dataset_list)
+ ]
+ name_counts = collections.Counter(original_candidate_names)
+ deduped_candidate_names = []
+ current_name_counts: collections.defaultdict[Any, int] = collections.defaultdict(
+ int
+ )
+
+ for name in original_candidate_names:
+ if name_counts[name] > 1:
+ current_name_counts[name] += 1
+ deduped_candidate_names.append(f"{name} #{current_name_counts[name]}")
+ else:
+ deduped_candidate_names.append(name)
+
+ loader = _evals_utils.EvalDatasetLoader(api_client=api_client)
+
+ agent_info = kwargs.get("agent_info", None)
+ validated_agent_info = None
+ if agent_info:
+ if isinstance(agent_info, dict):
+ validated_agent_info = types.evals.AgentInfo.model_validate(agent_info)
+ elif isinstance(agent_info, types.evals.AgentInfo):
+ validated_agent_info = agent_info
+ else:
+ raise TypeError(
+ "agent_info values must be of type types.evals.AgentInfo or dict,"
+ f" but got {type(agent_info)}'"
+ )
+
+ processed_eval_dataset, num_response_candidates = _resolve_dataset_inputs(
+ dataset=dataset_list,
+ dataset_schema=dataset_schema,
+ loader=loader,
+ agent_info=validated_agent_info,
+ )
+
+ resolved_metrics = _resolve_metrics(metrics, api_client)
+
+ evaluation_run_config = _evals_metric_handlers.EvaluationRunConfig(
+ evals_module=evals.Evals(api_client_=api_client),
+ dataset=processed_eval_dataset,
+ metrics=resolved_metrics,
+ num_response_candidates=num_response_candidates,
+ )
+
+ logger.info("Running Metric Computation...")
+ t1 = time.perf_counter()
+ evaluation_result = _evals_metric_handlers.compute_metrics_and_aggregate(
+ evaluation_run_config,
+ evaluation_service_qps=evaluation_service_qps,
+ )
+ t2 = time.perf_counter()
+ logger.info("Evaluation took: %f seconds", t2 - t1)
+
+ evaluation_result.evaluation_dataset = dataset_list
+ evaluation_result.agent_info = validated_agent_info
+
+ if not evaluation_result.metadata:
+ evaluation_result.metadata = types.EvaluationRunMetadata()
+
+ evaluation_result.metadata.creation_timestamp = datetime.datetime.now(
+ datetime.timezone.utc
+ )
+
+ if deduped_candidate_names:
+ evaluation_result.metadata.candidate_names = deduped_candidate_names
+
+ logger.info("Evaluation run completed.")
+
+ if dest:
+ uploaded_path = _gcs_utils.GcsUtils(
+ api_client=api_client
+ ).upload_json_to_prefix(
+ data=evaluation_result.model_dump(
+ mode="json",
+ exclude_none=True,
+ exclude={"evaluation_dataset"},
+ ),
+ gcs_dest_prefix=dest,
+ filename_prefix="evaluation_result",
+ )
+ logger.info(
+ "Evaluation results uploaded successfully to GCS: %s", uploaded_path
+ )
+ return evaluation_result
+
+
+def _get_session_inputs(row: pd.Series) -> types.evals.SessionInput:
+ """Parses session inputs from a row."""
+ if isinstance(row["session_inputs"], str):
+ return types.evals.SessionInput.model_validate(
+ json.loads(row["session_inputs"])
+ )
+ elif isinstance(row["session_inputs"], dict):
+ return types.evals.SessionInput.model_validate(row["session_inputs"])
+ elif isinstance(row["session_inputs"], types.evals.SessionInput):
+ return row["session_inputs"]
+ else:
+ raise TypeError(
+ f"Unsupported session_inputs type: {type(row['session_inputs'])}. "
+ "Expecting string or dict in types.evals.SessionInput format."
+ )
+
+
+def _is_multi_turn_agent_simulation(
+ user_simulator_config: Optional[types.evals.UserSimulatorConfig] = None,
+ prompt_dataset: pd.DataFrame = None,
+) -> bool:
+ """Checks if the agent run is a multi-turn user simulation."""
+ return (
+ user_simulator_config is not None
+ or "conversation_plan" in prompt_dataset.columns
+ )
+
+
+def _process_multi_turn_agent_response(
+ resp_item: Any,
+ agent_data_agents: Optional[dict[str, Any]],
+) -> Optional[Union[str, dict[str, Any]]]:
+ """Processes a multi-turn agent response."""
+ if isinstance(resp_item, dict) and "error" in resp_item:
+ return json.dumps(resp_item)
+ return types.evals.AgentData(
+ turns=resp_item,
+ agents=agent_data_agents,
+ ).model_dump(exclude_unset=True)
+
+
+def _process_single_turn_agent_response(
+ resp_item: Any,
+ agent_data_agents: Optional[dict[str, Any]],
+) -> tuple[
+ Optional[Union[str, dict[str, Any]]],
+ list[dict[str, Any]],
+ Optional[Union[str, dict[str, Any]]],
+]:
+ """Processes a single-turn agent response."""
+ intermediate_events_row: list[dict[str, Any]] = []
+ response_row: Optional[Union[str, dict[str, Any]]] = None
+ agent_data_row: Optional[Union[str, dict[str, Any]]] = None
+
+ if isinstance(resp_item, list):
+ try:
+ response_row = resp_item[-1]["content"]["parts"][0]["text"]
+ for intermediate_event in resp_item[:-1]:
+ intermediate_events_row.append(
+ {
+ "event_id": intermediate_event.get("id"),
+ "content": intermediate_event.get("content"),
+ "creation_timestamp": intermediate_event.get("timestamp"),
+ "author": intermediate_event.get("author"),
+ }
+ )
+ # Construct AgentData natively for single-turn runs
+ agent_events = []
+ for event_dict in resp_item:
+ content_dict = event_dict.get("content")
+ content_obj = None
+ if content_dict:
+ content_obj = genai_types.Content.model_validate(content_dict)
+
+ agent_events.append(
+ types.evals.AgentEvent(
+ author=event_dict.get("author", "model"),
+ content=content_obj,
+ )
+ )
+
+ turn = types.evals.ConversationTurn(
+ turn_index=0,
+ turn_id="turn_0",
+ events=agent_events,
+ )
+ agent_data_row = types.evals.AgentData(
+ turns=[turn],
+ agents=agent_data_agents,
+ ).model_dump(exclude_unset=True)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ error_payload = {
+ "error": (
+ f"Failed to parse agent run response {str(resp_item)} to "
+ f"agent data: {e}"
+ ),
+ }
+ response_row = json.dumps(error_payload)
+ agent_data_row = json.dumps(error_payload)
+ elif isinstance(resp_item, dict) and "error" in resp_item:
+ response_row = json.dumps(resp_item)
+ else:
+ error_payload = {
+ "error": "Unexpected response type from agent run",
+ "response_type": str(type(resp_item)),
+ "details": str(resp_item),
+ }
+ response_row = json.dumps(error_payload)
+
+ return response_row, intermediate_events_row, agent_data_row
+
+
+def _create_agent_results_dataframe(
+ prompt_dataset: pd.DataFrame,
+ processed_responses: list[Any],
+ processed_intermediate_events: list[Any],
+ processed_agent_data: list[Any],
+ is_user_simulation: bool,
+) -> pd.DataFrame:
+ """Creates a DataFrame from the processed agent responses."""
+ df_dict: dict[str, Any] = {}
+ if is_user_simulation:
+ df_dict[AGENT_DATA] = processed_agent_data
+ if len(processed_agent_data) != len(prompt_dataset):
+ raise RuntimeError(
+ "Critical prompt/agent_data count mismatch: %d"
+ " prompts vs %d agent_data. This indicates an issue in response"
+ " collection."
+ % (
+ len(prompt_dataset),
+ len(processed_agent_data),
+ )
+ )
+ else:
+ df_dict[_evals_constant.INTERMEDIATE_EVENTS] = processed_intermediate_events
+ df_dict[_evals_constant.RESPONSE] = processed_responses
+ df_dict[AGENT_DATA] = processed_agent_data
+ if len(processed_responses) != len(prompt_dataset) or len(
+ processed_responses
+ ) != len(processed_intermediate_events):
+ raise RuntimeError(
+ "Critical prompt/response/intermediate_events count mismatch: %d"
+ " prompts vs %d vs %d responses. This indicates an issue in response"
+ " collection."
+ % (
+ len(prompt_dataset),
+ len(processed_responses),
+ len(processed_intermediate_events),
+ )
+ )
+
+ results_df_raw = pd.DataFrame(df_dict)
+
+ prompt_dataset_indexed = prompt_dataset.reset_index(drop=True)
+ results_df_responses_only_indexed = results_df_raw.reset_index(drop=True)
+
+ # Drop columns from input that will be overwritten by results to avoid
+ # duplicate columns after concatenation (e.g. agent_data).
+ overlap = prompt_dataset_indexed.columns.intersection(
+ results_df_responses_only_indexed.columns
+ )
+ if not overlap.empty:
+ prompt_dataset_indexed = prompt_dataset_indexed.drop(columns=overlap)
+
+ results_df = pd.concat(
+ [prompt_dataset_indexed, results_df_responses_only_indexed], axis=1
+ )
+ return results_df
+
+
+def _run_agent_internal(
+ api_client: BaseApiClient,
+ agent_engine: Optional[Union[str, types.AgentEngine]],
+ agent: Optional["LlmAgent"], # type: ignore # noqa: F821
+ prompt_dataset: pd.DataFrame,
+ user_simulator_config: Optional[types.evals.UserSimulatorConfig] = None,
+ allow_cross_region_model: bool = False,
+) -> pd.DataFrame:
+ """Runs an agent."""
+ raw_responses = _run_agent(
+ api_client=api_client,
+ agent_engine=agent_engine,
+ agent=agent,
+ prompt_dataset=prompt_dataset,
+ user_simulator_config=user_simulator_config,
+ allow_cross_region_model=allow_cross_region_model,
+ )
+ processed_intermediate_events = []
+ processed_responses = []
+ processed_agent_data = []
+ agent_data_agents = None
+ if agent:
+ agent_data_agents = types.evals.AgentData.get_agents_map(agent)
+
+ is_user_simulation = _is_multi_turn_agent_simulation(
+ user_simulator_config, prompt_dataset
+ )
+
+ for resp_item in raw_responses:
+ if is_user_simulation:
+ agent_data_row = _process_multi_turn_agent_response(
+ resp_item, agent_data_agents
+ )
+ processed_agent_data.append(agent_data_row)
+ else:
+ response_row, intermediate_events_row, agent_data_row = (
+ _process_single_turn_agent_response(resp_item, agent_data_agents)
+ )
+ processed_responses.append(response_row)
+ processed_intermediate_events.append(intermediate_events_row)
+ processed_agent_data.append(agent_data_row)
+
+ return _create_agent_results_dataframe(
+ prompt_dataset,
+ processed_responses,
+ processed_intermediate_events,
+ processed_agent_data,
+ is_user_simulation,
+ )
+
+
+def _run_agent(
+ api_client: BaseApiClient,
+ agent_engine: Optional[Union[str, types.AgentEngine]],
+ agent: Optional["LlmAgent"], # type: ignore # noqa: F821
+ prompt_dataset: pd.DataFrame,
+ user_simulator_config: Optional[types.evals.UserSimulatorConfig] = None,
+ allow_cross_region_model: bool = False,
+) -> list[
+ Union[
+ list[dict[str, Any]],
+ dict[str, Any],
+ genai_types.GenerateContentResponse,
+ ]
+]:
+ """Internal helper to run inference using Gemini model with concurrency."""
+ original_location = os.environ.get("GOOGLE_CLOUD_LOCATION")
+ location_overridden = False
+
+ if user_simulator_config and user_simulator_config.model_name:
+ model_name = user_simulator_config.model_name
+ if model_name.startswith("gemini-3") and "/" not in model_name:
+ current_location = original_location or api_client.location or "us-central1"
+ if current_location != "global" and not allow_cross_region_model:
+ raise ValueError(
+ f"The model '{model_name}' is currently only available in the"
+ " 'global' region. Because this request originated in"
+ f" '{current_location}', you must explicitly set"
+ " allow_cross_region_model=True to allow your data to be routed"
+ " outside of your request's region."
+ )
+
+ logger.warning(
+ "Model %s is only available in the global region. Routing to global.",
+ model_name,
+ )
+ user_simulator_config.model_name = f"projects/{api_client.project}/locations/global/publishers/google/models/{model_name}"
+ if original_location != "global":
+ os.environ["GOOGLE_CLOUD_LOCATION"] = "global"
+ location_overridden = True
+
+ try:
+ if agent_engine:
+ return _execute_inference_concurrently(
+ api_client=api_client,
+ agent_engine=agent_engine,
+ prompt_dataset=prompt_dataset,
+ progress_desc="Agent Run",
+ gemini_config=None,
+ user_simulator_config=None,
+ inference_fn=_execute_agent_run_with_retry,
+ )
+ elif agent:
+ return _execute_inference_concurrently(
+ api_client=api_client,
+ agent=agent,
+ prompt_dataset=prompt_dataset,
+ progress_desc="Local Agent Run",
+ gemini_config=None,
+ user_simulator_config=user_simulator_config,
+ inference_fn=_execute_local_agent_run_with_retry,
+ )
+ else:
+ raise ValueError("Neither agent_engine nor agent is provided.")
+ finally:
+ if location_overridden:
+ if original_location is None:
+ del os.environ["GOOGLE_CLOUD_LOCATION"]
+ else:
+ os.environ["GOOGLE_CLOUD_LOCATION"] = original_location
+
+
+def _create_agent_engine_session(
+ *,
+ agent_engine: types.AgentEngine,
+ user_id: str,
+ session_state: Optional[dict[str, Any]] = None,
+) -> Any:
+ """Creates a session for an agent engine and returns the session ID.
+
+ First attempts to use the agent engine's own `create_session` operation
+ (available for agents deployed via AdkApp). If the agent engine does not
+ have `create_session` registered, falls back to the managed Vertex AI
+ Sessions API.
+
+ Args:
+ agent_engine: The AgentEngine instance.
+ user_id: The user ID for the session.
+ session_state: Optional initial state for the session.
+
+ Returns:
+ The session ID string.
+
+ Raises:
+ RuntimeError: If the session could not be created via either path.
+ """
+ try:
+ session = agent_engine.create_session( # type: ignore[attr-defined]
+ user_id=user_id,
+ state=session_state,
+ )
+ return session["id"]
+ except AttributeError as exc:
+ # Agent engine does not have create_session registered (e.g. deployed
+ # via Console, gcloud, or source code deployment without AdkApp).
+ # Fall back to the managed Vertex AI Sessions API.
+ logger.info(
+ "Agent engine does not have 'create_session' operation registered."
+ " Falling back to managed Sessions API."
+ )
+ if agent_engine.api_resource is None:
+ raise RuntimeError(
+ "Failed to create session: agent_engine.api_resource is None."
+ ) from exc
+ if agent_engine.api_client is None:
+ raise RuntimeError(
+ "Failed to create session: agent_engine.api_client is None."
+ ) from exc
+ operation = agent_engine.api_client.sessions.create(
+ name=agent_engine.api_resource.name,
+ user_id=user_id,
+ config=types.CreateAgentEngineSessionConfig(
+ session_state=session_state,
+ ),
+ )
+ if operation.response and operation.response.name:
+ # Session name format:
+ # projects/{p}/locations/{l}/reasoningEngines/{re}/sessions/{id}
+ return operation.response.name.split("/")[-1]
+ elif operation.error:
+ raise RuntimeError(
+ f"Failed to create session via managed API: {operation.error}"
+ ) from exc
+ else:
+ raise RuntimeError(
+ "Failed to create session via managed API: "
+ "operation returned no response."
+ ) from exc
+
+
+def _execute_agent_run_with_retry(
+ row: pd.Series,
+ contents: Union[genai_types.ContentListUnion, genai_types.ContentListUnionDict],
+ agent_engine: types.AgentEngine,
+ max_retries: int = 3,
+) -> Union[list[dict[str, Any]], dict[str, Any]]:
+ """Executes agent run over agent engine for a single prompt."""
+ try:
+ if "session_inputs" in row.index and row.get("session_inputs") is not None:
+ session_inputs = _get_session_inputs(row)
+ user_id = session_inputs.user_id or str(uuid.uuid4())
+ session_state = session_inputs.state
+ else:
+ user_id = str(uuid.uuid4())
+ session_state = None
+ except KeyError as e:
+ return {"error": f"Failed to get all required agent engine inputs: {e}"}
+
+ try:
+ session_id = _create_agent_engine_session(
+ agent_engine=agent_engine,
+ user_id=user_id,
+ session_state=session_state,
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ return {"error": f"Failed to create a new session: {e}"}
+
+ # Pre-populate remote session with agent_data history (N+1 case only).
+ if (
+ AGENT_DATA in row.index
+ and row.get(AGENT_DATA) is not None
+ and _is_n_plus_1_inference(row[AGENT_DATA])
+ ):
+ agent_data_obj = row[AGENT_DATA]
+ if isinstance(agent_data_obj, dict):
+ agent_data_obj = types.evals.AgentData.model_validate(agent_data_obj)
+ _, history_events = _extract_prompt_from_agent_data(agent_data_obj)
+
+ if agent_engine.api_resource is None:
+ return {"error": "agent_engine.api_resource is None."}
+ if agent_engine.api_client is None:
+ return {"error": "agent_engine.api_client is None."}
+ session_name = f"{agent_engine.api_resource.name}/sessions/{session_id}"
+ base_ts = datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc)
+ for i, ag_event in enumerate(history_events):
+ agent_engine.api_client.sessions.events.append(
+ name=session_name,
+ author=ag_event.author or "user",
+ invocation_id="history",
+ timestamp=base_ts + datetime.timedelta(seconds=i),
+ config=types.AppendAgentEngineSessionEventConfig(
+ content=ag_event.content,
+ ),
+ )
+
+ # stream_query retry loop (shared for both agent_data and prompt paths).
+ for attempt in range(max_retries):
+ try:
+ responses = []
+ for event in agent_engine.stream_query( # type: ignore[attr-defined]
+ user_id=user_id,
+ session_id=session_id,
+ message=contents,
+ ):
+ if event and CONTENT in event and PARTS in event[CONTENT]:
+ responses.append(event)
+ return responses
+ except api_exceptions.ResourceExhausted as e:
+ logger.warning(
+ "Resource Exhausted error on attempt %d/%d: %s. Retrying in %s"
+ " seconds...",
+ attempt + 1,
+ max_retries,
+ e,
+ 2**attempt,
+ )
+ if attempt == max_retries - 1:
+ return {"error": f"Resource exhausted after retries: {e}"}
+ time.sleep(2**attempt)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Unexpected error during agent engine run on attempt %d/%d: %s",
+ attempt + 1,
+ max_retries,
+ e,
+ )
+ if attempt == max_retries - 1:
+ return {"error": f"Failed after retries: {e}"}
+ time.sleep(1)
+ return {"error": f"Failed to get agent run results after {max_retries} retries"}
+
+
+def _execute_local_agent_run_with_retry(
+ row: pd.Series,
+ contents: Union[genai_types.ContentListUnion, genai_types.ContentListUnionDict],
+ agent: "LlmAgent", # type: ignore # noqa: F821
+ max_retries: int = 3,
+ user_simulator_config: Optional[types.evals.UserSimulatorConfig] = None,
+) -> Union[list[dict[str, Any]], dict[str, Any]]:
+ """Executes agent run locally for a single prompt synchronously."""
+ return asyncio.run(
+ _execute_local_agent_run_with_retry_async(
+ row, contents, agent, max_retries, user_simulator_config
+ )
+ )
+
+
+async def _execute_local_agent_run_with_retry_async(
+ row: pd.Series,
+ contents: Union[genai_types.ContentListUnion, genai_types.ContentListUnionDict],
+ agent: "LlmAgent", # type: ignore # noqa: F821
+ max_retries: int = 3,
+ user_simulator_config: Optional[types.evals.UserSimulatorConfig] = None,
+) -> Union[list[dict[str, Any]], dict[str, Any]]:
+ """Executes agent run locally for a single prompt asynchronously."""
+ # Lazy-import ADK dependencies to avoid top-level import failures when
+ # google-adk is not installed.
+ from google.adk.runners import Runner
+ from google.adk.sessions import InMemorySessionService
+
+ # Multi-turn agent scraping with user simulation.
+ if user_simulator_config or "conversation_plan" in row:
+ try:
+ return await _run_adk_user_simulation(row, agent, user_simulator_config)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error("Multi-turn agent run with user simulation failed: %s", e)
+ return {"error": f"Multi-turn agent run with user simulation failed: {e}"}
+
+ if "session_inputs" in row.index and row.get("session_inputs") is not None:
+ session_inputs = _get_session_inputs(row)
+ user_id = session_inputs.user_id or str(uuid.uuid4())
+ app_name = session_inputs.app_name or "local agent run"
+ else:
+ user_id = str(uuid.uuid4())
+ app_name = "local agent run"
+ session_id = str(uuid.uuid4())
+
+ session_service = InMemorySessionService()
+ await session_service.create_session(
+ app_name=app_name, user_id=user_id, session_id=session_id
+ )
+
+ # Pre-populate session with agent_data history (N+1 case only).
+ if (
+ AGENT_DATA in row.index
+ and row.get(AGENT_DATA) is not None
+ and _is_n_plus_1_inference(row[AGENT_DATA])
+ ):
+ from google.adk.events.event import Event as AdkEvent
+
+ agent_data_obj = row[AGENT_DATA]
+ if isinstance(agent_data_obj, dict):
+ agent_data_obj = types.evals.AgentData.model_validate(agent_data_obj)
+ _, history_events = _extract_prompt_from_agent_data(agent_data_obj)
+ internal_session = session_service.sessions[app_name][user_id][session_id]
+ for ag_event in history_events:
+ adk_event = AdkEvent(
+ author=ag_event.author or "user",
+ content=ag_event.content,
+ invocation_id="history",
+ )
+ internal_session.events.append(adk_event)
+
+ agent_runner = Runner(
+ agent=agent, app_name=app_name, session_service=session_service
+ )
+ new_message_content = genai_types.Content(
+ role=USER_AUTHOR,
+ parts=[genai_types.Part(text=contents)],
+ )
+ # Avoid printing out warning from agent_runner.run()
+ # WARNING:google_genai.types:Warning: there are non-text parts in the
+ # response: ['function_call'], returning concatenated text result from
+ # text parts. Check the full candidates.content.parts accessor to get
+ # the full model response.
+ # TODO: Update retry mechanism
+ with _temp_logger_level("google_genai.types", logging.ERROR):
+ for attempt in range(max_retries):
+ try:
+ events = []
+ async for event in agent_runner.run_async(
+ user_id=user_id,
+ session_id=session_id,
+ new_message=new_message_content,
+ ):
+ if event:
+ event = event.model_dump(exclude_none=True)
+ if event and CONTENT in event and PARTS in event[CONTENT]:
+ events.append(event)
+ return events
+ except api_exceptions.ResourceExhausted as e:
+ logger.warning(
+ "Resource Exhausted error on attempt %d/%d: %s. Retrying"
+ " in %s seconds...",
+ attempt + 1,
+ max_retries,
+ e,
+ 2**attempt,
+ )
+ if attempt == max_retries - 1:
+ return {"error": f"Resource exhausted after retries: {e}"}
+ await asyncio.sleep(2**attempt)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Unexpected error during agent run on attempt %d/%d: %s",
+ attempt + 1,
+ max_retries,
+ e,
+ )
+ if attempt == max_retries - 1:
+ return {"error": f"Failed after retries: {e}"}
+ await asyncio.sleep(1)
+ return {"error": f"Failed to get agent run results after {max_retries} retries"}
+
+
+def _convert_gcs_to_evaluation_item_result(
+ api_client: BaseApiClient,
+ gcs_uri: str,
+) -> types.EvaluationItemResult:
+ """Converts a json file to an EvaluationItemResult."""
+ logger.info("Loading evaluation item result from GCS: %s", gcs_uri)
+ gcs_utils = _gcs_utils.GcsUtils(api_client=api_client)
+ try:
+ eval_item_data = json.loads(gcs_utils.read_file_contents(gcs_uri))
+ return types.EvaluationItemResult(**eval_item_data)
+ except Exception as e:
+ logger.error(
+ "Failed to load evaluation result from GCS: %s. Error: %s", gcs_uri, e
+ )
+ return types.EvaluationItemResult()
+
+
+def _convert_gcs_to_evaluation_item_request(
+ api_client: BaseApiClient,
+ gcs_uri: str,
+) -> types.EvaluationItemRequest:
+ """Converts a json file to an EvaluationItemRequest."""
+ logger.info("Loading evaluation item request from GCS: %s", gcs_uri)
+ gcs_utils = _gcs_utils.GcsUtils(api_client=api_client)
+ try:
+ eval_item_data = json.loads(gcs_utils.read_file_contents(gcs_uri))
+ return types.EvaluationItemRequest(**eval_item_data)
+ except Exception as e:
+ logger.error(
+ "Failed to load evaluation request from GCS: %s. Error: %s", gcs_uri, e
+ )
+ return types.EvaluationItemRequest()
+
+
+def _get_aggregated_metrics(
+ results: types.EvaluationRunResults,
+) -> list[types.AggregatedMetricResult]:
+ """Retrieves an EvaluationResult from the resource name."""
+ if (
+ not results
+ or not results.summary_metrics
+ or not results.summary_metrics.metrics
+ ):
+ return []
+
+ aggregated_metrics_dict: dict[str, dict[str, Any]] = {}
+ for name, value in results.summary_metrics.metrics.items():
+ result = name.rsplit("/", 1)
+ full_metric_name = result[0]
+ aggregated_metric_name = result[1]
+ if full_metric_name not in aggregated_metrics_dict:
+ aggregated_metrics_dict[full_metric_name] = {}
+ aggregated_metrics_dict[full_metric_name]["sub_metric_name"] = (
+ full_metric_name.split("/")[-1]
+ )
+ aggregated_metrics_dict[full_metric_name][aggregated_metric_name] = value
+
+ items_sorted = sorted(
+ aggregated_metrics_dict.items(),
+ key=lambda item: (item[1]["sub_metric_name"], item[0]),
+ )
+
+ return [
+ types.AggregatedMetricResult(
+ metric_name=name.split("/")[-1],
+ mean_score=values.get("AVERAGE"),
+ stdev_score=values.get("STANDARD_DEVIATION"),
+ )
+ for name, values in items_sorted
+ ]
+
+
+def _get_eval_case_result_from_eval_item(
+ index: int,
+ eval_item: types.EvaluationItem,
+) -> types.EvalCaseResult:
+ """Transforms EvaluationItem to EvalCaseResult."""
+ metric_results = {}
+ if (
+ eval_item.evaluation_response
+ and eval_item.evaluation_response.candidate_results
+ ):
+ for candidate_result in eval_item.evaluation_response.candidate_results:
+ metric_results[candidate_result.metric] = types.EvalCaseMetricResult(
+ metric_name=candidate_result.metric,
+ score=candidate_result.score,
+ explanation=candidate_result.explanation,
+ rubric_verdicts=candidate_result.rubric_verdicts,
+ error_message=(eval_item.error.message if eval_item.error else None),
+ )
+ return types.EvalCaseResult(
+ eval_case_index=index,
+ response_candidate_results=[
+ types.ResponseCandidateResult(
+ response_index=0,
+ metric_results=metric_results,
+ )
+ ],
+ )
+
+
+def _convert_request_to_dataset_row(
+ request: types.EvaluationItemRequest,
+) -> dict[str, Any]:
+ """Converts an EvaluationItemRequest to a dictionary."""
+ dict_row: dict[str, Any] = {}
+ dict_row[_evals_constant.PROMPT] = (
+ request.prompt.text if request.prompt and request.prompt.text else None
+ )
+ dict_row[_evals_constant.REFERENCE] = request.golden_response
+
+ if request.prompt and request.prompt.user_scenario:
+ dict_row[_evals_constant.STARTING_PROMPT] = (
+ request.prompt.user_scenario.starting_prompt
+ )
+ dict_row[_evals_constant.CONVERSATION_PLAN] = (
+ request.prompt.user_scenario.conversation_plan
+ )
+
+ intermediate_events = []
+ agent_data = None
+ if request.candidate_responses:
+ for candidate in request.candidate_responses:
+ if candidate.candidate is not None:
+ dict_row[candidate.candidate] = (
+ candidate.text if candidate.text else None
+ )
+ if candidate.events:
+ for event in candidate.events:
+ content_dict = {"parts": event.parts, "role": event.role}
+ int_events_dict = {
+ "event_id": candidate.candidate,
+ "content": content_dict,
+ }
+ intermediate_events.append(int_events_dict)
+ agent_data = request.candidate_responses[0].agent_data
+
+ dict_row[_evals_constant.INTERMEDIATE_EVENTS] = intermediate_events
+ dict_row[_evals_constant.AGENT_DATA] = (
+ agent_data.model_dump() if agent_data else None
+ )
+ return dict_row
+
+
+def _drop_empty_columns(df: "pd.DataFrame") -> "pd.DataFrame":
+ """Drops columns that are all None or all empty lists/dicts."""
+ if df is None or df.empty or pd is None:
+ return df
+
+ def is_empty(x: Any) -> bool:
+ if isinstance(x, (list, dict)):
+ return not x
+ return pd.isna(x) # type: ignore[no-any-return]
+
+ cols_to_drop = [col for col in df.columns if df[col].apply(is_empty).all()]
+ return df.drop(columns=cols_to_drop)
+
+
+def _transform_dataframe(
+ rows: list[dict[str, Any]],
+) -> list[types.EvaluationDataset]:
+ """Transforms rows to a list of EvaluationDatasets.
+
+ Args:
+ rows: A list of rows, each row is a dictionary of candidate name to response
+ text.
+
+ Returns:
+ A list of EvaluationDatasets, one for each candidate.
+ """
+ df = pd.DataFrame(rows)
+ candidates = [
+ col for col in df.columns if col not in _evals_constant.COMMON_DATASET_COLUMNS
+ ]
+
+ eval_dfs = []
+ for candidate in candidates:
+ temp_df = df.rename(columns={candidate: _evals_constant.RESPONSE})
+ temp_df = _drop_empty_columns(temp_df)
+ eval_dfs.append(
+ types.EvaluationDataset(
+ candidate_name=candidate,
+ eval_dataset_df=temp_df,
+ )
+ )
+ return eval_dfs
+
+
+def _get_eval_cases_eval_dfs_from_eval_items(
+ eval_items: list[types.EvaluationItem],
+) -> tuple[list[types.EvalCaseResult], list[types.EvaluationDataset]]:
+ """Converts an EvaluationSet to a list of EvaluationCaseResults and EvaluationDatasets.
+
+ Args:
+ api_client: The API client.
+ evaluation_set_name: The name of the evaluation set.
+
+ Returns:
+ A tuple of two lists:
+ - eval_case_results: A list of EvalCaseResults, one for each evaluation
+ item.
+ - eval_dfs: A list of EvaluationDatasets, one for each candidate.
+ """
+ dataset_rows = []
+ eval_case_results = []
+ for index, eval_item in enumerate(eval_items):
+ if (
+ eval_item
+ and eval_item.evaluation_response
+ and eval_item.evaluation_response.request
+ ):
+ eval_case_results.append(
+ _get_eval_case_result_from_eval_item(index, eval_item)
+ )
+ dataset_rows.append(
+ _convert_request_to_dataset_row(eval_item.evaluation_response.request)
+ )
+ eval_dfs = _transform_dataframe(dataset_rows)
+ return eval_case_results, eval_dfs
+
+
+def _get_agent_info_from_inference_configs(
+ candidate_names: list[str],
+ inference_configs: Optional[dict[str, types.EvaluationRunInferenceConfig]] = None,
+) -> Optional[types.evals.AgentInfo]:
+ """Retrieves an AgentInfo from the inference configs."""
+ # TODO(lakeyk): Support multiple agents.
+ if not (
+ inference_configs
+ and candidate_names
+ and candidate_names[0] in inference_configs
+ and inference_configs[candidate_names[0]].agent_config
+ ):
+ return None
+ if len(inference_configs.keys()) > 1:
+ logger.warning(
+ "Multiple agents are not supported yet. Displaying the first agent."
+ )
+ agent_config = inference_configs[candidate_names[0]].agent_config
+ di = (
+ agent_config.developer_instruction
+ if agent_config and agent_config.developer_instruction
+ else None
+ )
+ instruction = di.parts[0].text if di and di.parts and di.parts[0].text else None
+ tools = agent_config.tools if agent_config and agent_config.tools else None
+
+ return types.evals.AgentInfo(
+ name=candidate_names[0],
+ agents={
+ "agent_0": types.evals.AgentConfig(
+ instruction=instruction,
+ tools=tools,
+ )
+ },
+ root_agent_id="agent_0",
+ )
+
+
+def _get_eval_result_from_eval_items(
+ results: types.EvaluationRunResults,
+ eval_items: list[types.EvaluationItem],
+ inference_configs: Optional[dict[str, types.EvaluationRunInferenceConfig]] = None,
+) -> types.EvaluationResult:
+ """Retrieves an EvaluationResult from the EvaluationRunResults.
+
+ This function is used to convert an EvaluationRunResults object used by the
+ Evaluation Management API to an EvaluationResult object. It is used to display
+ the evaluation results in the UI.
+
+ Args:
+ results: The EvaluationRunResults object.
+ eval_items: The list of EvaluationItems.
+
+ Returns:
+ An EvaluationResult object.
+ """
+ aggregated_metrics = _get_aggregated_metrics(results)
+ eval_case_results, eval_dfs = _get_eval_cases_eval_dfs_from_eval_items(eval_items)
+ candidate_names = [eval_df.candidate_name for eval_df in eval_dfs]
+ eval_result = types.EvaluationResult(
+ summary_metrics=aggregated_metrics,
+ eval_case_results=eval_case_results,
+ evaluation_dataset=eval_dfs,
+ metadata=types.EvaluationRunMetadata(
+ candidate_names=candidate_names,
+ ),
+ agent_info=_get_agent_info_from_inference_configs(
+ candidate_names, inference_configs
+ ),
+ )
+ return eval_result
+
+
+def _build_eval_item_map(
+ eval_items: list[types.EvaluationItem],
+) -> dict[str, dict[str, Any]]:
+ """Builds a mapping from EvaluationItem resource name to serialized data.
+
+ This is used by the loss analysis visualization to enrich examples with
+ scenario and rubric data from the original evaluation items.
+
+ Args:
+ eval_items: The list of EvaluationItem objects.
+
+ Returns:
+ A dict mapping evaluation item resource name to the serialized
+ evaluation_response dict (which the JS visualization reads as
+ ``evaluation_result``).
+ """
+ item_map: dict[str, dict[str, Any]] = {}
+ for item in eval_items:
+ if item.name and item.evaluation_response:
+ try:
+ item_map[item.name] = item.evaluation_response.model_dump(
+ mode="json", exclude_none=True
+ )
+ except Exception:
+ pass
+ return item_map
+
+
+def _convert_evaluation_run_results(
+ api_client: BaseApiClient,
+ evaluation_run_results: types.EvaluationRunResults,
+ inference_configs: Optional[dict[str, types.EvaluationRunInferenceConfig]] = None,
+) -> tuple[Optional[types.EvaluationResult], dict[str, dict[str, Any]]]:
+ """Retrieves an EvaluationResult and item map from EvaluationRunResults.
+
+ Returns:
+ A tuple of (EvaluationResult, eval_item_map). The eval_item_map maps
+ evaluation item resource names to their serialized evaluation response
+ data, used for enriching loss analysis visualization.
+ """
+ if not evaluation_run_results or not evaluation_run_results.evaluation_set:
+ return None, {}
+
+ evals_module = evals.Evals(api_client_=api_client)
+ eval_set = evals_module.get_evaluation_set(
+ name=evaluation_run_results.evaluation_set
+ )
+
+ eval_items = []
+ if eval_set and eval_set.evaluation_items:
+ eval_items = [
+ evals_module.get_evaluation_item(name=item_name)
+ for item_name in eval_set.evaluation_items
+ ]
+ eval_result = _get_eval_result_from_eval_items(
+ evaluation_run_results, eval_items, inference_configs
+ )
+ eval_item_map = _build_eval_item_map(eval_items)
+ return eval_result, eval_item_map
+
+
+async def _convert_evaluation_run_results_async(
+ api_client: BaseApiClient,
+ evaluation_run_results: types.EvaluationRunResults,
+ inference_configs: Optional[dict[str, types.EvaluationRunInferenceConfig]] = None,
+) -> tuple[Optional[types.EvaluationResult], dict[str, dict[str, Any]]]:
+ """Retrieves an EvaluationResult and item map from EvaluationRunResults."""
+ if not evaluation_run_results or not evaluation_run_results.evaluation_set:
+ return None, {}
+
+ evals_module = evals.AsyncEvals(api_client_=api_client)
+ eval_set = await evals_module.get_evaluation_set(
+ name=evaluation_run_results.evaluation_set
+ )
+
+ eval_items = []
+ if eval_set and eval_set.evaluation_items:
+ tasks = [
+ evals_module.get_evaluation_item(name=eval_item)
+ for eval_item in eval_set.evaluation_items
+ ]
+ eval_items = await asyncio.gather(*tasks)
+ eval_result = _get_eval_result_from_eval_items(
+ evaluation_run_results, eval_items, inference_configs
+ )
+ eval_item_map = _build_eval_item_map(eval_items)
+ return eval_result, eval_item_map
+
+
+def _object_to_dict(obj: Any) -> Union[dict[str, Any], Any]:
+ """Converts an object to a dictionary."""
+ if obj is None:
+ return obj
+ if isinstance(obj, (int, float, str, bool)):
+ return obj
+ if isinstance(obj, datetime.datetime):
+ return obj.isoformat()
+ if isinstance(obj, bytes):
+ return base64.b64encode(obj).decode("utf-8")
+ if isinstance(obj, (list, tuple)):
+ return [_object_to_dict(item) for item in obj]
+ if isinstance(obj, dict):
+ return {k: _object_to_dict(v) for k, v in obj.items()}
+
+ if not hasattr(obj, "__dict__"):
+ return obj # Not an object with attributes, return as is (e.g., set)
+
+ result: dict[str, Any] = {}
+ for key, value in obj.__dict__.items():
+ if value is None:
+ continue
+ result[key] = _object_to_dict(value)
+ return result
+
+
+def _get_content(row: dict[str, Any], column: str) -> Optional[genai_types.Content]:
+ if isinstance(row[column], str):
+ return genai_types.Content(
+ parts=[genai_types.Part(text=row[column])],
+ role=_evals_constant.USER_AUTHOR,
+ )
+ elif isinstance(row[column], genai_types.Content):
+ return cast(genai_types.Content, row[column])
+ else:
+ raise ValueError(
+ f"{column} must be a string or a Content object. Got {type(row[column])}."
+ )
+
+
+def _create_evaluation_set_from_dataframe(
+ api_client: BaseApiClient,
+ gcs_dest_prefix: str,
+ eval_df: pd.DataFrame,
+ candidate_name: Optional[str] = None,
+ parsed_agent_info: Optional[types.evals.AgentInfo] = None,
+) -> Union[types.EvaluationSet, Any]:
+ """Converts a dataframe to an EvaluationSet."""
+ eval_item_requests = []
+ for _, row in eval_df.iterrows():
+ intermediate_events = []
+ if (
+ _evals_constant.INTERMEDIATE_EVENTS in row
+ and isinstance(row[_evals_constant.INTERMEDIATE_EVENTS], list)
+ and len(row[_evals_constant.INTERMEDIATE_EVENTS]) > 0
+ ):
+ for event in row[_evals_constant.INTERMEDIATE_EVENTS]:
+ if CONTENT in event:
+ intermediate_events.append(event[CONTENT])
+
+ agent_data_obj = None
+ if _evals_constant.AGENT_DATA in row:
+ agent_data_val = row[AGENT_DATA]
+ if isinstance(agent_data_val, str):
+ try:
+ agent_data_val = json.loads(agent_data_val)
+ except json.JSONDecodeError:
+ pass
+ if isinstance(agent_data_val, dict):
+ try:
+ agent_data_obj = types.evals.AgentData.model_validate(
+ agent_data_val
+ )
+ except ValidationError:
+ pass
+ elif isinstance(agent_data_val, types.evals.AgentData):
+ agent_data_obj = agent_data_val
+
+ # When agent_data exists but has no agents map (e.g. from remote
+ # agent_engine inference), inject the agents map from agent_info so
+ # the server-side autorater can access tool definitions and
+ # instructions.
+ if (
+ agent_data_obj
+ and not agent_data_obj.agents
+ and parsed_agent_info
+ and parsed_agent_info.agents
+ ):
+ agent_data_obj.agents = parsed_agent_info.agents
+
+ candidate_responses = []
+ if _evals_constant.RESPONSE in row or agent_data_obj or intermediate_events:
+ # Resolve the oneof conflict: prioritize agent_data over flat text
+ response_text = row.get(_evals_constant.RESPONSE) or None
+
+ if agent_data_obj and response_text:
+ logger.info(
+ "Both 'response' and 'agent_data' columns found in the evaluation"
+ " dataset. Prioritizing 'agent_data' and omitting 'response' text"
+ " to satisfy CandidateResponse protobuf oneof constraints."
+ )
+ response_text = None
+
+ candidate_responses.append(
+ types.CandidateResponse(
+ candidate=candidate_name or "Candidate 1",
+ text=response_text,
+ events=intermediate_events or None,
+ agent_data=agent_data_obj,
+ )
+ )
+
+ prompt = None
+ # Determine which history column name is present, preferring
+ # "conversation_history" over "history" if both exist.
+ history_col = None
+ if _evals_constant.CONVERSATION_HISTORY in row:
+ history_col = _evals_constant.CONVERSATION_HISTORY
+ elif _evals_constant.HISTORY in row:
+ history_col = _evals_constant.HISTORY
+
+ if (
+ _evals_constant.STARTING_PROMPT in row
+ and _evals_constant.CONVERSATION_PLAN in row
+ ):
+ prompt = types.EvaluationPrompt(
+ user_scenario=types.evals.UserScenario(
+ starting_prompt=row[_evals_constant.STARTING_PROMPT],
+ conversation_plan=row[_evals_constant.CONVERSATION_PLAN],
+ )
+ )
+ elif _evals_constant.CONTEXT in row or history_col:
+ values = {}
+ if _evals_constant.CONTEXT in row:
+ values[_evals_constant.CONTEXT] = _get_content(
+ row, _evals_constant.CONTEXT
+ )
+ if history_col:
+ values[_evals_constant.CONVERSATION_HISTORY] = _get_content(
+ row, history_col
+ )
+ if _evals_constant.PROMPT in row:
+ values[_evals_constant.PROMPT] = _get_content(
+ row, _evals_constant.PROMPT
+ )
+ prompt = types.EvaluationPrompt(
+ prompt_template_data=types.PromptTemplateData(values=values)
+ )
+ elif _evals_constant.PROMPT in row:
+ prompt = types.EvaluationPrompt(text=row[_evals_constant.PROMPT])
+
+ eval_item_requests.append(
+ types.EvaluationItemRequest(
+ prompt=prompt or None,
+ golden_response=(
+ types.CandidateResponse(text=row[_evals_constant.REFERENCE])
+ if _evals_constant.REFERENCE in row
+ else None
+ ),
+ candidate_responses=(
+ candidate_responses if candidate_responses else None
+ ),
+ )
+ )
+ logger.info("Writing evaluation item requests to GCS.")
+ gcs_utils = _gcs_utils.GcsUtils(api_client=api_client)
+ evals_module = evals.Evals(api_client_=api_client)
+ eval_items = []
+ for eval_item_request in eval_item_requests:
+ gcs_uri = gcs_utils.upload_json_to_prefix(
+ data=_object_to_dict(eval_item_request),
+ gcs_dest_prefix=gcs_dest_prefix,
+ filename_prefix="request",
+ )
+ eval_item = evals_module.create_evaluation_item(
+ evaluation_item_type=types.EvaluationItemType.REQUEST,
+ gcs_uri=gcs_uri,
+ display_name="sdk-generated-eval-item",
+ )
+ eval_items.append(eval_item.name)
+ logger.info("Creating evaluation set from GCS URIs")
+ evaluation_set = evals_module.create_evaluation_set(
+ evaluation_items=eval_items,
+ )
+
+ return evaluation_set
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_constant.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_constant.py
new file mode 100644
index 0000000000000000000000000000000000000000..822f8e685a71ed32af205ac5c9847a05d8f6e057
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_constant.py
@@ -0,0 +1,78 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Constants for evals module."""
+
+SUPPORTED_PREDEFINED_METRICS = frozenset(
+ {
+ "general_quality_v1",
+ "text_quality_v1",
+ "instruction_following_v1",
+ "grounding_v1",
+ "safety_v1",
+ "multi_turn_general_quality_v1",
+ "multi_turn_text_quality_v1",
+ "multi_turn_tool_use_quality_v1",
+ "multi_turn_trajectory_quality_v1",
+ "multi_turn_task_success_v1",
+ "final_response_match_v2",
+ "final_response_reference_free_v1",
+ "final_response_quality_v1",
+ "hallucination_v1",
+ "tool_use_quality_v1",
+ "gecko_text2image_v1",
+ "gecko_text2video_v1",
+ }
+)
+
+SUPPORTED_VERTEX_MAAS_MODEL_PREFIXES = frozenset(
+ {
+ "meta/", # Meta/Llama
+ "deepseek-ai/", # DeepSeek AI
+ "qwen/", # Qwen
+ "openai/", # OpenAI (GPT-OSS)
+ "claude-", # Anthropic (Claude)
+ "mistral-", # Mistral AI
+ "jamba-", # AI21 (Jamba)
+ }
+)
+INTERMEDIATE_EVENTS = "intermediate_events"
+RESPONSE = "response"
+PROMPT = "prompt"
+REFERENCE = "reference"
+SESSION_INPUT = "session_inputs"
+CONTEXT = "context"
+CONTENT = "content"
+PARTS = "parts"
+USER_AUTHOR = "user"
+AGENT_DATA = "agent_data"
+STARTING_PROMPT = "starting_prompt"
+CONVERSATION_PLAN = "conversation_plan"
+HISTORY = "history"
+CONVERSATION_HISTORY = "conversation_history"
+
+COMMON_DATASET_COLUMNS = frozenset(
+ {
+ INTERMEDIATE_EVENTS,
+ PROMPT,
+ REFERENCE,
+ SESSION_INPUT,
+ CONTEXT,
+ HISTORY,
+ CONVERSATION_HISTORY,
+ STARTING_PROMPT,
+ CONVERSATION_PLAN,
+ AGENT_DATA,
+ }
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_data_converters.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_data_converters.py
new file mode 100644
index 0000000000000000000000000000000000000000..21564ff0a8949ab2b0fde27e7fb1d1d247d14a7d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_data_converters.py
@@ -0,0 +1,918 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Dataset converters for evals."""
+
+import copy
+import json
+import logging
+from typing import Any, Optional, Union
+
+from google.genai import _common
+from google.genai import types as genai_types
+from pydantic import ValidationError
+from typing_extensions import override
+
+from . import _evals_utils
+from . import _observability_data_converter
+from . import types
+
+
+logger = logging.getLogger("agentplatform_genai._evals_data_converters")
+
+
+class EvalDatasetSchema(_common.CaseInSensitiveEnum):
+ """Represents the schema of an evaluation dataset."""
+
+ GEMINI = "gemini"
+ FLATTEN = "flatten"
+ OPENAI = "openai"
+ OBSERVABILITY = "observability"
+ UNKNOWN = "unknown"
+
+
+_PLACEHOLDER_RESPONSE_TEXT = "Error: Missing response for this candidate"
+
+
+def _create_placeholder_response_candidate(
+ text: str = _PLACEHOLDER_RESPONSE_TEXT,
+) -> types.ResponseCandidate:
+ """Creates a ResponseCandidate with placeholder text."""
+ return types.ResponseCandidate(
+ response=genai_types.Content(parts=[genai_types.Part(text=text)])
+ )
+
+
+class _GeminiEvalDataConverter(_evals_utils.EvalDataConverter):
+ """Converter for dataset in the Gemini format."""
+
+ def _parse_request(self, request_data: dict[str, Any]) -> tuple[
+ genai_types.Content,
+ genai_types.Content,
+ list[types.evals.Message],
+ types.ResponseCandidate,
+ ]:
+ """Parses a request from a Gemini dataset."""
+ system_instruction = genai_types.Content()
+ prompt = genai_types.Content()
+ reference = types.ResponseCandidate()
+ conversation_history = []
+
+ if "system_instruction" in request_data:
+ system_instruction = genai_types.Content.model_validate(
+ request_data["system_instruction"]
+ )
+ for turn_id, content_dict in enumerate(request_data.get("contents", [])):
+ if not isinstance(content_dict, dict):
+ raise TypeError(
+ "Expected a dictionary for content at turn %s, but got %s: %s"
+ % (turn_id, type(content_dict).__name__, content_dict)
+ )
+ if "parts" not in content_dict:
+ raise ValueError(
+ "Missing 'parts' key in content structure at turn %s: %s"
+ % (turn_id, content_dict)
+ )
+ conversation_history.append(
+ types.evals.Message(
+ turn_id=str(turn_id),
+ content=genai_types.Content.model_validate(content_dict),
+ )
+ )
+ if conversation_history:
+ last_message = conversation_history.pop()
+ last_message_role = (
+ last_message.content.role if last_message.content else "user"
+ )
+ if last_message_role in ["user", None]:
+ prompt = (
+ last_message.content
+ if last_message.content
+ else genai_types.Content()
+ )
+ elif last_message_role == "model":
+ reference = types.ResponseCandidate(response=last_message.content)
+ if conversation_history:
+ second_to_last_message = conversation_history.pop()
+ prompt = (
+ second_to_last_message.content
+ if second_to_last_message.content
+ else genai_types.Content()
+ )
+ else:
+ prompt = genai_types.Content()
+
+ return prompt, system_instruction, conversation_history, reference
+
+ @override
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
+ """Converts a list of raw data into an EvaluationDataset."""
+ eval_cases = []
+
+ for i, item in enumerate(raw_data):
+ eval_case_id = "gemini_eval_case_%s" % i
+ request_data = item.get("request", {})
+ response_data = item.get("response", {})
+
+ (
+ prompt,
+ system_instruction,
+ conversation_history,
+ reference,
+ ) = self._parse_request(request_data)
+
+ responses = []
+ if isinstance(response_data, str):
+ responses.append(
+ types.ResponseCandidate(
+ response=genai_types.Content(
+ parts=[genai_types.Part(text=response_data)]
+ )
+ )
+ )
+ elif isinstance(response_data, dict):
+ try:
+ generate_content_response = (
+ genai_types.GenerateContentResponse.model_validate(
+ response_data
+ )
+ )
+ if generate_content_response.candidates:
+ candidate = generate_content_response.candidates[0]
+ if candidate.content:
+ responses.append(
+ types.ResponseCandidate(
+ response=genai_types.Content.model_validate(
+ candidate.content
+ )
+ )
+ )
+ else:
+ responses.append(_create_placeholder_response_candidate())
+ except Exception:
+ responses.append(_create_placeholder_response_candidate())
+ else:
+ responses.append(_create_placeholder_response_candidate())
+
+ eval_case = types.EvalCase(
+ eval_case_id=eval_case_id,
+ prompt=prompt,
+ responses=responses,
+ reference=reference,
+ system_instruction=system_instruction,
+ conversation_history=conversation_history,
+ )
+ eval_cases.append(eval_case)
+
+ return types.EvaluationDataset(eval_cases=eval_cases)
+
+
+class _FlattenEvalDataConverter(_evals_utils.EvalDataConverter):
+ """Converter for datasets in a structured table format."""
+
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
+ """Converts a list of raw data into an EvaluationDataset."""
+ eval_cases = []
+ for i, item_dict in enumerate(raw_data):
+ if not isinstance(item_dict, dict):
+ raise TypeError(
+ "Expected a dictionary for item at index %s, but got %s: %s"
+ % (i, type(item_dict).__name__, item_dict)
+ )
+ item = copy.deepcopy(item_dict)
+ eval_case_id = "eval_case_%s" % i
+ prompt_data = item.pop("prompt", None)
+ if not prompt_data:
+ prompt_data = item.pop("source", None)
+
+ conversation_history_data = item.pop("conversation_history", None)
+ if conversation_history_data is None:
+ conversation_history_data = item.pop("history", None)
+ response_data = item.pop("response", None)
+ reference_data = item.pop("reference", None)
+ system_instruction_data = item.pop("instruction", None)
+ rubric_groups_data = item.pop("rubric_groups", None)
+ intermediate_events_data = item.pop("intermediate_events", None)
+ agent_data_raw = item.pop("agent_data", None)
+
+ if not response_data and not agent_data_raw:
+ raise ValueError(
+ "Response is required but missing for %s." % eval_case_id
+ )
+ if not prompt_data and not agent_data_raw:
+ raise ValueError(
+ "Prompt is required but missing for %s." % eval_case_id
+ )
+
+ prompt: Optional[genai_types.Content] = None
+ if isinstance(prompt_data, str):
+ prompt = genai_types.Content(parts=[genai_types.Part(text=prompt_data)])
+ elif isinstance(prompt_data, dict):
+ prompt = genai_types.Content.model_validate(prompt_data)
+ elif isinstance(prompt_data, genai_types.Content):
+ prompt = prompt_data
+ elif not agent_data_raw:
+ raise ValueError(
+ "Invalid prompt type for case %s: %s" % (i, type(prompt_data))
+ )
+
+ conversation_history: Optional[list[types.evals.Message]] = None
+ if isinstance(conversation_history_data, list):
+ conversation_history = []
+ for turn_id, content in enumerate(conversation_history_data):
+ if isinstance(content, genai_types.Content):
+ conversation_history.append(
+ types.evals.Message(
+ turn_id=str(turn_id),
+ content=content,
+ )
+ )
+ elif isinstance(content, dict):
+ try:
+ validated_content = genai_types.Content.model_validate(
+ content
+ )
+ conversation_history.append(
+ types.evals.Message(
+ turn_id=str(turn_id),
+ content=validated_content,
+ )
+ )
+ except ValidationError as e:
+ logger.warning(
+ "Item at index %s in 'history' column for case "
+ " %s is a dict but could not be validated as"
+ " genai_types.Content: %s",
+ turn_id,
+ eval_case_id,
+ e,
+ )
+ else:
+ logger.warning(
+ "Invalid type in 'history' column for case %s at index %s. "
+ "Expected genai_types.Content or dict, but got %s. "
+ "Skipping this history item.",
+ eval_case_id,
+ turn_id,
+ type(content),
+ )
+
+ responses: Optional[list[types.ResponseCandidate]] = None
+ if isinstance(response_data, dict):
+ responses = [
+ types.ResponseCandidate(
+ response=genai_types.Content.model_validate(response_data)
+ )
+ ]
+ elif isinstance(response_data, str):
+ responses = [
+ types.ResponseCandidate(
+ response=genai_types.Content(
+ parts=[genai_types.Part(text=response_data)]
+ )
+ )
+ ]
+ elif isinstance(response_data, genai_types.Content):
+ responses = [types.ResponseCandidate(response=response_data)]
+ elif not agent_data_raw:
+ raise ValueError(
+ "Invalid response type for case %s: %s" % (i, type(response_data))
+ )
+
+ reference: Optional[types.ResponseCandidate] = None
+ if reference_data:
+ if isinstance(reference_data, dict):
+ reference = types.ResponseCandidate(
+ response=genai_types.Content.model_validate(reference_data)
+ )
+ elif isinstance(reference_data, str):
+ reference = types.ResponseCandidate(
+ response=genai_types.Content(
+ parts=[genai_types.Part(text=reference_data)]
+ )
+ )
+ elif isinstance(reference_data, genai_types.Content):
+ reference = types.ResponseCandidate(response=reference_data)
+
+ system_instruction: Optional[genai_types.Content] = None
+ if system_instruction_data:
+ if isinstance(system_instruction_data, dict):
+ system_instruction = genai_types.Content.model_validate(
+ system_instruction_data
+ )
+ elif isinstance(system_instruction_data, str):
+ system_instruction = genai_types.Content(
+ parts=[genai_types.Part(text=system_instruction_data)]
+ )
+ elif isinstance(system_instruction_data, genai_types.Content):
+ system_instruction = system_instruction_data
+
+ rubric_groups: Optional[dict[str, types.RubricGroup]] = None
+ if rubric_groups_data:
+ if isinstance(rubric_groups_data, dict):
+ rubric_groups = {}
+ for key, value in rubric_groups_data.items():
+ if isinstance(value, list):
+ try:
+ validated_rubrics = [
+ (
+ types.evals.Rubric.model_validate(r)
+ if isinstance(r, dict)
+ else r
+ )
+ for r in value
+ ]
+ if all(
+ isinstance(r, types.evals.Rubric)
+ for r in validated_rubrics
+ ):
+ rubric_groups[key] = types.RubricGroup(
+ rubrics=validated_rubrics
+ )
+ else:
+ logger.warning(
+ "Invalid item type in rubric list for group '%s' in case %s.",
+ key,
+ i,
+ )
+ except Exception as e:
+ logger.warning(
+ "Failed to validate rubrics for group '%s' in case %s: %s",
+ key,
+ i,
+ e,
+ )
+ elif isinstance(value, types.RubricGroup):
+ rubric_groups[key] = value
+ elif isinstance(value, dict):
+ try:
+ rubric_groups[key] = types.RubricGroup.model_validate(
+ value
+ )
+ except Exception as e:
+ logger.warning(
+ "Failed to validate RubricGroup dict for group '%s' in case %s: %s",
+ key,
+ i,
+ e,
+ )
+ else:
+ logger.warning(
+ "Invalid type for rubric group '%s' in case %s."
+ " Expected list of rubrics, dict, or RubricGroup.",
+ key,
+ i,
+ )
+ else:
+ logger.warning(
+ "Invalid type for rubric_groups in case %s. Expected dict.",
+ i,
+ )
+
+ intermediate_events: Optional[list[types.evals.Event]] = None
+ if intermediate_events_data:
+ if isinstance(intermediate_events_data, list):
+ intermediate_events = []
+ for event in intermediate_events_data:
+ if isinstance(event, dict):
+ try:
+ validated_event = types.evals.Event.model_validate(
+ event
+ )
+ intermediate_events.append(validated_event)
+ except Exception as e:
+ logger.warning(
+ "Failed to validate intermediate event dict for"
+ " case %s: %s",
+ i,
+ e,
+ )
+ elif isinstance(event, types.evals.Event):
+ intermediate_events.append(event)
+ else:
+ logger.warning(
+ "Invalid type for intermediate_event in case"
+ " %s. Expected list of dicts or list of"
+ " types.evals.Event objects.",
+ i,
+ )
+ else:
+ logger.warning(
+ "Invalid type for intermediate_events in case %s. Expected"
+ " list of types.evals.Event objects.",
+ i,
+ )
+
+ agent_data: Optional[types.evals.AgentData] = None
+ if agent_data_raw:
+ if isinstance(agent_data_raw, str):
+ try:
+ agent_data_dict = json.loads(agent_data_raw)
+ agent_data = types.evals.AgentData.model_validate(
+ agent_data_dict
+ )
+ except json.JSONDecodeError:
+ logger.warning(
+ "Could not decode agent_data JSON string for case %s.", i
+ )
+ except ValidationError as e:
+ logger.warning(
+ "Failed to validate agent_data for case %s: %s", i, e
+ )
+ elif isinstance(agent_data_raw, dict):
+ try:
+ agent_data = types.evals.AgentData.model_validate(
+ agent_data_raw
+ )
+ except ValidationError as e:
+ logger.warning(
+ "Failed to validate agent_data for case %s: %s", i, e
+ )
+ elif isinstance(agent_data_raw, types.evals.AgentData):
+ agent_data = agent_data_raw
+ else:
+ logger.warning(
+ "Invalid type for agent_data in case %s. Expected str, dict"
+ " or types.evals.AgentData object. Got %s",
+ i,
+ type(agent_data_raw),
+ )
+
+ eval_case = types.EvalCase(
+ eval_case_id=eval_case_id,
+ prompt=prompt,
+ responses=responses,
+ reference=reference,
+ conversation_history=conversation_history,
+ system_instruction=system_instruction,
+ rubric_groups=rubric_groups,
+ intermediate_events=intermediate_events,
+ agent_data=agent_data,
+ **item, # Pass remaining columns as extra fields to EvalCase.
+ # They can be used for custom metric prompt templates.
+ )
+ eval_cases.append(eval_case)
+
+ return types.EvaluationDataset(eval_cases=eval_cases)
+
+
+class _OpenAIDataConverter(_evals_utils.EvalDataConverter):
+ """Converter for dataset in OpenAI's Chat Completion format."""
+
+ def _parse_messages(self, messages: list[dict[str, Any]]) -> tuple[
+ Optional[genai_types.Content],
+ list[types.evals.Message],
+ Optional[genai_types.Content],
+ Optional[types.ResponseCandidate],
+ ]:
+ """Parses a list of messages into instruction, history, prompt, and reference."""
+ system_instruction = None
+ prompt = None
+ reference = None
+ conversation_history = []
+
+ if messages and messages[0].get("role") in ["system", "developer"]:
+ system_instruction = genai_types.Content(
+ parts=[genai_types.Part(text=messages[0].get("content"))]
+ )
+ messages = messages[1:]
+
+ for turn_id, msg in enumerate(messages):
+ role = msg.get("role", "user")
+ content = msg.get("content", "")
+ conversation_history.append(
+ types.evals.Message(
+ turn_id=str(turn_id),
+ content=genai_types.Content(
+ parts=[genai_types.Part(text=content)], role=role
+ ),
+ author=role,
+ )
+ )
+
+ if conversation_history:
+ last_message = conversation_history.pop()
+ if last_message.content and last_message.content.role == "user":
+ prompt = last_message.content
+ elif last_message.content and last_message.content.role == "assistant":
+ reference = types.ResponseCandidate(response=last_message.content)
+ if conversation_history:
+ second_to_last_message = conversation_history.pop()
+ prompt = second_to_last_message.content
+
+ return system_instruction, conversation_history, prompt, reference
+
+ @override
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
+ """Converts a list of OpenAI ChatCompletion data into an EvaluationDataset."""
+ eval_cases = []
+ for i, item in enumerate(raw_data):
+ eval_case_id = "openai_eval_case_%s" % i
+
+ if "request" not in item or "response" not in item:
+ logger.warning(
+ "Skipping case %s due to missing 'request' or 'response' key.", i
+ )
+ continue
+
+ request_data = item.get("request", {})
+ response_data_raw = item.get("response", {})
+
+ response_data = {}
+ if isinstance(response_data_raw, str):
+ try:
+ loaded_json = json.loads(response_data_raw)
+ if isinstance(loaded_json, dict):
+ response_data = loaded_json
+ else:
+ logger.warning(
+ "Decoded response JSON is not a dictionary for case"
+ " %s. Type: %s",
+ i,
+ type(loaded_json),
+ )
+ except json.JSONDecodeError:
+ logger.warning(
+ "Could not decode response JSON string for case %s."
+ " Treating as empty response.",
+ i,
+ )
+ elif isinstance(response_data_raw, dict):
+ response_data = response_data_raw
+
+ messages = request_data.get("messages", [])
+ choices = response_data.get("choices", [])
+
+ (
+ system_instruction,
+ conversation_history,
+ prompt,
+ reference,
+ ) = self._parse_messages(messages)
+
+ if prompt is None and reference is None:
+ logger.warning(
+ "Could not determine a user prompt or reference for case %s."
+ " Skipping.",
+ i,
+ )
+ continue
+
+ responses = []
+ if (
+ choices
+ and isinstance(choices, list)
+ and isinstance(choices[0], dict)
+ and choices[0].get("message")
+ ):
+ response_content = choices[0]["message"].get("content", "")
+ responses.append(
+ types.ResponseCandidate(
+ response=genai_types.Content(
+ parts=[genai_types.Part(text=response_content)]
+ )
+ )
+ )
+ else:
+ responses.append(_create_placeholder_response_candidate())
+
+ other_fields = {
+ k: v for k, v in item.items() if k not in ["request", "response"]
+ }
+
+ eval_case = types.EvalCase(
+ eval_case_id=eval_case_id,
+ prompt=prompt,
+ responses=responses,
+ reference=reference,
+ system_instruction=system_instruction,
+ conversation_history=conversation_history,
+ **other_fields,
+ )
+ eval_cases.append(eval_case)
+
+ return types.EvaluationDataset(eval_cases=eval_cases)
+
+
+def auto_detect_dataset_schema(
+ raw_dataset: list[dict[str, Any]],
+) -> Union[EvalDatasetSchema, str]:
+ """Detects the schema of a raw dataset."""
+ if not raw_dataset:
+ return EvalDatasetSchema.UNKNOWN
+
+ first_item = raw_dataset[0]
+ keys = set(first_item.keys())
+
+ if "format" in keys:
+ format_content = first_item.get("format", "")
+ if isinstance(format_content, str) and format_content == "observability":
+ return EvalDatasetSchema.OBSERVABILITY
+
+ if "request" in keys and "response" in keys:
+ request_content = first_item.get("request", {})
+ if isinstance(request_content, dict) and "contents" in request_content:
+ contents_list = request_content.get("contents")
+ if (
+ contents_list
+ and isinstance(contents_list, list)
+ and isinstance(contents_list[0], dict)
+ ):
+ if "parts" in contents_list[0]:
+ return EvalDatasetSchema.GEMINI
+
+ if "request" in keys and "response" in keys:
+ request_content = first_item.get("request", {})
+ if isinstance(request_content, dict) and "messages" in request_content:
+ messages_list = request_content.get("messages")
+ if (
+ messages_list
+ and isinstance(messages_list, list)
+ and isinstance(messages_list[0], dict)
+ ):
+ if "role" in messages_list[0] and "content" in messages_list[0]:
+ return EvalDatasetSchema.OPENAI
+
+ if "agent_data" in keys:
+ return EvalDatasetSchema.FLATTEN
+
+ if {"prompt", "response"}.issubset(keys) or {
+ "response",
+ "reference",
+ }.issubset(keys):
+ return EvalDatasetSchema.FLATTEN
+ else:
+ return EvalDatasetSchema.UNKNOWN
+
+
+_CONVERTER_REGISTRY = {
+ EvalDatasetSchema.GEMINI: _GeminiEvalDataConverter,
+ EvalDatasetSchema.FLATTEN: _FlattenEvalDataConverter,
+ EvalDatasetSchema.OPENAI: _OpenAIDataConverter,
+ EvalDatasetSchema.OBSERVABILITY: _observability_data_converter.ObservabilityDataConverter,
+}
+
+
+def get_dataset_converter(
+ dataset_schema: EvalDatasetSchema,
+) -> _evals_utils.EvalDataConverter:
+ """Returns the appropriate dataset converter for the given schema."""
+ if dataset_schema in _CONVERTER_REGISTRY:
+ return _CONVERTER_REGISTRY[dataset_schema]() # type: ignore[abstract]
+ else:
+ raise ValueError("Unsupported dataset schema: %s" % dataset_schema)
+
+
+def _get_content_text(content: genai_types.Content) -> str:
+ """Safely extracts text from all parts of a content.
+
+ If the content has multiple parts, text from all parts is concatenated.
+ If a part is not text, it is ignored. If no text parts are found,
+ an empty string is returned.
+ """
+ text_parts = []
+ if (
+ content
+ and hasattr(content, "parts")
+ and isinstance(content.parts, list)
+ and content.parts
+ ):
+ for part in content.parts:
+ if hasattr(part, "text") and part.text is not None:
+ text_parts.append(str(part.text))
+ return "".join(text_parts)
+
+
+def _get_text_from_reference(
+ reference: Optional[types.ResponseCandidate],
+) -> Optional[str]:
+ """Safely extracts text from a reference field."""
+ if reference and hasattr(reference, "response") and reference.response:
+ return _get_content_text(reference.response)
+ return None
+
+
+def _validate_case_consistency(
+ base_case: types.EvalCase,
+ current_case: types.EvalCase,
+ case_idx: int,
+ dataset_idx: int,
+) -> None:
+ """Logs warnings if prompt or reference mismatches occur."""
+ if base_case.prompt != current_case.prompt:
+ base_prompt_text_preview = _get_content_text(base_case.prompt)[:50]
+ current_prompt_text_preview = _get_content_text(current_case.prompt)[:50]
+ logger.warning(
+ "Prompt mismatch for case index %d between base dataset (0)"
+ " and dataset %d. Using prompt from base. Base prompt"
+ " preview: '%s...', Dataset"
+ " %d prompt preview: '%s...'",
+ case_idx,
+ dataset_idx,
+ base_prompt_text_preview,
+ dataset_idx,
+ current_prompt_text_preview,
+ )
+
+ base_ref_text = _get_text_from_reference(base_case.reference)
+ current_ref_text = _get_text_from_reference(current_case.reference)
+
+ if bool(base_case.reference) != bool(current_case.reference):
+ logger.warning(
+ "Reference presence mismatch for case index %d between base"
+ " dataset (0) and dataset %d. Using reference (or lack"
+ " thereof) from base.",
+ case_idx,
+ dataset_idx,
+ )
+ elif base_ref_text != current_ref_text:
+ logger.warning(
+ "Reference text mismatch for case index %d between base"
+ " dataset (0) and dataset %d. Using reference from base. "
+ " Base ref: '%s...', Current ref:"
+ " '%s...'",
+ case_idx,
+ dataset_idx,
+ str(base_ref_text)[:50],
+ str(current_ref_text)[:50],
+ )
+
+
+def merge_evaluation_datasets(
+ datasets: list[types.EvaluationDataset],
+ agent_info: Optional[types.evals.AgentInfo] = None,
+) -> types.EvaluationDataset:
+ """Merges multiple EvaluationDatasets into a single EvaluationDataset.
+
+ Assumes that each dataset has responses corresponding to the same set of
+ prompts, in the same order. The prompt, reference, system_instruction, and
+ conversation_history are taken from the first dataset.
+ """
+ if not datasets:
+ raise ValueError("Input 'datasets' cannot be empty.")
+
+ num_expected_cases = 0
+ if datasets[0].eval_cases:
+ num_expected_cases = len(datasets[0].eval_cases)
+
+ if num_expected_cases == 0:
+ logger.warning(
+ "The first dataset has no evaluation cases. Result will be empty."
+ )
+ return types.EvaluationDataset(eval_cases=[])
+
+ for i, ds in enumerate(datasets):
+ current_len = len(ds.eval_cases) if ds.eval_cases else 0
+ if current_len != num_expected_cases:
+ raise ValueError(
+ "All datasets must have the same number of evaluation cases. "
+ "Base dataset (0) has %s, but dataset %s has %s."
+ % (num_expected_cases, i, current_len)
+ )
+
+ merged_eval_cases: list[types.EvalCase] = []
+ base_parsed_dataset = datasets[0]
+
+ for case_idx in range(num_expected_cases):
+ base_eval_case: types.EvalCase = (
+ base_parsed_dataset.eval_cases[case_idx]
+ if base_parsed_dataset.eval_cases
+ else types.EvalCase()
+ )
+ candidate_responses: list[types.ResponseCandidate] = []
+
+ if base_eval_case.responses:
+ candidate_responses.append(base_eval_case.responses[0])
+ elif base_eval_case.agent_data:
+ candidate_responses.append(_create_placeholder_response_candidate(""))
+ else:
+ logger.warning(
+ "No response or agent data found for base dataset (index 0) in case %s. "
+ "Adding placeholder.",
+ case_idx,
+ )
+ candidate_responses.append(
+ _create_placeholder_response_candidate(
+ "Missing response from base dataset (0) for case %s" % case_idx
+ )
+ )
+
+ eval_case_custom_columns = base_eval_case.model_dump(
+ exclude={
+ "eval_case_id",
+ "prompt",
+ "responses",
+ "reference",
+ "system_instruction",
+ "conversation_history",
+ "intermediate_events",
+ "agent_data",
+ "agent_info",
+ },
+ exclude_none=True,
+ )
+ for dataset_idx_offset, current_parsed_ds in enumerate(datasets[1:], start=1):
+ current_ds_eval_case: types.EvalCase = (
+ current_parsed_ds.eval_cases[case_idx]
+ if current_parsed_ds.eval_cases
+ else types.EvalCase()
+ )
+
+ _validate_case_consistency(
+ base_eval_case, current_ds_eval_case, case_idx, dataset_idx_offset
+ )
+
+ current_ds_extra_attrs = current_ds_eval_case.model_dump(
+ exclude={
+ "eval_case_id",
+ "prompt",
+ "responses",
+ "reference",
+ "system_instruction",
+ "conversation_history",
+ "intermediate_events",
+ "agent_data",
+ "agent_info",
+ },
+ exclude_none=True,
+ )
+ eval_case_custom_columns.update(current_ds_extra_attrs)
+
+ if current_ds_eval_case.responses:
+ candidate_responses.append(current_ds_eval_case.responses[0])
+ elif current_ds_eval_case.agent_data:
+ candidate_responses.append(_create_placeholder_response_candidate(""))
+ else:
+ logger.warning(
+ "No response or agent data found for dataset %s in case %s. Adding"
+ " placeholder.",
+ dataset_idx_offset,
+ case_idx,
+ )
+ candidate_responses.append(
+ _create_placeholder_response_candidate(
+ "Missing response from dataset %s for case %s"
+ % (dataset_idx_offset, case_idx)
+ )
+ )
+
+ merged_case = types.EvalCase(
+ eval_case_id=base_eval_case.eval_case_id
+ or "merged_eval_case_%s" % case_idx,
+ prompt=base_eval_case.prompt,
+ responses=candidate_responses if candidate_responses else None,
+ reference=base_eval_case.reference,
+ system_instruction=base_eval_case.system_instruction,
+ conversation_history=base_eval_case.conversation_history,
+ agent_info=agent_info or base_eval_case.agent_info,
+ agent_data=base_eval_case.agent_data,
+ intermediate_events=base_eval_case.intermediate_events,
+ **eval_case_custom_columns,
+ )
+ merged_eval_cases.append(merged_case)
+
+ return types.EvaluationDataset(eval_cases=merged_eval_cases)
+
+
+def merge_response_datasets_into_canonical_format(
+ raw_datasets: list[list[dict[str, Any]]],
+ schemas: list[str],
+ agent_info: Optional[types.evals.AgentInfo] = None,
+) -> types.EvaluationDataset:
+ """Merges multiple raw response datasets into a single EvaluationDataset.
+
+ Assumes that each dataset in raw_datasets has responses corresponding
+ to the same set of prompts, in the same order. The prompt, reference,
+ system_instruction, and conversation_history are taken from the first dataset.
+ """
+ if not isinstance(raw_datasets, list):
+ raise TypeError(
+ "Input 'raw_datasets' must be a list, got %s." % type(raw_datasets)
+ )
+ if not raw_datasets or not all(isinstance(ds, list) for ds in raw_datasets):
+ raise ValueError(
+ "Input 'raw_datasets' cannot be empty and must be a list of lists."
+ )
+ if not schemas or len(schemas) != len(raw_datasets):
+ raise ValueError(
+ "A list of schemas must be provided, one for each raw dataset. "
+ "Got %s schemas for %s datasets." % (len(schemas), len(raw_datasets))
+ )
+
+ parsed_evaluation_datasets: list[types.EvaluationDataset] = []
+ for i, (raw_ds_entry, schema) in enumerate(zip(raw_datasets, schemas)):
+ converter = get_dataset_converter(schema)
+ parsed_evaluation_datasets.append(converter.convert(raw_ds_entry))
+
+ return merge_evaluation_datasets(parsed_evaluation_datasets, agent_info)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_handlers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..4571802dbc6498198f00a43c94039c7a9bd8a2db
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_handlers.py
@@ -0,0 +1,1755 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Handlers for computing evaluation metrics."""
+
+import abc
+import collections
+from concurrent import futures
+import json
+import logging
+import random
+import statistics
+import time
+from typing import Any, Callable, Generic, Optional, TypeVar, Union
+
+from google.genai import errors as genai_errors
+from google.genai import _common
+from google.genai import types as genai_types
+from tqdm import tqdm
+from typing_extensions import override
+
+from . import _evals_common
+from . import _evals_constant
+from . import _evals_utils
+from . import evals
+from . import types
+
+
+logger = logging.getLogger(__name__)
+_MAX_RETRIES = 5
+# HTTP status codes that are safe to retry with backoff.
+_RETRYABLE_STATUS_CODES = frozenset(
+ {
+ 408, # RequestTimeout (DEADLINE_EXCEEDED)
+ 409, # Conflict / Aborted (ABORTED)
+ 429, # TooManyRequests / ResourceExhausted (RESOURCE_EXHAUSTED)
+ 499, # Client Closed Request (CANCELLED)
+ 500, # InternalServerError (INTERNAL)
+ 502, # BadGateway
+ 503, # ServiceUnavailable (UNAVAILABLE)
+ 504, # GatewayTimeout (DEADLINE_EXCEEDED)
+ }
+)
+
+R = TypeVar("R")
+T = TypeVar("T", types.Metric, types.MetricSource, types.LLMMetric)
+
+
+def _call_with_retry(
+ fn: Callable[[], R],
+ metric_name: str,
+) -> R:
+ """Calls ``fn()`` with exponential backoff + jitter on retryable errors.
+
+ Retries up to ``_MAX_RETRIES`` times on errors whose HTTP status code is
+ in ``_RETRYABLE_STATUS_CODES`` (Aborted, DeadlineExceeded,
+ ResourceExhausted, ServiceUnavailable, Cancelled). Non-retryable errors
+ are re-raised immediately. If all retries are exhausted the last
+ exception is re-raised so the caller can decide how to handle it.
+
+ Args:
+ fn: A zero-argument callable that performs the API call.
+ metric_name: Name of the metric, used for log messages.
+
+ Returns:
+ The return value of ``fn()``.
+
+ Raises:
+ genai_errors.APIError: If all retries are exhausted or the error is
+ not retryable.
+ """
+ for attempt in range(_MAX_RETRIES):
+ try:
+ return fn()
+ except genai_errors.APIError as e:
+ if e.code in _RETRYABLE_STATUS_CODES:
+ backoff = 2**attempt + random.uniform(0, 1)
+ logger.warning(
+ "Retryable error (code=%s) on attempt %d/%d for metric"
+ " '%s': %s. Retrying in %.1f seconds...",
+ e.code,
+ attempt + 1,
+ _MAX_RETRIES,
+ metric_name,
+ e,
+ backoff,
+ )
+ if attempt == _MAX_RETRIES - 1:
+ raise
+ time.sleep(backoff)
+ else:
+ raise
+ raise genai_errors.APIError(
+ code=504, response_json={"message": "Retries exhausted"}
+ )
+
+
+def _has_tool_call(events: Optional[list[Any]]) -> bool:
+ """Checks if any event in events has a function call."""
+ if not events:
+ return False
+ for event in events:
+ if getattr(event, "content", None) and getattr(event.content, "parts", None):
+ for part in event.content.parts:
+ if hasattr(part, "function_call") and part.function_call:
+ return True
+ return False
+
+
+def _extract_text_from_content(
+ content: Optional[genai_types.Content], warn_property: str = "text"
+) -> Optional[str]:
+ """Extracts and concatenates all text parts from a Content object."""
+ if not content or not content.parts:
+ return None
+
+ text_accumulator = ""
+ any_text_part_found = False
+ non_text_part_names = []
+
+ for part_obj in content.parts:
+ part_dump = part_obj.model_dump(exclude={"text", "thought"})
+ for field_name, field_value in part_dump.items():
+ if field_value is not None:
+ if field_name not in non_text_part_names:
+ non_text_part_names.append(field_name)
+
+ if isinstance(part_obj.text, str):
+ if (
+ hasattr(part_obj, "thought")
+ and isinstance(part_obj.thought, bool)
+ and part_obj.thought
+ ):
+ continue
+ any_text_part_found = True
+ text_accumulator += part_obj.text
+
+ if non_text_part_names and any_text_part_found:
+ logger.warning(
+ "Warning: content contains non-text parts: %s. Returning"
+ " concatenated %s result from text parts. Inspect individual parts"
+ " for full content.",
+ non_text_part_names,
+ warn_property,
+ )
+ return text_accumulator if any_text_part_found else None
+
+
+def _get_prompt_from_eval_case(
+ eval_case: types.EvalCase,
+) -> Optional[genai_types.Content]:
+ """Extracts prompt content from eval_case.prompt or starting_prompt."""
+ if eval_case.prompt:
+ return eval_case.prompt
+
+ user_scenario = getattr(eval_case, "user_scenario", None)
+ if user_scenario and user_scenario.starting_prompt:
+ return genai_types.Content(
+ parts=[genai_types.Part(text=user_scenario.starting_prompt)]
+ )
+
+ return None
+
+
+def _get_response_from_eval_case(
+ eval_case: types.EvalCase, response_index: int, metric_name: str
+) -> Optional[genai_types.Content]:
+ """Extracts response content from eval_case.responses."""
+ response_content = None
+ if eval_case.responses and response_index < len(eval_case.responses):
+ response_content = eval_case.responses[response_index].response
+
+ return response_content
+
+
+def _value_to_content_list(value: Any) -> list[genai_types.Content]:
+ """Converts a value to a list of Content objects."""
+ if isinstance(value, genai_types.Content):
+ return [value]
+ if isinstance(value, types.ResponseCandidate):
+ return [value.response] if value.response else []
+ if isinstance(value, list) and value:
+ if isinstance(value[0], genai_types.Content):
+ return value
+ if isinstance(value[0], types.evals.Message):
+ history_texts = []
+ for msg_obj in value:
+ msg_text = _extract_text_from_content(msg_obj.content)
+ if msg_text:
+ role = msg_obj.content.role or msg_obj.author or "user"
+ history_texts.append(f"{role}: {msg_text}")
+ return [
+ genai_types.Content(
+ parts=[genai_types.Part(text="\n".join(history_texts))]
+ )
+ ]
+ return [genai_types.Content(parts=[genai_types.Part(text=json.dumps(value))])]
+ if isinstance(value, dict):
+ return [genai_types.Content(parts=[genai_types.Part(text=json.dumps(value))])]
+ return [genai_types.Content(parts=[genai_types.Part(text=str(value))])]
+
+
+def _get_autorater_config(metric: types.Metric) -> dict[str, Any]:
+ """Extracts autorater config settings from a metric."""
+ autorater_config: dict[str, Any] = {}
+ if metric.judge_model:
+ autorater_config["autorater_model"] = metric.judge_model
+ if metric.judge_model_generation_config:
+ autorater_config["generation_config"] = metric.judge_model_generation_config
+ if metric.judge_model_sampling_count:
+ autorater_config["sampling_count"] = metric.judge_model_sampling_count
+ return autorater_config
+
+
+def _default_aggregate_scores(
+ metric_name: str,
+ eval_case_metric_results: list[types.EvalCaseMetricResult],
+ calculate_pass_rate: bool = False,
+) -> types.AggregatedMetricResult:
+ """Default aggregation logic using mean and standard deviation."""
+ scores = []
+ num_error = 0
+ num_valid = 0
+ num_passing = 0
+
+ for result in eval_case_metric_results:
+ if result.error_message is None and result.score is not None:
+ try:
+ score = float(result.score)
+ scores.append(score)
+ num_valid += 1
+ if calculate_pass_rate and score == 1.0:
+ num_passing += 1
+ except (ValueError, TypeError):
+ logger.warning(
+ "Could not convert score '%s' to float for metric '%s' during"
+ " default aggregation. Counting as error.",
+ result.score,
+ metric_name,
+ )
+ num_error += 1
+ else:
+ num_error += 1
+
+ mean_score = None
+ stdev_score = None
+ pass_rate = None
+
+ if num_valid > 0:
+ try:
+ mean_score = statistics.mean(scores)
+ except statistics.StatisticsError as e:
+ logger.warning("Could not calculate mean for %s: %s", metric_name, e)
+ if calculate_pass_rate:
+ pass_rate = num_passing / num_valid
+
+ if num_valid > 1:
+ try:
+ stdev_score = statistics.stdev(scores)
+ except statistics.StatisticsError as e:
+ logger.warning("Could not calculate stdev for %s: %s", metric_name, e)
+
+ return types.AggregatedMetricResult(
+ metric_name=metric_name,
+ num_cases_total=len(eval_case_metric_results),
+ num_cases_valid=num_valid,
+ num_cases_error=num_error,
+ mean_score=mean_score,
+ stdev_score=stdev_score,
+ pass_rate=pass_rate if calculate_pass_rate else None,
+ )
+
+
+class MetricHandler(abc.ABC, Generic[T]):
+ """Abstract base class for metric handlers."""
+
+ def __init__(self, module: "evals.Evals", metric: T):
+ self.module = module
+ self.metric: T = metric
+
+ @property
+ @abc.abstractmethod
+ def metric_name(self) -> str:
+ """Returns the name of the metric polymorphically."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case for a specific metric."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a specific metric."""
+ raise NotImplementedError()
+
+
+class ComputationMetricHandler(MetricHandler[types.Metric]):
+ """Metric handler for computation metrics."""
+
+ SUPPORTED_COMPUTATION_METRICS = frozenset(
+ {
+ "exact_match",
+ "bleu",
+ "rouge_1",
+ "rouge_l_sum",
+ "tool_call_valid",
+ "tool_name_match",
+ "tool_parameter_key_match",
+ "tool_parameter_kv_match",
+ # TODO b/423934249 - Add trajectory metrics once they are supported.
+ }
+ )
+
+ @property
+ def metric_name(self) -> str:
+ return self.metric.name or "unknown_metric"
+
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
+ super().__init__(module=module, metric=metric)
+ if self.metric.name not in self.SUPPORTED_COMPUTATION_METRICS:
+ raise ValueError(
+ f"Metric '{self.metric.name}' is not supported for computation."
+ )
+
+ def _build_request_payload(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> dict[str, Any]:
+ """Builds the request parameters for evaluate instances."""
+ request_payload = {}
+
+ response_content = _get_response_from_eval_case(
+ eval_case, response_index, self.metric.name
+ )
+ prediction_text = _extract_text_from_content(response_content)
+
+ if prediction_text is None:
+ raise ValueError(
+ f"Response text missing for candidate {response_index} in eval_case"
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
+ )
+
+ if (
+ eval_case.reference is None
+ or _extract_text_from_content(eval_case.reference.response) is None
+ ):
+ raise ValueError(
+ "Reference text missing for eval_case"
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
+ )
+ logger.debug("eval_case: %s", eval_case)
+
+ if self.metric.name and self.metric.name.startswith("rouge"):
+ request_payload["rouge_input"] = {
+ "metric_spec": {
+ "rouge_type": (
+ "rougeLsum" if self.metric.name == "rouge_l_sum" else "rouge1"
+ ),
+ },
+ "instances": [
+ {
+ "prediction": prediction_text,
+ "reference": _extract_text_from_content(
+ eval_case.reference.response
+ ),
+ }
+ ],
+ }
+ else:
+ request_payload[f"{self.metric.name}_input"] = {
+ "metric_spec": {},
+ "instances": [
+ {
+ "prediction": prediction_text,
+ "reference": _extract_text_from_content(
+ eval_case.reference.response
+ ),
+ }
+ ],
+ }
+ logger.debug("request_payload: %s", request_payload)
+ return request_payload
+
+ @override
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case for a specific computation metric."""
+
+ metric_name = self.metric.name
+ logger.debug(
+ "ComputationMetricHandler: Processing '%s' for case: %s",
+ metric_name,
+ eval_case.model_dump(exclude_none=True),
+ )
+ response = _call_with_retry(
+ lambda: self.module.evaluate_instances(
+ metric_config=self._build_request_payload(eval_case, response_index)
+ ).model_dump(exclude_none=True),
+ metric_name,
+ )
+ logger.debug("response: %s", response)
+ score = None
+ for _, result_value in response.items():
+ if isinstance(result_value, dict) and result_value:
+ for _, metric_value in result_value.items():
+ if isinstance(metric_value, list) and metric_value:
+ score = metric_value[0]["score"]
+ break
+ logger.debug("Metric result: %s", score)
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ score=score,
+ )
+
+ @override
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a computation metric."""
+ logger.debug("Aggregating results for computation metric: %s", self.metric.name)
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
+
+
+class TranslationMetricHandler(MetricHandler[types.Metric]):
+ """Metric handler for translation metrics."""
+
+ SUPPORTED_TRANSLATION_METRICS = frozenset({"comet", "metricx"})
+
+ @property
+ def metric_name(self) -> str:
+ return self.metric.name or "unknown_metric"
+
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
+ super().__init__(module=module, metric=metric)
+
+ if self.metric.name not in self.SUPPORTED_TRANSLATION_METRICS:
+ raise ValueError(
+ f"Metric '{self.metric.name}' is not supported for translation."
+ )
+
+ def _build_request_payload(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> dict[str, Any]:
+ """Builds the request parameters for evaluate instances."""
+ request_payload = {}
+ metric_input_name = f"{self.metric.name}_input"
+ version = None
+ if hasattr(self.metric, "version"):
+ version = self.metric.version
+ elif self.metric.name == "comet":
+ version = "COMET_22_SRC_REF"
+ elif self.metric.name == "metricx":
+ version = "METRICX_24_SRC_REF"
+
+ source_language = None
+ target_language = None
+ if hasattr(self.metric, "source_language"):
+ source_language = self.metric.source_language
+ if hasattr(self.metric, "target_language"):
+ target_language = self.metric.target_language
+
+ response_content = _get_response_from_eval_case(
+ eval_case, response_index, self.metric.name
+ )
+ prediction_text = _extract_text_from_content(response_content)
+ prompt_text = _extract_text_from_content(_get_prompt_from_eval_case(eval_case))
+
+ if prediction_text is None:
+ raise ValueError(
+ f"Response text missing for candidate {response_index} in eval_case"
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
+ )
+
+ if (
+ eval_case.reference is None
+ or _extract_text_from_content(eval_case.reference.response) is None
+ ):
+ raise ValueError(
+ "Reference text missing for eval_case"
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
+ )
+ if prompt_text is None:
+ raise ValueError(
+ "Prompt text (source for translation) missing for eval_case"
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
+ )
+
+ request_payload[metric_input_name] = {
+ "metric_spec": {
+ "version": version,
+ "source_language": source_language,
+ "target_language": target_language,
+ },
+ "instance": {
+ "prediction": prediction_text,
+ "reference": _extract_text_from_content(eval_case.reference.response),
+ "source": prompt_text,
+ },
+ }
+ return request_payload
+
+ @override
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case for a specific translation metric."""
+ metric_name = self.metric.name
+ logger.debug(
+ "TranslationMetricHandler: Processing '%s' for case: %s",
+ metric_name,
+ eval_case,
+ )
+ api_response = _call_with_retry(
+ lambda: self.module.evaluate_instances(
+ metric_config=self._build_request_payload(eval_case, response_index)
+ ),
+ metric_name,
+ )
+ logger.debug("API Response: %s", api_response)
+
+ score = None
+ error_message = None
+
+ try:
+ if metric_name == "comet":
+ if api_response and api_response.comet_result:
+ score = api_response.comet_result.score
+ else:
+ logger.warning(
+ "Comet result missing in API response for metric '%s'."
+ " API response: %s",
+ metric_name,
+ (
+ api_response.model_dump_json(exclude_none=True)
+ if api_response
+ else "None"
+ ),
+ )
+ elif metric_name == "metricx":
+ if api_response and api_response.metricx_result:
+ score = api_response.metricx_result.score
+ else:
+ logger.warning(
+ "MetricX result missing in API response for metric '%s'."
+ " API response: %s",
+ metric_name,
+ (
+ api_response.model_dump_json(exclude_none=True)
+ if api_response
+ else "None"
+ ),
+ )
+ if score is None and not error_message:
+ logger.warning(
+ "Score could not be extracted for translation metric '%s'."
+ " API response: %s",
+ metric_name,
+ (
+ api_response.model_dump_json(exclude_none=True)
+ if api_response
+ else "None"
+ ),
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Error processing/extracting score for translation metric '%s': %s."
+ " API response: %s",
+ metric_name,
+ e,
+ (
+ api_response.model_dump_json(exclude_none=True)
+ if api_response
+ else "None"
+ ),
+ exc_info=True,
+ )
+ error_message = f"Error extracting score: {e}"
+
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ score=score,
+ error_message=error_message,
+ )
+
+ @override
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a translation metric."""
+ logger.debug("Aggregating results for translation metric: %s", self.metric.name)
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
+
+
+def _content_to_instance_data(
+ content: Optional[genai_types.Content],
+) -> Optional[types.evals.InstanceData]:
+ """Converts a genai_types.Content object to a types.InstanceData object."""
+ if not content:
+ return None
+ return types.evals.InstanceData(
+ contents=types.evals.InstanceDataContents(contents=[content])
+ )
+
+
+def _eval_case_to_agent_data(
+ eval_case: types.EvalCase,
+ prompt_content: Optional[genai_types.Content] = None,
+ response_content: Optional[genai_types.Content] = None,
+) -> Optional[types.evals.AgentData]:
+ """Converts an EvalCase object to a single turn AgentData object.
+
+ If `eval_case.agent_data` is provided, it is returned directly, and
+ `prompt_content` and `response_content` are ignored.
+ """
+ if getattr(eval_case, "agent_data", None):
+ return eval_case.agent_data
+
+ if (
+ not eval_case.agent_info
+ and not eval_case.intermediate_events
+ and not prompt_content
+ and not response_content
+ ):
+ return None
+
+ agents_map = eval_case.agent_info.agents if eval_case.agent_info else None
+ events = []
+ if prompt_content:
+ events.append(types.evals.AgentEvent(author="user", content=prompt_content))
+
+ if eval_case.intermediate_events:
+ for event in eval_case.intermediate_events:
+ events.append(
+ types.evals.AgentEvent(
+ author=event.author,
+ content=event.content,
+ event_time=event.creation_timestamp,
+ )
+ )
+
+ if response_content:
+ events.append(types.evals.AgentEvent(author="model", content=response_content))
+
+ turns = (
+ [types.evals.ConversationTurn(turn_index=0, turn_id="turn_0", events=events)]
+ if events
+ else None
+ )
+ return types.evals.AgentData(agents=agents_map, turns=turns)
+
+
+def _build_evaluation_instance(
+ eval_case: types.EvalCase,
+ response_content: Optional[genai_types.Content],
+ prompt_instance_data: Optional[types.evals.InstanceData] = None,
+ prompt_template: Optional[str] = None,
+) -> types.EvaluationInstance:
+ """Builds a unified EvaluationInstance. Multi-turn logic is handled by the caller."""
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
+
+ # 1. Use caller-provided prompt data (multi-turn) or default to simple content
+ if prompt_instance_data is None:
+ prompt_instance_data = _content_to_instance_data(extracted_prompt)
+
+ # 2. Collect placeholders for other_data
+ other_data_map: dict[str, Any] = {}
+ if hasattr(eval_case, "context") and eval_case.context:
+ if isinstance(eval_case.context, str):
+ other_data_map["context"] = types.evals.InstanceData(text=eval_case.context)
+ elif isinstance(eval_case.context, genai_types.Content):
+ other_data_map["context"] = _content_to_instance_data(eval_case.context)
+
+ # 3. Extract custom variables from LLMMetric templates
+ if prompt_template:
+ template_vars = types.PromptTemplate(text=prompt_template).variables
+ standard_fields = {"prompt", "response", "reference", "context", "agent_data"}
+ for full_path in template_vars:
+ # Extract the root variable (e.g. 'metadata' from 'metadata.user_id')
+ root_var = full_path.split(".")[0].split("[")[0]
+
+ if root_var not in standard_fields and hasattr(eval_case, root_var):
+ val = getattr(eval_case, root_var)
+ # Add the root object to other_data so the backend can traverse it
+ other_data_map[root_var] = types.evals.InstanceData(
+ contents=types.evals.InstanceDataContents(
+ contents=_value_to_content_list(val)
+ )
+ )
+
+ return types.EvaluationInstance(
+ prompt=prompt_instance_data,
+ response=_content_to_instance_data(response_content),
+ reference=(
+ _content_to_instance_data(eval_case.reference.response)
+ if eval_case.reference
+ else None
+ ),
+ rubric_groups=eval_case.rubric_groups,
+ other_data=(
+ types.MapInstance(map_instance=other_data_map) if other_data_map else None
+ ),
+ agent_data=_eval_case_to_agent_data(
+ eval_case, extracted_prompt, response_content
+ ),
+ )
+
+
+class LLMMetricHandler(MetricHandler[types.LLMMetric]):
+ """Metric handler for LLM metrics."""
+
+ @property
+ def metric_name(self) -> str:
+ return self.metric.name or "unknown_metric"
+
+ def __init__(self, module: "evals.Evals", metric: types.LLMMetric):
+ super().__init__(module=module, metric=metric)
+
+ @override
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case using the unified backend interface."""
+ try:
+ response_content = _get_response_from_eval_case(
+ eval_case, response_index, self.metric_name
+ )
+ if not response_content:
+ raise ValueError(
+ f"Response content missing for candidate {response_index}."
+ )
+
+ instance = _build_evaluation_instance(
+ eval_case, response_content, prompt_template=self.metric.prompt_template
+ )
+ api_response = _call_with_retry(
+ lambda: self.module._evaluate_instances(
+ metrics=[self.metric],
+ instance=instance,
+ ),
+ self.metric_name,
+ )
+
+ if api_response and api_response.metric_results:
+ result = api_response.metric_results[0]
+ error_msg = None
+ if result.error and getattr(result.error, "code"):
+ error_msg = f"Error in metric result: {result.error}"
+
+ return types.EvalCaseMetricResult(
+ metric_name=self.metric_name,
+ score=result.score,
+ explanation=result.explanation,
+ rubric_verdicts=result.rubric_verdicts,
+ error_message=error_msg,
+ )
+ else:
+ return types.EvalCaseMetricResult(
+ metric_name=self.metric_name,
+ error_message="Metric results missing in API response.",
+ )
+
+ except Exception as e:
+ logger.error(
+ "Error processing metric %s for case %s.",
+ self.metric_name,
+ eval_case.eval_case_id,
+ exc_info=True,
+ )
+ return types.EvalCaseMetricResult(
+ metric_name=self.metric_name, error_message=str(e)
+ )
+
+ @override
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a LLM metric."""
+ if self.metric.aggregate_summary_fn and callable(
+ self.metric.aggregate_summary_fn
+ ):
+ logger.info(
+ "Using custom aggregate_summary_fn for metric '%s'", self.metric.name
+ )
+ try:
+ custom_summary_dict = self.metric.aggregate_summary_fn(
+ eval_case_metric_results
+ )
+ if not isinstance(custom_summary_dict, dict):
+ raise TypeError("aggregate_summary_fn must return a dictionary.")
+
+ num_cases_total = len(eval_case_metric_results)
+ num_cases_error = len(
+ [
+ result
+ for result in eval_case_metric_results
+ if result.error_message is not None
+ ]
+ )
+ num_cases_valid = num_cases_total - num_cases_error
+ required_fields = {
+ "num_cases_total": num_cases_total,
+ "num_cases_error": num_cases_error,
+ "num_cases_valid": num_cases_valid,
+ }
+ final_summary_dict = {**required_fields, **custom_summary_dict}
+
+ return types.AggregatedMetricResult(
+ metric_name=self.metric.name,
+ **final_summary_dict,
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Error executing custom aggregate_summary_fn for metric '%s': %s."
+ " Falling back to default aggregation.",
+ self.metric.name,
+ e,
+ exc_info=True,
+ )
+ return _default_aggregate_scores(
+ self.metric.name, eval_case_metric_results
+ )
+ else:
+ logger.debug(
+ "Using default aggregation for LLM metric '%s'", self.metric.name
+ )
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
+
+
+class CustomMetricHandler(MetricHandler[types.Metric]):
+ """Metric handler for custom metrics."""
+
+ @property
+ def metric_name(self) -> str:
+ return self.metric.name or "unknown_metric"
+
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
+ super().__init__(module=module, metric=metric)
+
+ if not self.metric.custom_function:
+ raise ValueError(
+ f"CustomMetricHandler for '{self.metric.name}' needs "
+ " Metric.custom_function to be set."
+ )
+ if not isinstance(self.metric.custom_function, Callable):
+ raise ValueError(
+ f"CustomMetricHandler for '{self.metric.name}' needs "
+ " Metric.custom_function to be a callable function."
+ )
+
+ @override
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case for a custom metric."""
+ metric_name = self.metric.name
+ logger.debug(
+ "CustomMetricHandler: Processing '%s' for case: %s",
+ metric_name,
+ eval_case.model_dump(exclude_none=True),
+ )
+
+ try:
+ response_content = _get_response_from_eval_case(
+ eval_case, response_index, metric_name
+ )
+ except ValueError as e:
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ error_message=str(e),
+ )
+
+ if not response_content:
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ error_message=(
+ f"No response found for candidate {response_index} in EvalCase"
+ f" {eval_case.eval_case_id}."
+ ),
+ )
+
+ instance_for_custom_fn = eval_case.model_dump(
+ exclude={"responses"}, mode="json", exclude_none=True
+ )
+ instance_for_custom_fn["response"] = response_content.model_dump(
+ mode="json", exclude_none=True
+ )
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
+ if extracted_prompt:
+ instance_for_custom_fn["prompt"] = extracted_prompt.model_dump(
+ mode="json", exclude_none=True
+ )
+
+ error_msg = None
+ score = None
+ explanation = None
+ try:
+ if self.metric.custom_function and callable(self.metric.custom_function):
+ custom_function_result = self.metric.custom_function(
+ instance_for_custom_fn
+ )
+
+ if isinstance(custom_function_result, types.EvalCaseMetricResult):
+ return custom_function_result
+ elif (
+ isinstance(custom_function_result, dict)
+ and "score" in custom_function_result
+ ):
+ score = custom_function_result["score"]
+ explanation = custom_function_result.get("explanation", None)
+ elif isinstance(custom_function_result, (float, int)):
+ score = custom_function_result
+ explanation = None
+ else:
+ error_msg = (
+ f"CustomFunctionError({self.metric.custom_function}): Returned"
+ f" unexpected type {type(custom_function_result)}"
+ )
+
+ except Exception as e: # pylint: disable=broad-exception-caught
+ if self.metric.custom_function and hasattr(
+ self.metric.custom_function, "__name__"
+ ):
+ custom_function_name = self.metric.custom_function.__name__
+ else:
+ custom_function_name = "unknown_custom_function"
+ error_msg = f"CustomFunctionError({custom_function_name}): {e}"
+ score = None
+ explanation = None
+
+ return types.EvalCaseMetricResult(
+ metric_name=self.metric.name,
+ score=score,
+ explanation=explanation,
+ error_message=error_msg,
+ )
+
+ @override
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a custom metric."""
+ logger.debug("Aggregating results for custom metric: %s", self.metric.name)
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
+
+
+class PredefinedMetricHandler(MetricHandler[types.Metric]):
+ """Metric handler for predefined metrics."""
+
+ @property
+ def metric_name(self) -> str:
+ return self.metric.name or "unknown_metric"
+
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
+ super().__init__(module=module, metric=metric)
+ if self.metric.name not in _evals_constant.SUPPORTED_PREDEFINED_METRICS:
+ raise ValueError(
+ f"Metric '{self.metric.name}' is not a supported predefined metric."
+ )
+
+ def _build_request_payload(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> dict[str, Any]:
+ """Builds the request parameters for evaluate instances request."""
+ response_content = _get_response_from_eval_case(
+ eval_case, response_index, self.metric.name
+ )
+
+ if not response_content and not getattr(eval_case, "agent_data", None):
+ raise ValueError(
+ f"Response content missing for candidate {response_index}."
+ )
+
+ if self.metric.name == "tool_use_quality_v1":
+ has_tool_call = _has_tool_call(eval_case.intermediate_events)
+
+ # Check agent_data for tool calls if intermediate_events is empty
+ agent_data = getattr(eval_case, "agent_data", None)
+ if not has_tool_call and agent_data:
+ for turn in agent_data.turns or []:
+ if _has_tool_call(turn.events):
+ has_tool_call = True
+ break
+
+ if not has_tool_call:
+ logger.warning(
+ "Metric 'tool_use_quality_v1' requires tool usage in "
+ "'intermediate_events' or 'agent_data', but no tool usage was found for case %s.",
+ eval_case.eval_case_id,
+ )
+
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
+ prompt_instance_data = None
+ if self.metric.name and self.metric.name.startswith("multi_turn"):
+ prompt_contents = [
+ msg.content for msg in (eval_case.conversation_history or [])
+ ]
+ if extracted_prompt:
+ prompt_contents.append(extracted_prompt)
+ prompt_instance_data = types.evals.InstanceData(
+ contents=types.evals.InstanceDataContents(contents=prompt_contents)
+ )
+
+ instance_payload = _build_evaluation_instance(
+ eval_case=eval_case,
+ response_content=response_content,
+ prompt_instance_data=prompt_instance_data,
+ )
+
+ request_payload: dict[str, Any] = {
+ "instance": instance_payload,
+ }
+
+ autorater_config = _get_autorater_config(self.metric)
+ if autorater_config:
+ request_payload["autorater_config"] = genai_types.AutoraterConfig(
+ **autorater_config
+ )
+ return request_payload
+
+ @override
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case for a specific predefined metric."""
+ metric_name = self.metric.name
+ try:
+ payload = self._build_request_payload(eval_case, response_index)
+ api_response = _call_with_retry(
+ lambda: self.module._evaluate_instances(
+ metrics=[self.metric],
+ instance=payload.get("instance"),
+ autorater_config=payload.get("autorater_config"),
+ ),
+ metric_name,
+ )
+
+ if (
+ api_response
+ and hasattr(api_response, "metric_results")
+ and api_response.metric_results
+ ):
+ result_data = api_response.metric_results[0]
+
+ error_message = None
+ if result_data.error and getattr(result_data.error, "code"):
+ error_message = f"Error in metric result: {result_data.error}"
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ score=result_data.score,
+ explanation=result_data.explanation,
+ rubric_verdicts=result_data.rubric_verdicts,
+ error_message=error_message,
+ )
+ else:
+ logger.error(
+ "Metric results missing in API response for predefined metric '%s'."
+ " API response: %s",
+ metric_name,
+ (
+ api_response.model_dump_json(exclude_none=True)
+ if api_response
+ else "None"
+ ),
+ )
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ error_message="Metric results missing in API response.",
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Error processing metric %s for case %s: %s",
+ metric_name,
+ eval_case.eval_case_id,
+ e,
+ exc_info=True,
+ )
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name, error_message=str(e)
+ )
+
+ @override
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a predefined metric."""
+ logger.debug("Aggregating results for predefined metric: %s", self.metric.name)
+ return _default_aggregate_scores(
+ self.metric.name, eval_case_metric_results, calculate_pass_rate=True
+ )
+
+
+class CustomCodeExecutionMetricHandler(MetricHandler[types.Metric]):
+ """Metric handler for custom code execution metrics."""
+
+ @property
+ def metric_name(self) -> str:
+ return self.metric.name or "unknown_metric"
+
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
+ super().__init__(module=module, metric=metric)
+
+ if not self.metric.remote_custom_function and not self.metric.custom_function:
+ raise ValueError(
+ f"CustomCodeExecutionMetricHandler for '{self.metric.name}' needs "
+ " custom function to be set."
+ )
+
+ def _build_request_payload(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> dict[str, Any]:
+ """Builds the request parameters for evaluate instances request."""
+ response_content = _get_response_from_eval_case(
+ eval_case, response_index, self.metric.name
+ )
+
+ if not response_content and not getattr(eval_case, "agent_data", None):
+ raise ValueError(
+ f"Response content missing for candidate {response_index}."
+ )
+
+ reference_instance_data = None
+ if eval_case.reference:
+ reference_instance_data = _content_to_instance_data(
+ eval_case.reference.response
+ )
+
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
+ prompt_instance_data = _content_to_instance_data(extracted_prompt)
+
+ instance_payload = types.EvaluationInstance(
+ prompt=prompt_instance_data,
+ response=_content_to_instance_data(response_content),
+ reference=reference_instance_data,
+ agent_data=_eval_case_to_agent_data(eval_case),
+ )
+
+ return {
+ "instance": instance_payload,
+ }
+
+ @override
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case for a specific custom code execution metric."""
+ metric_name = self.metric.name
+ try:
+ payload = self._build_request_payload(eval_case, response_index)
+ api_response = _call_with_retry(
+ lambda: self.module._evaluate_instances(
+ metrics=[self.metric],
+ instance=payload.get("instance"),
+ ),
+ metric_name,
+ )
+
+ if (
+ api_response
+ and hasattr(api_response, "metric_results")
+ and api_response.metric_results
+ ):
+ result_data = api_response.metric_results[0]
+
+ error_message = None
+ if result_data.error and getattr(result_data.error, "code"):
+ error_message = f"Error in metric result: {result_data.error}"
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ score=result_data.score,
+ explanation=result_data.explanation,
+ error_message=error_message,
+ )
+ else:
+ logger.error(
+ "Metric results missing in API response for metric '%s'."
+ " API response: %s",
+ metric_name,
+ (
+ api_response.model_dump_json(exclude_none=True)
+ if api_response
+ else "None"
+ ),
+ )
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ error_message="Metric results missing in API response.",
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Error processing metric %s for case %s",
+ metric_name,
+ eval_case.eval_case_id,
+ exc_info=True,
+ )
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name, error_message=str(e)
+ )
+
+ @override
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a custom code execution metric."""
+ logger.debug(
+ "Aggregating results for custom code execution metric: %s", self.metric.name
+ )
+ return _default_aggregate_scores(
+ self.metric.name, eval_case_metric_results, calculate_pass_rate=True
+ )
+
+
+class RegisteredMetricHandler(MetricHandler[types.Metric]):
+ """Metric handler for registered metrics."""
+
+ def __init__(
+ self,
+ module: "evals.Evals",
+ metric: types.Metric,
+ ):
+ if isinstance(metric, dict):
+ metric = types.MetricSource(**metric)
+ super().__init__(module=module, metric=metric)
+
+ def _build_request_payload(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> dict[str, Any]:
+ """Builds request payload for registered metric by assembling EvaluationInstance."""
+ response_content = _get_response_from_eval_case(
+ eval_case, response_index, self.metric_name
+ )
+
+ if not response_content and not getattr(eval_case, "agent_data", None):
+ raise ValueError(
+ f"Response content missing for candidate {response_index}."
+ )
+
+ reference_instance_data = None
+ if eval_case.reference:
+ reference_instance_data = _content_to_instance_data(
+ eval_case.reference.response
+ )
+
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
+ prompt_instance_data = _content_to_instance_data(extracted_prompt)
+
+ instance_payload = types.EvaluationInstance(
+ prompt=prompt_instance_data,
+ response=_content_to_instance_data(response_content),
+ reference=reference_instance_data,
+ rubric_groups=eval_case.rubric_groups,
+ agent_data=_eval_case_to_agent_data(eval_case),
+ )
+
+ request_payload = {
+ "instance": instance_payload,
+ }
+ return request_payload
+
+ @property
+ def metric_name(self) -> str:
+ return self.metric.name or "unknown_metric"
+
+ @override
+ def get_metric_result(
+ self, eval_case: types.EvalCase, response_index: int
+ ) -> types.EvalCaseMetricResult:
+ """Processes a single evaluation case using a MetricSource reference."""
+ metric_name = self.metric_name
+ metric_source = types.MetricSource(
+ metric_resource_name=self.metric.metric_resource_name
+ )
+
+ try:
+ payload = self._build_request_payload(eval_case, response_index)
+ api_response = _call_with_retry(
+ lambda: self.module._evaluate_instances(
+ metric_sources=[metric_source],
+ instance=payload.get("instance"),
+ autorater_config=payload.get("autorater_config"),
+ ),
+ metric_name,
+ )
+
+ if api_response and api_response.metric_results:
+ result_data = api_response.metric_results[0]
+ error_message = None
+ if result_data.error and getattr(result_data.error, "code"):
+ error_message = f"Error in metric result: {result_data.error}"
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ score=result_data.score,
+ explanation=result_data.explanation,
+ rubric_verdicts=result_data.rubric_verdicts,
+ error_message=error_message,
+ )
+ else:
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ error_message="Metric results missing in API response.",
+ )
+ except Exception as e:
+ return types.EvalCaseMetricResult(
+ metric_name=metric_name, error_message=str(e)
+ )
+
+ @override
+ def aggregate(
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
+ ) -> types.AggregatedMetricResult:
+ """Aggregates the metric results for a registered metric."""
+ return _default_aggregate_scores(
+ self.metric_name, eval_case_metric_results, calculate_pass_rate=True
+ )
+
+
+_METRIC_HANDLER_MAPPING = [
+ (
+ lambda m: (
+ # Recognize the user-facing class
+ isinstance(m, types.CodeExecutionMetric)
+ and (hasattr(m, "custom_function") and m.custom_function)
+ )
+ or (hasattr(m, "remote_custom_function") and m.remote_custom_function)
+ # Recognize base Metric objects that have been coerced by Pydantic
+ or (
+ isinstance(m, types.Metric)
+ and isinstance(getattr(m, "custom_function", None), str)
+ ),
+ CustomCodeExecutionMetricHandler,
+ ),
+ (
+ lambda m: m.custom_function and isinstance(m.custom_function, Callable),
+ CustomMetricHandler,
+ ),
+ (
+ lambda m: getattr(m, "metric_resource_name", None) is not None,
+ RegisteredMetricHandler,
+ ),
+ (
+ lambda m: m.name in ComputationMetricHandler.SUPPORTED_COMPUTATION_METRICS,
+ ComputationMetricHandler,
+ ),
+ (
+ lambda m: m.name in TranslationMetricHandler.SUPPORTED_TRANSLATION_METRICS,
+ TranslationMetricHandler,
+ ),
+ (
+ lambda m: m.name in _evals_constant.SUPPORTED_PREDEFINED_METRICS,
+ PredefinedMetricHandler,
+ ),
+ (lambda m: isinstance(m, types.LLMMetric), LLMMetricHandler),
+]
+
+MetricHandlerType = TypeVar(
+ "MetricHandlerType",
+ ComputationMetricHandler,
+ TranslationMetricHandler,
+ LLMMetricHandler,
+ CustomMetricHandler,
+ CustomCodeExecutionMetricHandler,
+ PredefinedMetricHandler,
+)
+
+
+def get_handler_for_metric(
+ module: "evals.Evals", metric: types.Metric
+) -> Union[MetricHandlerType, Any]:
+ """Returns a metric handler for the given metric."""
+ for condition, handler_class in _METRIC_HANDLER_MAPPING:
+ if condition(metric): # type: ignore[no-untyped-call]
+ return handler_class(module=module, metric=metric)
+ raise ValueError(f"Unsupported metric: {metric.name}")
+
+
+def calculate_win_rates(eval_result: types.EvaluationResult) -> dict[str, Any]:
+ """Calculates win/tie rates for comparison results."""
+ if not eval_result.eval_case_results:
+ return {}
+ max_models = max(
+ (
+ len(case.response_candidate_results)
+ for case in eval_result.eval_case_results
+ if case.response_candidate_results
+ ),
+ default=0,
+ )
+ if max_models == 0:
+ return {}
+ stats: collections.defaultdict[str, dict[str, Any]] = collections.defaultdict(
+ lambda: {"wins": [0] * max_models, "ties": 0, "valid_comparisons": 0}
+ )
+ for case in eval_result.eval_case_results:
+ if not case.response_candidate_results:
+ continue
+ scores_by_metric = collections.defaultdict(list)
+ for idx, candidate in enumerate(case.response_candidate_results):
+ for name, res in (
+ candidate.metric_results.items() if candidate.metric_results else {}
+ ):
+ if res.score is not None:
+ scores_by_metric[name].append({"score": res.score, "cand_idx": idx})
+ for name, scores in scores_by_metric.items():
+ if not scores:
+ continue
+ stats[name]["valid_comparisons"] += 1
+ max_score = max(s["score"] for s in scores)
+ winners = [s["cand_idx"] for s in scores if s["score"] == max_score]
+ if len(winners) == 1:
+ stats[name]["wins"][winners[0]] += 1
+ else:
+ stats[name]["ties"] += 1
+ win_rates = {}
+ for name, metric_stats in stats.items():
+ if metric_stats["valid_comparisons"] > 0:
+ win_rates[name] = {
+ "win_rates": [
+ w / metric_stats["valid_comparisons"] for w in metric_stats["wins"]
+ ],
+ "tie_rate": metric_stats["ties"] / metric_stats["valid_comparisons"],
+ }
+ return win_rates
+
+
+def _aggregate_metric_results(
+ metric_handlers: list[MetricHandler[Any]],
+ eval_case_results: list[types.EvalCaseResult],
+) -> list[types.AggregatedMetricResult]:
+ """Aggregates results by calling the aggregate method of each handler."""
+ aggregated_metric_results = []
+ logger.info("Aggregating results per metric...")
+ for handler in metric_handlers:
+ metric_name = handler.metric_name
+ results_for_this_metric: list[types.EvalCaseMetricResult] = []
+ for case_result in eval_case_results:
+ if case_result.response_candidate_results:
+ for response_candidate_res in case_result.response_candidate_results:
+ if (
+ response_candidate_res.metric_results
+ and metric_name in response_candidate_res.metric_results
+ and isinstance(metric_name, str)
+ ):
+ results_for_this_metric.append(
+ response_candidate_res.metric_results[metric_name]
+ )
+ if not results_for_this_metric:
+ logger.warning(
+ "No results found for metric '%s' to aggregate.", metric_name
+ )
+ continue
+
+ try:
+ summary = handler.aggregate(results_for_this_metric)
+ aggregated_metric_results.append(summary)
+ except NotImplementedError:
+ logger.warning(
+ "Aggregation not implemented for metric handler: %s (metric: '%s')."
+ " Skipping summary.",
+ type(handler).__name__,
+ metric_name,
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Error during aggregation for metric '%s' using handler %s: %s",
+ metric_name,
+ type(handler).__name__,
+ e,
+ exc_info=True,
+ )
+ aggregated_metric_results.append(
+ types.AggregatedMetricResult(
+ metric_name=metric_name,
+ num_cases_total=len(results_for_this_metric),
+ num_cases_valid=0,
+ num_cases_error=len(results_for_this_metric),
+ mean_score=None,
+ stdev_score=None,
+ )
+ )
+ logger.debug("Finished aggregation, returning: %s", aggregated_metric_results)
+ return aggregated_metric_results
+
+
+class EvaluationRunConfig(_common.BaseModel):
+ """Configuration for an evaluation run."""
+
+ evals_module: Any
+ """The module to be used for the evaluation run."""
+ dataset: types.EvaluationDataset
+ """The dataset to be used for the evaluation run."""
+ metrics: list[types.Metric]
+ """The list of metrics to be used for the evaluation run."""
+ num_response_candidates: int
+ """The number of response candidates for the evaluation run."""
+
+
+def _rate_limited_get_metric_result(
+ rate_limiter: _evals_utils.RateLimiter,
+ handler: MetricHandler[Any],
+ eval_case: types.EvalCase,
+ response_index: int,
+) -> types.EvalCaseMetricResult:
+ """Wraps a handler's get_metric_result with rate limiting."""
+ rate_limiter.sleep_and_advance()
+ return handler.get_metric_result(eval_case, response_index)
+
+
+def compute_metrics_and_aggregate(
+ evaluation_run_config: EvaluationRunConfig,
+ evaluation_service_qps: Optional[float] = None,
+) -> types.EvaluationResult:
+ """Computes metrics and aggregates them for a given evaluation run config.
+
+ Args:
+ evaluation_run_config: The configuration for the evaluation run.
+ evaluation_service_qps: Optional QPS limit for the evaluation service.
+ Defaults to _DEFAULT_EVAL_SERVICE_QPS (10). Users with higher
+ quotas can increase this value.
+ """
+ metric_handlers = []
+ all_futures = []
+ results_by_case_response_metric: collections.defaultdict[
+ Any, collections.defaultdict[Any, dict[Any, Any]]
+ ] = collections.defaultdict(lambda: collections.defaultdict(dict))
+ submission_errors = []
+ execution_errors = []
+ case_indices_with_errors = set()
+
+ if evaluation_service_qps is not None and evaluation_service_qps <= 0:
+ raise ValueError("evaluation_service_qps must be a positive number.")
+ qps = evaluation_service_qps or _evals_utils._DEFAULT_EVAL_SERVICE_QPS
+ rate_limiter = _evals_utils.RateLimiter(rate=qps)
+ logger.info("Rate limiting evaluation service requests to %.1f QPS.", qps)
+
+ for eval_metric in evaluation_run_config.metrics:
+ metric_handlers.append(
+ get_handler_for_metric(evaluation_run_config.evals_module, eval_metric)
+ )
+
+ eval_case_count = len(evaluation_run_config.dataset.eval_cases)
+ logger.info("Total number of evaluation cases: %d", eval_case_count)
+ logger.info(
+ "Number of response candidates: %d",
+ evaluation_run_config.num_response_candidates,
+ )
+ total_metric_computations = (
+ eval_case_count
+ * len(metric_handlers)
+ * evaluation_run_config.num_response_candidates
+ )
+ logger.info("Total number of metric computations: %d", total_metric_computations)
+
+ with tqdm(
+ total=total_metric_computations,
+ desc="Computing Metrics for Evaluation Dataset",
+ ) as pbar:
+ with futures.ThreadPoolExecutor(
+ max_workers=_evals_common.MAX_WORKERS
+ ) as executor:
+ for metric_handler_instance in metric_handlers:
+ for eval_case_index, eval_case in enumerate(
+ evaluation_run_config.dataset.eval_cases
+ ):
+ num_responses = (
+ len(eval_case.responses) if eval_case.responses else 0
+ )
+ if num_responses == 0 and getattr(eval_case, "agent_data", None):
+ num_responses = 1
+
+ actual_num_candidates_for_case = min(
+ evaluation_run_config.num_response_candidates,
+ num_responses,
+ )
+ for response_index in range(actual_num_candidates_for_case):
+ try:
+ future = executor.submit(
+ _rate_limited_get_metric_result,
+ rate_limiter,
+ metric_handler_instance,
+ eval_case,
+ response_index,
+ )
+ future.add_done_callback(lambda _: pbar.update(1))
+ logger.debug(
+ "Submitting metric computation for case %d, "
+ "response %d for metric %s.",
+ eval_case_index,
+ response_index,
+ metric_handler_instance.metric_name,
+ )
+ all_futures.append(
+ (
+ future,
+ metric_handler_instance.metric_name,
+ eval_case_index,
+ response_index,
+ )
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Error submitting metric computation for case %d, "
+ "response %d for metric %s: %s",
+ eval_case_index,
+ response_index,
+ metric_handler_instance.metric_name,
+ e,
+ exc_info=True,
+ )
+ submission_errors.append(
+ (
+ metric_handler_instance.metric_name,
+ eval_case_index,
+ response_index,
+ f"Error: {e}",
+ )
+ )
+ error_result = types.EvalCaseMetricResult(
+ metric_name=metric_handler_instance.metric_name,
+ error_message=f"Submission Error: {e}",
+ )
+ results_by_case_response_metric[eval_case_index][
+ response_index
+ ][metric_handler_instance.metric_name] = error_result
+ case_indices_with_errors.add(eval_case_index)
+ pbar.update(1)
+
+ for future, metric_name, eval_case_index, response_index in all_futures:
+ try:
+ eval_case_metric_result = future.result()
+ logger.debug(
+ "Successfully obtained result for metric '%s', case %d, response"
+ " %d: %s.",
+ metric_name,
+ eval_case_index,
+ response_index,
+ eval_case_metric_result,
+ )
+ results_by_case_response_metric[eval_case_index][response_index][
+ metric_name
+ ] = eval_case_metric_result
+ logger.debug(
+ "Stored result for metric '%s', case %d, response %d.",
+ metric_name,
+ eval_case_index,
+ response_index,
+ )
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error(
+ "Error executing metric '%s' for case %s, response %s: %s",
+ metric_name,
+ eval_case_index,
+ response_index,
+ e,
+ exc_info=True,
+ )
+ error_msg = (
+ f"Error executing metric '{metric_name}' for case"
+ f" {eval_case_index}, response {response_index}: {e}"
+ )
+ execution_errors.append(
+ (
+ metric_name,
+ eval_case_index,
+ response_index,
+ error_msg,
+ )
+ )
+ case_indices_with_errors.add(eval_case_index)
+ error_result = types.EvalCaseMetricResult(
+ metric_name=metric_name,
+ error_message=error_msg,
+ )
+ results_by_case_response_metric[eval_case_index][response_index][
+ metric_name
+ ] = error_result
+
+ final_eval_case_results = []
+ sorted_eval_case_indices = sorted(results_by_case_response_metric.keys())
+ for eval_case_index in sorted_eval_case_indices:
+ per_response_results_for_this_case = results_by_case_response_metric[
+ eval_case_index
+ ]
+
+ current_response_candidate_results_list = []
+ sorted_response_indices = sorted(per_response_results_for_this_case.keys())
+
+ for response_index in sorted_response_indices:
+ metric_results_for_this_response = per_response_results_for_this_case[
+ response_index
+ ]
+
+ response_candidate_result_obj = types.ResponseCandidateResult(
+ response_index=response_index,
+ metric_results=metric_results_for_this_response,
+ )
+ current_response_candidate_results_list.append(
+ response_candidate_result_obj
+ )
+
+ if current_response_candidate_results_list:
+ eval_case_result = types.EvalCaseResult(
+ eval_case_index=eval_case_index,
+ response_candidate_results=current_response_candidate_results_list,
+ )
+ final_eval_case_results.append(eval_case_result)
+ elif eval_case_index in case_indices_with_errors or any(
+ err_case_idx == eval_case_index
+ for _, err_case_idx, _, _ in submission_errors
+ ):
+ logger.warning(
+ "EvalCase %d had errors but no metric results were"
+ " processed into the structure.",
+ eval_case_index,
+ )
+ eval_case_result = types.EvalCaseResult(
+ eval_case_index=eval_case_index,
+ response_candidate_results=[],
+ )
+ final_eval_case_results.append(eval_case_result)
+
+ if submission_errors:
+ logger.warning("Encountered %d submission errors.", len(submission_errors))
+ logger.warning("Submission errors: %s", submission_errors)
+ if execution_errors:
+ logger.warning("Encountered %d execution errors.", len(execution_errors))
+ logger.warning("Execution errors: %s", execution_errors)
+
+ aggregated_metric_results = _aggregate_metric_results(
+ metric_handlers, final_eval_case_results
+ )
+ eval_result = types.EvaluationResult(
+ eval_case_results=final_eval_case_results,
+ summary_metrics=aggregated_metric_results,
+ )
+ if evaluation_run_config.num_response_candidates > 1:
+ try:
+ eval_result.win_rates = calculate_win_rates(eval_result)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ logger.error("Error calculating win rates: %s", e, exc_info=True)
+ return eval_result
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_loaders.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_loaders.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9f62cb92ae58388772c84ed95279a46ba756cbf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_loaders.py
@@ -0,0 +1,381 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Utility functions for evals."""
+
+import json
+import logging
+import os
+import re
+from typing import Any, Optional, Union, TYPE_CHECKING
+
+import yaml
+
+from . import _evals_constant
+from . import _gcs_utils
+
+if TYPE_CHECKING:
+ from . import types
+
+
+logger = logging.getLogger(__name__)
+
+
+class LazyLoadedPrebuiltMetric:
+ """A proxy object representing a prebuilt metric to be loaded on demand.
+
+ This can resolve to either an API Predefined Metric or an LLM Metric
+ loaded from GCS.
+ """
+
+ _cache: dict[str, "types.Metric"] = {}
+ _base_gcs_path = (
+ "gs://vertex-ai-generative-ai-eval-sdk-resources/metrics/{metric_name}/"
+ )
+
+ def __init__(self, name: str, version: Optional[str] = None, **kwargs: Any):
+ self.name = name.upper()
+ self.version = version
+ self.metric_kwargs = kwargs
+ self._resolved_metric: Optional["types.Metric"] = None
+
+ def _get_api_metric_spec_name(self) -> Optional[str]:
+ """Constructs the metric_spec_name for API Predefined Metrics."""
+ base_name = self.name.lower()
+ if self.version:
+ # Explicit version provided
+ version = self.version.lower()
+ potential_name = f"{base_name}_{version}"
+ return (
+ potential_name
+ if potential_name in _evals_constant.SUPPORTED_PREDEFINED_METRICS
+ else None
+ )
+ else:
+ # Default versioning: Try _v1, then base name
+ v1_name = f"{base_name}_v1"
+ if v1_name in _evals_constant.SUPPORTED_PREDEFINED_METRICS:
+ return v1_name
+ if base_name in _evals_constant.SUPPORTED_PREDEFINED_METRICS:
+ return base_name
+ return None
+
+ def _resolve_api_predefined(self) -> Optional["types.Metric"]:
+ """Attempts to resolve as an API Predefined Metric."""
+ from . import types
+
+ metric_spec_name = self._get_api_metric_spec_name()
+ if metric_spec_name:
+ logger.info(
+ "Resolving '%s' as API Predefined Metric with spec name: %s",
+ self.name,
+ metric_spec_name,
+ )
+ return types.Metric(name=metric_spec_name, **self.metric_kwargs)
+ return None
+
+ def _get_latest_version_uri(self, api_client: Any, metric_gcs_dir: str) -> str:
+ """Lists files in GCS directory and determines the latest version URI."""
+ gcs_utils = _gcs_utils.GcsUtils(api_client)
+ bucket_name, prefix = gcs_utils.parse_gcs_path(metric_gcs_dir)
+
+ blobs = gcs_utils.storage_client.list_blobs(bucket_name, prefix=prefix)
+
+ version_files: list[dict[str, Union[list[int], str]]] = (
+ []
+ ) # {'version_parts': [1,0,0], 'filename': 'v1.0.0.yaml'}
+
+ version_pattern = re.compile(
+ r"v(\d+)(?:\.(\d+))?(?:\.(\d+))?\.(yaml|yml|json)$", re.IGNORECASE
+ )
+
+ for blob in blobs:
+ match = version_pattern.match(os.path.basename(blob.name))
+ if match:
+ major = int(match.group(1))
+ minor = int(match.group(2)) if match.group(2) else 0
+ patch = int(match.group(3)) if match.group(3) else 0
+ version_files.append(
+ {
+ "version_parts": [major, minor, patch],
+ "filename": os.path.basename(blob.name),
+ }
+ )
+
+ if not version_files:
+ raise IOError(f"No versioned metric files found in {metric_gcs_dir}")
+
+ version_files.sort(key=lambda x: x["version_parts"], reverse=True)
+
+ latest_filename = version_files[0]["filename"]
+ return os.path.join(metric_gcs_dir, latest_filename)
+
+ def _fetch_and_parse(self, api_client: Any) -> "types.LLMMetric":
+ """Fetches and parses the metric definition from GCS."""
+
+ from . import types
+
+ metric_gcs_dir = self._base_gcs_path.format(metric_name=self.name.lower())
+ uri: str
+ if self.version == "latest" or self.version is None:
+ uri = self._get_latest_version_uri(api_client, metric_gcs_dir)
+ resolved_version_match = re.match(
+ r"(v\d+(?:\.\d+)*)\.(?:yaml|yml|json)",
+ os.path.basename(uri),
+ re.IGNORECASE,
+ )
+ if resolved_version_match:
+ self.version = resolved_version_match.group(1)
+ else:
+ # Fallback if regex fails
+ self.version = os.path.splitext(os.path.basename(uri))[0]
+ else:
+ yaml_uri = os.path.join(metric_gcs_dir, f"{self.version}.yaml")
+ json_uri = os.path.join(metric_gcs_dir, f"{self.version}.json")
+
+ gcs_utils = _gcs_utils.GcsUtils(api_client)
+ try:
+ bucket_name, blob_path = gcs_utils.parse_gcs_path(yaml_uri)
+ if (
+ gcs_utils.storage_client.bucket(bucket_name)
+ .blob(blob_path)
+ .exists()
+ ):
+ uri = yaml_uri
+ else:
+ bucket_name_json, blob_path_json = gcs_utils.parse_gcs_path(
+ json_uri
+ )
+ if (
+ gcs_utils.storage_client.bucket(bucket_name_json)
+ .blob(blob_path_json)
+ .exists()
+ ):
+ uri = json_uri
+ else:
+ raise IOError(
+ f"Metric file for version '{self.version}' "
+ f"not found as .yaml or .json in {metric_gcs_dir}"
+ )
+ except Exception as e:
+ raise IOError(
+ f"Error checking for metric file version '{self.version}' in"
+ f" {metric_gcs_dir}: {e}"
+ ) from e
+
+ logger.info(
+ "Fetching predefined metric '%s@%s' from %s...",
+ self.name,
+ self.version,
+ uri,
+ )
+
+ gcs_utils = _gcs_utils.GcsUtils(api_client)
+ content_str = gcs_utils.read_file_contents(uri)
+
+ file_extension = os.path.splitext(uri)[1].lower()
+ data: dict[str, Any]
+ if file_extension == ".yaml" or file_extension == ".yml":
+ if yaml is None:
+ raise ImportError(
+ "YAML parsing requires the pyyaml library. Please install it"
+ " with `pip install google-cloud-aiplatform[evaluation]`."
+ )
+ data = yaml.safe_load(content_str)
+ elif file_extension == ".json":
+ data = json.loads(content_str)
+ else:
+ raise ValueError(f"Unsupported file extension: {file_extension}")
+
+ if not isinstance(data, dict):
+ raise ValueError("Metric config content did not parse into a dictionary.")
+
+ metric_obj = types.LLMMetric.model_validate({**data, **self.metric_kwargs})
+ metric_obj._is_predefined = True
+ metric_obj._config_source = uri
+ metric_obj._version = self.version
+ return metric_obj
+
+ def resolve(self, api_client: Any) -> "types.Metric":
+ """Resolves the metric by checking API Predefined, then GCS, caching results."""
+ if self._resolved_metric:
+ return self._resolved_metric
+
+ cache_key = f"{self.name}@{self.version or 'default'}"
+ if cache_key in LazyLoadedPrebuiltMetric._cache:
+ self._resolved_metric = LazyLoadedPrebuiltMetric._cache[cache_key]
+ logger.debug("Metric '%s' found in cache.", cache_key)
+ return self._resolved_metric
+
+ # Try resolving as API Predefined Metric first
+ api_metric = self._resolve_api_predefined()
+ if api_metric:
+ self._resolved_metric = api_metric
+ LazyLoadedPrebuiltMetric._cache[cache_key] = self._resolved_metric
+ return self._resolved_metric
+
+ # Fallback to GCS loading for custom LLM-based Prebuilt Metrics
+ logger.debug(
+ "Metric '%s' not an API Predefined Metric, trying GCS...", self.name
+ )
+ try:
+ gcs_metric = self._fetch_and_parse(api_client)
+ final_cache_key = f"{self.name}@{self.version}"
+ LazyLoadedPrebuiltMetric._cache[final_cache_key] = gcs_metric
+ self._resolved_metric = gcs_metric
+ return self._resolved_metric
+ except Exception as e:
+ logger.error(
+ "Error loading metric %s (requested version: %s) from GCS: %s",
+ self.name,
+ self.version,
+ e,
+ )
+ raise ValueError(
+ f"Metric '{self.name}' could not be resolved as an API "
+ "Predefined Metric or loaded from GCS."
+ ) from e
+
+ def __call__(
+ self, version: Optional[str] = None, **kwargs: Any
+ ) -> "LazyLoadedPrebuiltMetric":
+ """Allows setting a specific version and other metric attributes."""
+ updated_kwargs = self.metric_kwargs.copy()
+ updated_kwargs.update(kwargs)
+ return LazyLoadedPrebuiltMetric(
+ name=self.name, version=version or self.version, **updated_kwargs
+ )
+
+
+class PrebuiltMetricLoader:
+ """Provides access to predefined evaluation metrics via attributes.
+
+ This class provides a set of predefined LLM-based metrics (Autorater recipes)
+ for evaluation. These metrics are lazily loaded from a GCS repository
+ when they are first accessed.
+
+ Example:
+ from agentplatform import types
+ text_quality_metric = types.RubricMetric.TEXT_QUALITY
+ """
+
+ def __getattr__(
+ self, name: str, version: Optional[str] = None, **kwargs: Any
+ ) -> LazyLoadedPrebuiltMetric:
+ return LazyLoadedPrebuiltMetric(name=name, version=version, **kwargs)
+
+ @property
+ def GENERAL_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("GENERAL_QUALITY")
+
+ @property
+ def TEXT_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("TEXT_QUALITY")
+
+ @property
+ def INSTRUCTION_FOLLOWING(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("INSTRUCTION_FOLLOWING")
+
+ @property
+ def SAFETY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("SAFETY")
+
+ @property
+ def MULTI_TURN_GENERAL_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("MULTI_TURN_GENERAL_QUALITY")
+
+ @property
+ def MULTI_TURN_TEXT_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("MULTI_TURN_TEXT_QUALITY")
+
+ @property
+ def MULTI_TURN_TOOL_USE_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("MULTI_TURN_TOOL_USE_QUALITY", version="v1")
+
+ @property
+ def MULTI_TURN_TRAJECTORY_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("MULTI_TURN_TRAJECTORY_QUALITY", version="v1")
+
+ @property
+ def MULTI_TURN_TASK_SUCCESS(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("MULTI_TURN_TASK_SUCCESS", version="v1")
+
+ @property
+ def FINAL_RESPONSE_MATCH(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("FINAL_RESPONSE_MATCH", version="v2")
+
+ @property
+ def FINAL_RESPONSE_REFERENCE_FREE(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("FINAL_RESPONSE_REFERENCE_FREE")
+
+ @property
+ def COHERENCE(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("COHERENCE")
+
+ @property
+ def FLUENCY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("FLUENCY")
+
+ @property
+ def VERBOSITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("VERBOSITY")
+
+ @property
+ def SUMMARIZATION_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("SUMMARIZATION_QUALITY")
+
+ @property
+ def QUESTION_ANSWERING_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("QUESTION_ANSWERING_QUALITY")
+
+ @property
+ def MULTI_TURN_CHAT_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("MULTI_TURN_CHAT_QUALITY")
+
+ @property
+ def MULTI_TURN_SAFETY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("MULTI_TURN_SAFETY")
+
+ @property
+ def FINAL_RESPONSE_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("FINAL_RESPONSE_QUALITY")
+
+ @property
+ def HALLUCINATION(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("HALLUCINATION")
+
+ @property
+ def TOOL_USE_QUALITY(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("TOOL_USE_QUALITY")
+
+ @property
+ def GECKO_TEXT2IMAGE(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("GECKO_TEXT2IMAGE")
+
+ @property
+ def GECKO_TEXT2VIDEO(self) -> LazyLoadedPrebuiltMetric:
+ return self.__getattr__("GECKO_TEXT2VIDEO")
+
+
+PrebuiltMetric = PrebuiltMetricLoader()
+RubricMetric = PrebuiltMetric
+
+
+def CodeExecutionMetric(
+ name: str, custom_function: str, **kwargs: Any
+) -> "types.Metric":
+ """Instantiates a code execution metric."""
+ from . import types
+
+ return types.Metric(name=name, remote_custom_function=custom_function, **kwargs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..97bc2d478d610426de93d452a9267e41858383a7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_utils.py
@@ -0,0 +1,1043 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Utility functions for evals."""
+
+import abc
+import asyncio
+import json
+import logging
+import os
+import threading
+import time
+from typing import Any, Optional, Union
+
+from google.genai._api_client import BaseApiClient
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+import pandas as pd
+
+from . import _bigquery_utils
+from . import _gcs_utils
+from . import _transformers
+from . import types
+
+
+logger = logging.getLogger(__name__)
+
+
+GCS_PREFIX = "gs://"
+BQ_PREFIX = "bq://"
+_DEFAULT_EVAL_SERVICE_QPS = 10
+
+
+class RateLimiter:
+ """Helper class for rate-limiting requests to Vertex AI to improve QoS.
+
+ Implements a token bucket algorithm to limit the rate at which API calls
+ can occur. Designed for cases where the batch size is always 1 for traffic
+ shaping and rate limiting.
+
+ Attributes:
+ seconds_per_event: The time interval (in seconds) between events to
+ maintain the desired rate.
+ last: The timestamp of the last event.
+ _lock: A lock to ensure thread safety.
+ """
+
+ def __init__(self, rate: float) -> None:
+ """Initializes the rate limiter.
+
+ Args:
+ rate: The number of queries allowed per second.
+
+ Raises:
+ ValueError: If the rate is not positive.
+ """
+ if not rate or rate <= 0:
+ raise ValueError("Rate must be a positive number")
+ self.seconds_per_event = 1.0 / rate
+ self._next_allowed = time.monotonic()
+ self._lock = threading.Lock()
+
+ def sleep_and_advance(self) -> None:
+ """Blocks the current thread until the next event can be admitted.
+
+ The lock is held only long enough to reserve a time slot. The
+ actual sleep happens outside the lock so that multiple threads
+ can be sleeping concurrently with staggered wake-up times.
+ """
+ with self._lock:
+ now = time.monotonic()
+ wait_until = max(now, self._next_allowed)
+ delay = wait_until - now
+ self._next_allowed = wait_until + self.seconds_per_event
+
+ if delay > 0:
+ time.sleep(delay)
+
+
+class EvalDatasetLoader:
+ """A loader for datasets from various sources, using a shared client."""
+
+ def __init__(self, api_client: BaseApiClient) -> None:
+ self.api_client = api_client
+ self.gcs_utils = _gcs_utils.GcsUtils(self.api_client)
+ self.bigquery_utils = _bigquery_utils.BigQueryUtils(self.api_client)
+
+ def _load_file(
+ self, filepath: str, file_type: str
+ ) -> Union[list[dict[str, Any]], Any]:
+ """Loads data from a file into a list of dictionaries."""
+ if filepath.startswith(GCS_PREFIX):
+ df = self.gcs_utils.read_gcs_file_to_dataframe(filepath, file_type)
+ return df.to_dict(orient="records")
+ else:
+ if file_type == "jsonl":
+ df = pd.read_json(filepath, lines=True)
+ return df.to_dict(orient="records")
+ elif file_type == "csv":
+ df = pd.read_csv(filepath, encoding="utf-8")
+ return df.to_dict(orient="records")
+ else:
+ raise ValueError(
+ f"Unsupported file type: '{file_type}'. Please provide 'jsonl' or"
+ " 'csv'."
+ )
+
+ def load(
+ self, source: Union[str, "pd.DataFrame"]
+ ) -> Union[list[dict[str, Any]], Any]:
+ """Loads dataset from various sources into a list of dictionaries."""
+ if isinstance(source, pd.DataFrame):
+ return source.to_dict(orient="records")
+ elif isinstance(source, str):
+ if source.startswith(BQ_PREFIX):
+ df = self.bigquery_utils.load_bigquery_to_dataframe(
+ source[len(BQ_PREFIX) :]
+ )
+ return df.to_dict(orient="records")
+
+ _, extension = os.path.splitext(source)
+ file_type = extension.lower()[1:]
+
+ if file_type == "jsonl":
+ return self._load_file(source, "jsonl")
+ elif file_type == "csv":
+ return self._load_file(source, "csv")
+ else:
+ raise TypeError(
+ f"Unsupported file type: {file_type} from {source}. Please"
+ " provide a valid GCS path with `jsonl` or `csv` suffix, "
+ "a local file path, or a valid BigQuery table URI."
+ )
+ else:
+ raise TypeError(
+ "Unsupported dataset type. Must be a `pd.DataFrame`, Python"
+ " a valid GCS path with `jsonl` or `csv` suffix, a local"
+ " file path, or a valid BigQuery table URI."
+ )
+
+
+class BatchEvaluateRequestPreparer:
+ """Prepares data for requests."""
+
+ @staticmethod
+ def _EvaluationDataset_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+ ) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["gcs_source"]) is not None:
+ setv(
+ to_object,
+ ["gcs_source"],
+ getv(from_object, ["gcs_source"]),
+ )
+
+ if getv(from_object, ["bigquery_source"]) is not None:
+ setv(
+ to_object,
+ ["bigquery_source"],
+ getv(from_object, ["bigquery_source"]),
+ )
+
+ return to_object
+
+ @staticmethod
+ def _Metric_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+ ) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["prompt_template"]) is not None:
+ setv(
+ to_object,
+ ["pointwise_metric_spec", "prompt_template"],
+ getv(from_object, ["prompt_template"]),
+ )
+
+ if getv(from_object, ["judge_model"]) is not None:
+ setv(
+ parent_object,
+ ["autorater_config", "autorater_model"],
+ getv(from_object, ["judge_model"]),
+ )
+
+ if getv(from_object, ["judge_model_sampling_count"]) is not None:
+ setv(
+ parent_object,
+ ["autorater_config", "sampling_count"],
+ getv(from_object, ["judge_model_sampling_count"]),
+ )
+
+ if getv(from_object, ["judge_model_system_instruction"]) is not None:
+ setv(
+ to_object,
+ ["pointwise_metric_spec", "system_instruction"],
+ getv(from_object, ["judge_model_system_instruction"]),
+ )
+
+ if getv(from_object, ["return_raw_output"]) is not None:
+ setv(
+ to_object,
+ [
+ "pointwise_metric_spec",
+ "custom_output_format_config",
+ "return_raw_output",
+ ],
+ getv(from_object, ["return_raw_output"]),
+ )
+
+ return to_object
+
+ @staticmethod
+ def _OutputConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+ ) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["gcs_destination"]) is not None:
+ setv(
+ to_object,
+ ["gcsDestination"],
+ getv(from_object, ["gcs_destination"]),
+ )
+
+ return to_object
+
+ @staticmethod
+ def _EvaluationDataset_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+ ) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["dataset", "gcs_source"]) is not None:
+ setv(
+ to_object,
+ ["gcs_source"],
+ getv(from_object, ["dataset", "gcs_source"]),
+ )
+
+ if getv(from_object, ["dataset", "bigquery_source"]) is not None:
+ setv(
+ to_object,
+ ["bigquery_source"],
+ getv(from_object, ["dataset", "bigquery_source"]),
+ )
+
+ return to_object
+
+ @staticmethod
+ def _AutoraterConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+ ) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["sampling_count"]) is not None:
+ setv(to_object, ["samplingCount"], getv(from_object, ["sampling_count"]))
+
+ if getv(from_object, ["flip_enabled"]) is not None:
+ setv(to_object, ["flipEnabled"], getv(from_object, ["flip_enabled"]))
+
+ if getv(from_object, ["autorater_model"]) is not None:
+ setv(
+ to_object,
+ ["autoraterModel"],
+ getv(from_object, ["autorater_model"]),
+ )
+
+ return to_object
+
+ @staticmethod
+ def EvaluateDatasetOperation_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+ ) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["done"]) is not None:
+ setv(to_object, ["done"], getv(from_object, ["done"]))
+
+ if getv(from_object, ["error"]) is not None:
+ setv(to_object, ["error"], getv(from_object, ["error"]))
+
+ if getv(from_object, ["response"]) is not None:
+ setv(
+ to_object,
+ ["response"],
+ BatchEvaluateRequestPreparer._EvaluationDataset_from_vertex(
+ getv(from_object, ["response"]), to_object
+ ),
+ )
+
+ return to_object
+
+ @staticmethod
+ def EvaluateDatasetRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+ ) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["dataset"]) is not None:
+ setv(
+ to_object,
+ ["dataset"],
+ BatchEvaluateRequestPreparer._EvaluationDataset_to_vertex(
+ getv(from_object, ["dataset"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["metrics"]) is not None:
+ setv(
+ to_object,
+ ["metrics"],
+ [
+ BatchEvaluateRequestPreparer._Metric_to_vertex(item, to_object)
+ for item in getv(from_object, ["metrics"])
+ ],
+ )
+
+ if getv(from_object, ["output_config"]) is not None:
+ setv(
+ to_object,
+ ["outputConfig"],
+ BatchEvaluateRequestPreparer._OutputConfig_to_vertex(
+ getv(from_object, ["output_config"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["autorater_config"]) is not None:
+ setv(
+ to_object,
+ ["autoraterConfig"],
+ BatchEvaluateRequestPreparer._AutoraterConfig_to_vertex(
+ getv(from_object, ["autorater_config"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+ @staticmethod
+ def prepare_metric_payload(
+ request_dict: dict[str, Any], resolved_metrics: list["types.MetricSubclass"]
+ ) -> dict[str, Any]:
+ """Prepares the metric payload for the evaluation request.
+
+ Args:
+ request_dict: The dictionary containing the request details.
+ resolved_metrics: A list of resolved metric objects.
+
+ Returns:
+ The updated request dictionary with the prepared metric payload.
+ """
+ request_dict["metrics"] = _transformers.t_metrics(
+ resolved_metrics, set_default_aggregation_metrics=True
+ )
+ return request_dict
+
+
+class EvalDataConverter(abc.ABC):
+ """Abstract base class for dataset converters."""
+
+ @abc.abstractmethod
+ def convert(self, raw_data: Any) -> "types.EvaluationDataset":
+ """Converts a loaded raw dataset into an EvaluationDataset."""
+ raise NotImplementedError()
+
+
+def _postprocess_user_scenarios_response(
+ response: types.GenerateUserScenariosResponse,
+) -> types.EvaluationDataset:
+ """Postprocesses the response from generating user scenarios."""
+ eval_cases = []
+ data_for_df = []
+ if hasattr(response, "user_scenarios") and response.user_scenarios:
+ for scenario in response.user_scenarios:
+ eval_case = types.EvalCase(
+ user_scenario=scenario,
+ )
+ eval_cases.append(eval_case)
+ data_for_df.append(
+ {
+ "starting_prompt": scenario.starting_prompt,
+ "conversation_plan": scenario.conversation_plan,
+ }
+ )
+ eval_dataset_df = None
+ if pd is not None:
+ eval_dataset_df = pd.DataFrame(data_for_df)
+ else:
+ logger.warning("Pandas is not installed. eval_dataset_df will be None.")
+ return types.EvaluationDataset(
+ eval_cases=eval_cases, eval_dataset_df=eval_dataset_df
+ )
+
+
+def _display_loss_analysis_result(
+ result: types.LossAnalysisResult,
+) -> None:
+ """Displays a LossAnalysisResult as a formatted pandas DataFrame."""
+ metric = result.config.metric if result.config else None
+ candidate = result.config.candidate if result.config else None
+ rows: list[dict[str, Any]] = []
+ for cluster in result.clusters or []:
+ entry = cluster.taxonomy_entry
+ row = {
+ "metric": metric,
+ "candidate": candidate,
+ "cluster_id": cluster.cluster_id,
+ "l1_category": entry.l1_category if entry else None,
+ "l2_category": entry.l2_category if entry else None,
+ "description": entry.description if entry else None,
+ "item_count": cluster.item_count,
+ }
+ rows.append(row)
+
+ if not rows:
+ logger.info("No loss clusters found.")
+ return
+
+ df = pd.DataFrame(rows)
+ try:
+ from IPython.display import display # pylint: disable=g-import-not-at-top
+
+ display(df)
+ except ImportError:
+ print(df.to_string()) # pylint: disable=print-function
+
+
+def _resolve_metric_name(
+ metric: Optional[Any],
+) -> Optional[str]:
+ """Extracts a metric name string from a metric argument.
+
+ Accepts a string, a Metric object, or a LazyLoadedPrebuiltMetric
+ (RubricMetric) and returns the metric name as a string.
+
+ For LazyLoadedPrebuiltMetric (e.g., RubricMetric.MULTI_TURN_TASK_SUCCESS),
+ this resolves to the API metric spec name (e.g.,
+ "multi_turn_task_success_v1") so it matches the keys in eval results.
+
+ Args:
+ metric: A metric name string, Metric object, RubricMetric enum value, or
+ None.
+
+ Returns:
+ The metric name as a string, or None if metric is None.
+ """
+ if metric is None:
+ return None
+ if isinstance(metric, str):
+ return metric
+ # LazyLoadedPrebuiltMetric: resolve to versioned API spec name.
+ if hasattr(metric, "_get_api_metric_spec_name"):
+ spec_name: Optional[str] = metric._get_api_metric_spec_name()
+ if spec_name:
+ return spec_name
+ # Metric objects and other types with a .name attribute.
+ if hasattr(metric, "name"):
+ return str(metric.name)
+ return str(metric)
+
+
+def _resolve_eval_run_loss_configs(
+ loss_analysis_metrics: Optional[list[Any]] = None,
+ loss_analysis_configs: Optional[list[Any]] = None,
+ inference_configs: Optional[dict[str, Any]] = None,
+) -> Optional[list[types.LossAnalysisConfig]]:
+ """Resolves loss analysis configs for create_evaluation_run.
+
+ Supports two modes:
+ 1. ``loss_analysis_metrics``: A simplified list of metrics. The candidate
+ is auto-inferred from ``inference_configs`` when there is exactly one
+ candidate. Each metric is resolved via ``_resolve_metric_name()``.
+ 2. ``loss_analysis_configs``: Explicit ``LossAnalysisConfig`` objects or
+ dicts for full control.
+
+ Args:
+ loss_analysis_metrics: Optional list of metric references (strings,
+ Metric objects, or RubricMetric enums).
+ loss_analysis_configs: Optional list of LossAnalysisConfig or dicts.
+ inference_configs: The resolved inference_configs dict (candidate name
+ -> config). Used to auto-infer candidate for the metrics path.
+
+ Returns:
+ A list of resolved LossAnalysisConfig objects, or None if neither
+ loss_analysis_metrics nor loss_analysis_configs is provided.
+
+ Raises:
+ ValueError: If candidate cannot be inferred for loss_analysis_metrics.
+ """
+ if not loss_analysis_metrics and not loss_analysis_configs:
+ return None
+
+ if loss_analysis_configs:
+ return [
+ types.LossAnalysisConfig.model_validate(c) if isinstance(c, dict) else c
+ for c in loss_analysis_configs
+ ]
+
+ # loss_analysis_metrics path: auto-infer candidate from inference_configs
+ candidate = None
+ if inference_configs and len(inference_configs) == 1:
+ candidate = next(iter(inference_configs))
+ elif inference_configs and len(inference_configs) > 1:
+ raise ValueError(
+ "Cannot infer candidate for loss analysis: multiple candidates"
+ f" found in inference_configs: {list(inference_configs.keys())}."
+ " Please use loss_analysis_configs with explicit candidate values"
+ " instead."
+ )
+
+ configs = []
+ for m in loss_analysis_metrics or []:
+ metric_name = _resolve_metric_name(m)
+ configs.append(
+ types.LossAnalysisConfig(metric=metric_name, candidate=candidate)
+ )
+ return configs
+
+
+def _resolve_red_teaming_config(
+ red_teaming_config: Optional[types.RedTeamingAnalysisConfigOrDict] = None,
+) -> Optional[list[types.AnalysisConfig]]:
+ """Wraps a RedTeamingAnalysisConfig into analysis_configs for the API."""
+ if not red_teaming_config:
+ return None
+ config = (
+ types.RedTeamingAnalysisConfig.model_validate(red_teaming_config)
+ if isinstance(red_teaming_config, dict)
+ else red_teaming_config
+ )
+ return [types.AnalysisConfig(red_teaming_analysis_config=config)]
+
+
+def _resolve_loss_analysis_config(
+ eval_result: types.EvaluationResult,
+ config: Optional[types.LossAnalysisConfig] = None,
+ metric: Optional[str] = None,
+ candidate: Optional[str] = None,
+) -> types.LossAnalysisConfig:
+ """Resolves and validates the LossAnalysisConfig for generate_loss_clusters.
+
+ Auto-infers `metric` and `candidate` from the EvaluationResult when not
+ explicitly provided. Validates that provided values exist in the eval result.
+
+ Args:
+ eval_result: The EvaluationResult from client.evals.evaluate().
+ config: Optional explicit LossAnalysisConfig. If provided, metric and
+ candidate from config take precedence over the separate arguments.
+ metric: Optional metric name override.
+ candidate: Optional candidate name override.
+
+ Returns:
+ A resolved LossAnalysisConfig with metric and candidate populated.
+
+ Raises:
+ ValueError: If metric/candidate cannot be inferred or are invalid.
+ """
+ # Start from config if provided, otherwise create a new one.
+ if config is not None:
+ resolved_metric = metric or config.metric
+ resolved_candidate = candidate or config.candidate
+ resolved_config = config.model_copy(
+ update={"metric": resolved_metric, "candidate": resolved_candidate}
+ )
+ else:
+ resolved_config = types.LossAnalysisConfig(metric=metric, candidate=candidate)
+
+ # Collect available metric names from the eval result.
+ available_metrics: set[str] = set()
+ if eval_result.eval_case_results:
+ for case_result in eval_result.eval_case_results:
+ for resp_cand in case_result.response_candidate_results or []:
+ for m_name in (resp_cand.metric_results or {}).keys():
+ available_metrics.add(m_name)
+
+ # Collect available candidate names from metadata.
+ available_candidates: list[str] = []
+ if eval_result.metadata and eval_result.metadata.candidate_names:
+ available_candidates = list(eval_result.metadata.candidate_names)
+
+ # Auto-infer metric if not provided.
+ if not resolved_config.metric:
+ if len(available_metrics) == 1:
+ resolved_config = resolved_config.model_copy(
+ update={"metric": next(iter(available_metrics))}
+ )
+ elif len(available_metrics) == 0:
+ raise ValueError(
+ "Cannot infer metric: no metric results found in eval_result."
+ " Please provide metric explicitly via"
+ " config=types.LossAnalysisConfig(metric='...')."
+ )
+ else:
+ raise ValueError(
+ "Cannot infer metric: multiple metrics found in eval_result:"
+ f" {sorted(available_metrics)}. Please provide metric"
+ " explicitly via config=types.LossAnalysisConfig(metric='...')."
+ )
+
+ # Validate metric if provided explicitly.
+ if available_metrics and resolved_config.metric not in available_metrics:
+ raise ValueError(
+ f"Metric '{resolved_config.metric}' not found in eval_result."
+ f" Available metrics: {sorted(available_metrics)}."
+ )
+
+ # Auto-infer candidate if not provided.
+ if not resolved_config.candidate:
+ if len(available_candidates) == 1:
+ resolved_config = resolved_config.model_copy(
+ update={"candidate": available_candidates[0]}
+ )
+ elif len(available_candidates) == 0:
+ # Fallback: use default candidate naming convention from SDK.
+ resolved_config = resolved_config.model_copy(
+ update={"candidate": "candidate_1"}
+ )
+ logger.warning(
+ "No candidate names found in eval_result.metadata."
+ " Defaulting to 'candidate_1'. If this is incorrect, provide"
+ " candidate explicitly via"
+ " config=types.LossAnalysisConfig(candidate='...')."
+ )
+ else:
+ raise ValueError(
+ "Cannot infer candidate: multiple candidates found in"
+ f" eval_result: {available_candidates}. Please provide"
+ " candidate explicitly via"
+ " config=types.LossAnalysisConfig(candidate='...')."
+ )
+
+ # Validate candidate if provided explicitly and candidates are known.
+ if available_candidates and resolved_config.candidate not in available_candidates:
+ raise ValueError(
+ f"Candidate '{resolved_config.candidate}' not found in"
+ f" eval_result. Available candidates: {available_candidates}."
+ )
+
+ return resolved_config
+
+
+def _build_rubric_description_map(
+ eval_result: types.EvaluationResult,
+) -> dict[str, str]:
+ """Builds a rubric_id -> description map from the EvaluationResult."""
+ rubric_map: dict[str, str] = {}
+ for case_result in eval_result.eval_case_results or []:
+ for resp_cand in case_result.response_candidate_results or []:
+ for metric_res in (resp_cand.metric_results or {}).values():
+ for verdict in metric_res.rubric_verdicts or []:
+ rubric = verdict.evaluated_rubric
+ if rubric and rubric.rubric_id and rubric.content:
+ if (
+ rubric.content.property
+ and rubric.content.property.description
+ ):
+ rubric_map[rubric.rubric_id] = (
+ rubric.content.property.description
+ )
+ return rubric_map
+
+
+def _extract_scenario_preview_from_dict(
+ eval_result_dict: dict[str, Any],
+) -> Optional[str]:
+ """Extracts the first user message from an evaluation_result dict.
+
+ Handles both snake_case (SDK-side) and camelCase (API echo-back) keys.
+ """
+ request = eval_result_dict.get("request")
+ if not request:
+ return None
+ prompt = request.get("prompt")
+ if not prompt:
+ return None
+ # Try agent_data (snake_case or camelCase)
+ agent_data = prompt.get("agent_data") or prompt.get("agentData")
+ if agent_data and isinstance(agent_data, dict):
+ turns = agent_data.get("turns", [])
+ for turn in turns:
+ events = turn.get("events", [])
+ for event in events:
+ author = event.get("author", "")
+ content = event.get("content")
+ if author.lower() == "user" and content and isinstance(content, dict):
+ parts = content.get("parts", [])
+ for part in parts:
+ text = str(part.get("text", "")).strip()
+ if text:
+ if len(text) > 150:
+ return text[:150] + "..."
+ return text
+ # Try simple prompt path
+ parts = prompt.get("parts", [])
+ for part in parts:
+ text = str(part.get("text", "")).strip()
+ if text:
+ if len(text) > 150:
+ return text[:150] + "..."
+ return text
+ return None
+
+
+def _extract_scenario_from_agent_data(agent_data: Any) -> Optional[str]:
+ """Extracts the first user message from an AgentData object or dict."""
+ if agent_data is None:
+ return None
+ if hasattr(agent_data, "model_dump"):
+ agent_data = agent_data.model_dump()
+ if isinstance(agent_data, str):
+ try:
+ agent_data = json.loads(agent_data)
+ except (json.JSONDecodeError, ValueError):
+ return None
+ if not isinstance(agent_data, dict):
+ return None
+ turns = agent_data.get("turns", [])
+ if not isinstance(turns, list):
+ return None
+ for turn in turns:
+ if not isinstance(turn, dict):
+ continue
+ events = turn.get("events", [])
+ if not isinstance(events, list):
+ continue
+ for event in events:
+ if not isinstance(event, dict):
+ continue
+ author = event.get("author", "")
+ if not isinstance(author, str) or author.lower() != "user":
+ continue
+ content = event.get("content")
+ if not content or not isinstance(content, dict):
+ continue
+ parts = content.get("parts", [])
+ if not isinstance(parts, list):
+ continue
+ for part in parts:
+ if not isinstance(part, dict):
+ continue
+ text = str(part.get("text", "")).strip()
+ if text:
+ if len(text) > 150:
+ return text[:150] + "..."
+ return text
+ return None
+
+
+def _truncate_scenario(text: str, max_len: int = 150) -> str:
+ """Truncates a scenario preview to max_len characters."""
+ text = text.strip()
+ if len(text) > max_len:
+ return text[:max_len] + "..."
+ return text
+
+
+def _build_scenario_preview_list(
+ eval_result: types.EvaluationResult,
+) -> list[Optional[str]]:
+ """Builds an ordered list of scenario previews from the EvaluationResult.
+
+ Returns one scenario preview per eval_case_result, in the same order as
+ eval_case_results. This extracts the first user message from the original
+ SDK EvaluationResult (via eval_cases or DataFrame), rather than relying
+ on the API echo-back which may not preserve the request data.
+
+ Extraction priority per eval case:
+ 1. eval_case.agent_data → first user message in turns
+ 2. eval_case.user_scenario.starting_prompt
+ 3. eval_case.prompt → text content
+ 4. DataFrame agent_data column → first user message
+ 5. DataFrame starting_prompt column
+ """
+ eval_dataset = eval_result.evaluation_dataset
+ eval_cases: list[Any] = []
+ if isinstance(eval_dataset, list) and eval_dataset:
+ eval_cases = getv(eval_dataset[0], ["eval_cases"]) or []
+
+ eval_case_results = eval_result.eval_case_results or []
+ scenarios: list[Optional[str]] = []
+
+ for case_result in eval_case_results:
+ case_idx = case_result.eval_case_index or 0
+ scenario: Optional[str] = None
+
+ eval_case = None
+ if 0 <= case_idx < len(eval_cases):
+ eval_case = eval_cases[case_idx]
+
+ if eval_case:
+ # 1. Try agent_data (populated after run_inference)
+ agent_data = getv(eval_case, ["agent_data"])
+ if agent_data:
+ scenario = _extract_scenario_from_agent_data(agent_data)
+
+ # 2. Try user_scenario.starting_prompt (from
+ # generate_conversation_scenarios)
+ if scenario is None:
+ user_scenario = getv(eval_case, ["user_scenario"])
+ if user_scenario:
+ starting_prompt = getv(user_scenario, ["starting_prompt"])
+ if starting_prompt and isinstance(starting_prompt, str):
+ scenario = _truncate_scenario(starting_prompt)
+
+ # 3. Try prompt text
+ if scenario is None:
+ prompt = getv(eval_case, ["prompt"])
+ if prompt:
+ from . import _evals_data_converters
+
+ text = _evals_data_converters._get_content_text(prompt)
+ if text:
+ scenario = _truncate_scenario(str(text))
+
+ # 4. Fallback: extract agent_data from DataFrame
+ if scenario is None and eval_dataset:
+ df_agent_data = _transformers._extract_agent_data_from_df(
+ eval_dataset, case_idx
+ )
+ if df_agent_data is not None:
+ scenario = _extract_scenario_from_agent_data(df_agent_data)
+
+ # 5. Fallback: extract starting_prompt from DataFrame
+ if scenario is None and eval_dataset:
+ ds = eval_dataset[0] if isinstance(eval_dataset, list) else eval_dataset
+ df = getv(ds, ["eval_dataset_df"])
+ if df is not None and hasattr(df, "iloc"):
+ if 0 <= case_idx < len(df):
+ row = df.iloc[case_idx]
+ sp = row.get("starting_prompt")
+ if sp and isinstance(sp, str) and sp.strip():
+ scenario = _truncate_scenario(sp)
+
+ scenarios.append(scenario)
+
+ return scenarios
+
+
+def _enrich_loss_response_with_rubric_descriptions(
+ response: types.GenerateLossClustersResponse,
+ eval_result: types.EvaluationResult,
+) -> None:
+ """Enriches loss response with rubric descriptions and scenario previews.
+
+ Rubric descriptions and scenario previews are extracted from the original
+ SDK EvaluationResult object, because the API echo-back in
+ LossExample.evaluation_result may not preserve all request data (e.g.,
+ agent_data turns with user messages).
+ """
+ rubric_map = _build_rubric_description_map(eval_result)
+ scenario_list = _build_scenario_preview_list(eval_result)
+ logger.debug(
+ "Enriching loss response: %d scenarios extracted, %d rubric" " descriptions",
+ sum(1 for s in scenario_list if s),
+ len(rubric_map),
+ )
+ for result in response.results or []:
+ for cluster in result.clusters or []:
+ for example in cluster.examples or []:
+ if example.evaluation_result is None:
+ example.evaluation_result = {}
+ if rubric_map:
+ example.evaluation_result["rubric_descriptions"] = rubric_map
+ # Try extracting scenario from the API echo-back first
+ if "scenario_preview" not in example.evaluation_result:
+ scenario = _extract_scenario_preview_from_dict(
+ example.evaluation_result
+ )
+ if scenario:
+ example.evaluation_result["scenario_preview"] = scenario
+ # Fallback: match against scenarios from original eval_result
+ if "scenario_preview" not in example.evaluation_result:
+ if scenario_list:
+ for s in scenario_list:
+ if s:
+ example.evaluation_result["scenario_preview"] = s
+ break
+
+
+def _poll_operation(
+ api_client: BaseApiClient,
+ operation: types.GenerateLossClustersOperation,
+ poll_interval_seconds: float = 5.0,
+) -> types.GenerateLossClustersOperation:
+ """Polls a long-running operation until completion.
+
+ Args:
+ api_client: The API client to use for polling.
+ operation: The initial operation returned from the API call.
+ poll_interval_seconds: Time between polls.
+
+ Returns:
+ The completed operation.
+ """
+ if operation.done:
+ return operation
+ start_time = time.time()
+ while True:
+ response = api_client.request("get", operation.name, {}, None)
+ response_dict = {} if not response.body else json.loads(response.body)
+ polled = types.GenerateLossClustersOperation._from_response(
+ response=response_dict, kwargs={}
+ )
+ if polled.done:
+ return polled
+ elapsed = int(time.time() - start_time)
+ logger.info(
+ "Loss analysis operation still running... Elapsed time: %d seconds",
+ elapsed,
+ )
+ time.sleep(poll_interval_seconds)
+
+
+async def _poll_operation_async(
+ api_client: BaseApiClient,
+ operation: types.GenerateLossClustersOperation,
+ poll_interval_seconds: float = 5.0,
+) -> types.GenerateLossClustersOperation:
+ """Polls a long-running operation until completion (async).
+
+ Args:
+ api_client: The API client to use for polling.
+ operation: The initial operation returned from the API call.
+ poll_interval_seconds: Time between polls.
+
+ Returns:
+ The completed operation.
+ """
+ if operation.done:
+ return operation
+ start_time = time.time()
+ while True:
+ response = await api_client.async_request("get", operation.name, {}, None)
+ response_dict = {} if not response.body else json.loads(response.body)
+ polled = types.GenerateLossClustersOperation._from_response(
+ response=response_dict, kwargs={}
+ )
+ if polled.done:
+ return polled
+ elapsed = int(time.time() - start_time)
+ logger.info(
+ "Loss analysis operation still running... Elapsed time: %d seconds",
+ elapsed,
+ )
+ await asyncio.sleep(poll_interval_seconds)
+
+
+def _validate_dataset_agent_data(
+ dataset: types.EvaluationDataset,
+ inference_configs: Optional[dict[str, Any]] = None,
+) -> None:
+ """Validates agent_data in the EvaluationDataset.
+
+ Checks that agent_data matches the expected AgentData type and that
+ 'agents' are not defined in both the dataset's agent_data and inference_configs.
+ """
+ has_inference_agent_configs = False
+ if inference_configs:
+ for cand_config in inference_configs.values():
+ if isinstance(cand_config, dict) and cand_config.get("agent_configs"):
+ has_inference_agent_configs = True
+ elif hasattr(cand_config, "agent_configs") and cand_config.agent_configs:
+ has_inference_agent_configs = True
+
+ def _validate_single_agent_data(agent_data_val: Any, identifier: str) -> None:
+
+ if not agent_data_val:
+ return
+
+ agent_data_obj = None
+ if isinstance(agent_data_val, str):
+ try:
+ agent_data_val = json.loads(agent_data_val)
+ if "error" in agent_data_val:
+ return
+ agent_data_obj = types.evals.AgentData.model_validate(agent_data_val)
+ except json.JSONDecodeError as e:
+ raise ValueError(
+ f"{identifier}: 'agent_data' is not valid JSON: {e}"
+ ) from e
+ elif isinstance(agent_data_val, dict) and "error" in agent_data_val:
+ return
+ elif isinstance(agent_data_val, dict):
+ try:
+ agent_data_obj = types.evals.AgentData.model_validate(agent_data_val)
+ except Exception as e:
+ raise ValueError(
+ f"{identifier}: 'agent_data' "
+ f"is inconsistent with AgentData type: {e}"
+ ) from e
+ elif isinstance(agent_data_val, types.evals.AgentData):
+ agent_data_obj = agent_data_val
+ else:
+ raise ValueError(
+ f"{identifier}: 'agent_data' is inconsistent with AgentData type. "
+ f"Got {type(agent_data_val)}"
+ )
+
+ if agent_data_obj and agent_data_obj.agents and has_inference_agent_configs:
+ raise ValueError(
+ f"{identifier}: Cannot provide 'agents' in the dataset's 'agent_data' "
+ "and 'agent_configs' in inference_configs at the same time."
+ )
+
+ if (
+ dataset.eval_dataset_df is not None
+ and "agent_data" in dataset.eval_dataset_df.columns
+ ):
+ for idx, row in dataset.eval_dataset_df.iterrows():
+ _validate_single_agent_data(row.get("agent_data"), f"Row {idx}")
+
+ if dataset.eval_cases:
+ for idx, eval_case in enumerate(dataset.eval_cases):
+ agent_data = None
+ if isinstance(eval_case, dict):
+ agent_data = eval_case.get("agent_data", None)
+ elif hasattr(eval_case, "agent_data"):
+ agent_data = eval_case.agent_data
+ _validate_single_agent_data(agent_data, f"EvalCase {idx}")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_visualization.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_visualization.py
new file mode 100644
index 0000000000000000000000000000000000000000..45b50b6ebc112661404fea8932df91b1be08696c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_visualization.py
@@ -0,0 +1,2026 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Visualization utilities for GenAI Evaluation SDK."""
+
+import base64
+import datetime
+import html
+import json
+import logging
+import textwrap
+from typing import Any, Optional
+
+import pandas as pd
+from pydantic import errors
+
+from . import types
+
+
+logger = logging.getLogger(__name__)
+
+
+def _is_ipython_env() -> bool:
+ """Checks if the code is running in an IPython environment."""
+ try:
+ from IPython import get_ipython
+
+ return get_ipython() is not None
+ except ImportError:
+ return False
+
+
+def _pydantic_serializer(obj: Any) -> Any:
+ """Custom serializer for Pydantic models."""
+ if hasattr(obj, "model_dump"):
+ return obj.model_dump(mode="json")
+ if isinstance(obj, datetime.datetime):
+ return obj.isoformat()
+ if isinstance(obj, bytes):
+ return base64.b64encode(obj).decode("utf-8")
+ raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
+
+
+def _preprocess_df_for_json(df: Optional[pd.DataFrame]) -> Optional[pd.DataFrame]:
+ """Prepares a DataFrame for JSON serialization by converting complex objects to strings."""
+ if df is None:
+ return None
+ df_copy = df.copy()
+
+ for col in df_copy.columns:
+ if (
+ df_copy[col].dtype == "object"
+ or df_copy[col].apply(lambda x: isinstance(x, (dict, list))).any()
+ ):
+
+ def stringify_cell(cell: Any) -> Optional[str]:
+ if isinstance(cell, (dict, list)):
+ try:
+ return json.dumps(
+ cell, ensure_ascii=False, default=_pydantic_serializer
+ )
+ except TypeError:
+ return str(cell)
+ elif pd.isna(cell):
+ return None
+ elif not isinstance(cell, (str, int, float, bool)):
+ if hasattr(cell, "model_dump"):
+ return json.dumps(
+ cell.model_dump(mode="json"), ensure_ascii=False
+ )
+ return str(cell)
+ return str(cell)
+
+ df_copy[col] = df_copy[col].apply(stringify_cell)
+ return df_copy
+
+
+def _encode_to_base64(data: str) -> str:
+ """Encodes a string to a web-safe Base64 string."""
+ return base64.b64encode(data.encode("utf-8")).decode("utf-8")
+
+
+def _extract_text_and_raw_json(content: Any) -> dict[str, str]:
+ """Extracts display text and raw JSON from a content object."""
+ if hasattr(content, "model_dump"):
+ content = content.model_dump(mode="json", exclude_none=True)
+
+ if not isinstance(content, (str, dict)):
+ return {"display_text": str(content or ""), "raw_json": ""}
+
+ try:
+ data = json.loads(content) if isinstance(content, str) else content
+
+ if not isinstance(data, dict):
+ return {"display_text": str(content), "raw_json": ""}
+
+ pretty_json = json.dumps(data, indent=2, ensure_ascii=False)
+
+ # Gemini format check (API Wrapper format).
+ if (
+ "contents" in data
+ and isinstance(data.get("contents"), list)
+ and data["contents"]
+ ):
+ first_part = data["contents"][0].get("parts", [{}])[0]
+ display_text = first_part.get("text", str(data))
+ return {"display_text": display_text, "raw_json": pretty_json}
+
+ # Direct Gemini Content Object Check
+ elif "parts" in data and isinstance(data.get("parts"), list) and data["parts"]:
+ text_parts = [p.get("text", "") for p in data["parts"] if "text" in p]
+ display_text = "\n".join(text_parts) if text_parts else str(data)
+ return {"display_text": display_text, "raw_json": pretty_json}
+
+ # OpenAI response format check.
+ elif (
+ "choices" in data
+ and isinstance(data.get("choices"), list)
+ and data["choices"]
+ ):
+ message = data["choices"][0].get("message", {})
+ display_text = message.get("content", str(data))
+ return {"display_text": display_text, "raw_json": pretty_json}
+
+ # OpenAI request format check.
+ elif (
+ "messages" in data
+ and isinstance(data.get("messages"), list)
+ and data["messages"]
+ ):
+ user_messages = [
+ message.get("content", "")
+ for message in data["messages"]
+ if message.get("role") == "user"
+ ]
+ display_text = user_messages[-1] if user_messages else str(data)
+ return {"display_text": display_text, "raw_json": pretty_json}
+ else:
+ # Not a recognized format.
+ return {"display_text": str(content), "raw_json": pretty_json}
+
+ except (json.JSONDecodeError, TypeError, IndexError):
+ return {"display_text": str(content), "raw_json": ""}
+
+
+def _extract_dataset_rows(dataset: types.EvaluationDataset) -> list[dict[str, Any]]:
+ """Helper to consistently extract rows from either a dataframe or raw eval_cases list."""
+ processed_rows = []
+
+ # Process from DataFrame if available
+ if getattr(dataset, "eval_dataset_df", None) is not None:
+ processed_df = _preprocess_df_for_json(dataset.eval_dataset_df)
+ if processed_df is not None:
+ for _, row in processed_df.iterrows():
+ prompt_key = "request" if "request" in row else "prompt"
+ prompt_info = _extract_text_and_raw_json(row.get(prompt_key))
+ response_info = _extract_text_and_raw_json(row.get("response"))
+ ref_info = _extract_text_and_raw_json(row.get("reference"))
+ processed_row = {
+ "prompt_display_text": prompt_info["display_text"],
+ "prompt_raw_json": prompt_info["raw_json"],
+ "reference": ref_info["display_text"],
+ "reference_raw_json": ref_info["raw_json"],
+ "response_display_text": response_info["display_text"],
+ "response_raw_json": response_info["raw_json"],
+ "intermediate_events": row.get("intermediate_events", None),
+ "agent_data": row.get("agent_data", None),
+ }
+ processed_rows.append(processed_row)
+
+ # Fallback to pure eval_cases extraction
+ elif dataset.eval_cases:
+ for case in dataset.eval_cases:
+ prompt_info = (
+ _extract_text_and_raw_json(case.prompt)
+ if case.prompt
+ else {"display_text": "", "raw_json": ""}
+ )
+
+ response_info = {"display_text": "", "raw_json": ""}
+ if case.responses and case.responses[0].response:
+ response_info = _extract_text_and_raw_json(case.responses[0].response)
+
+ reference_text = ""
+ reference_raw_json = ""
+ if case.reference and case.reference.response:
+ ref_info = _extract_text_and_raw_json(case.reference.response)
+ reference_text = ref_info["display_text"]
+ reference_raw_json = ref_info["raw_json"]
+
+ agent_data_json = None
+ if case.agent_data:
+ agent_data_json = json.dumps(
+ case.agent_data.model_dump(mode="json", exclude_none=True),
+ ensure_ascii=False,
+ )
+
+ intermediate_events_json = None
+ if case.intermediate_events:
+ intermediate_events_json = json.dumps(
+ [
+ e.model_dump(mode="json", exclude_none=True)
+ for e in case.intermediate_events
+ ],
+ ensure_ascii=False,
+ )
+
+ processed_row = {
+ "prompt_display_text": prompt_info["display_text"],
+ "prompt_raw_json": prompt_info["raw_json"],
+ "reference": reference_text,
+ "reference_raw_json": reference_raw_json,
+ "response_display_text": response_info["display_text"],
+ "response_raw_json": response_info["raw_json"],
+ "intermediate_events": intermediate_events_json,
+ "agent_data": agent_data_json,
+ }
+ processed_rows.append(processed_row)
+
+ return processed_rows
+
+
+def get_evaluation_html(eval_result_json: str) -> str:
+ """Returns a self-contained HTML for single evaluation visualization."""
+ payload_b64 = _encode_to_base64(eval_result_json)
+ return textwrap.dedent(
+ f"""
+
+
+
+
+ Evaluation Report
+
+
+
+
+
+
+
Evaluation Report
+
+
+
+
+
+
+"""
+ )
+
+
+def get_comparison_html(eval_result_json: str) -> str:
+ """Returns a self-contained HTML for a side-by-side eval comparison."""
+ payload_b64 = _encode_to_base64(eval_result_json)
+ return textwrap.dedent(
+ f"""
+
+
+
+
+ Eval Comparison Report
+
+
+
+
+
+
+
Eval Comparison Report
+
+
+
+
+
+
+"""
+ )
+
+
+def get_inference_html(dataframe_json: str) -> str:
+ """Returns a self-contained HTML for displaying inference results."""
+ payload_b64 = _encode_to_base64(dataframe_json)
+ return textwrap.dedent(
+ f"""
+
+
+
+
+ Evaluation Dataset
+
+
+
+
+
+
+
+
+
+"""
+ )
+
+
+def display_evaluation_result(
+ eval_result_obj: types.EvaluationResult,
+ candidate_names: Optional[list[str]] = None,
+) -> None:
+ """Displays evaluation result in an IPython environment."""
+ if not _is_ipython_env():
+ logger.warning("Skipping display: not in an IPython environment.")
+ return
+ else:
+ from IPython import display
+
+ try:
+ result_dump = eval_result_obj.model_dump(
+ mode="json", exclude_none=True, exclude={"evaluation_dataset"}
+ )
+ except errors.PydanticSerializationError as e:
+ logger.error(
+ "Serialization Error: %s\nCould not display the evaluation "
+ "result due to a data serialization issue. Please check the "
+ "content of the EvaluationResult object.",
+ e,
+ )
+ return
+ except Exception as e:
+ logger.error("Failed to serialize EvaluationResult: %s", e, exc_info=True)
+ raise
+
+ input_dataset_list = eval_result_obj.evaluation_dataset
+ is_comparison = input_dataset_list and len(input_dataset_list) > 1
+
+ metadata_payload = result_dump.get("metadata", {})
+ metadata_payload["candidate_names"] = candidate_names or metadata_payload.get(
+ "candidate_names"
+ )
+
+ if is_comparison and input_dataset_list:
+ if input_dataset_list[0]:
+ metadata_payload["dataset"] = _extract_dataset_rows(input_dataset_list[0])
+
+ if "eval_case_results" in result_dump:
+ for case_res in result_dump["eval_case_results"]:
+ for resp_idx, cand_res in enumerate(
+ case_res.get("response_candidate_results", [])
+ ):
+ if (
+ input_dataset_list is not None
+ and resp_idx < len(input_dataset_list)
+ and input_dataset_list[resp_idx]
+ ):
+ rows = _extract_dataset_rows(input_dataset_list[resp_idx])
+ case_idx = case_res.get("eval_case_index")
+ if case_idx is not None and case_idx < len(rows):
+ original_case = rows[case_idx]
+ cand_res["display_text"] = original_case[
+ "response_display_text"
+ ]
+ cand_res["raw_json"] = original_case["response_raw_json"]
+
+ win_rates = eval_result_obj.win_rates if eval_result_obj.win_rates else {}
+ if "summary_metrics" in result_dump:
+ for summary in result_dump["summary_metrics"]:
+ if summary.get("metric_name") in win_rates:
+ summary.update(win_rates[summary["metric_name"]])
+
+ result_dump["metadata"] = metadata_payload
+ html_content = get_comparison_html(json.dumps(result_dump))
+ else:
+ single_dataset = input_dataset_list[0] if input_dataset_list else None
+ processed_rows = []
+ if single_dataset is not None:
+ processed_rows = _extract_dataset_rows(single_dataset)
+ metadata_payload["dataset"] = processed_rows
+
+ if "eval_case_results" in result_dump and processed_rows:
+ for case_res in result_dump["eval_case_results"]:
+ case_idx = case_res.get("eval_case_index")
+ if (
+ case_idx is not None
+ and case_idx < len(processed_rows)
+ and case_res.get("response_candidate_results")
+ ):
+ original_case = processed_rows[case_idx]
+ cand_res = case_res["response_candidate_results"][0]
+ cand_res["display_text"] = original_case[
+ "response_display_text"
+ ]
+ cand_res["raw_json"] = original_case["response_raw_json"]
+
+ result_dump["metadata"] = metadata_payload
+ html_content = get_evaluation_html(json.dumps(result_dump))
+
+ display.display(display.HTML(html_content))
+
+
+def display_evaluation_dataset(eval_dataset_obj: types.EvaluationDataset) -> None:
+ """Displays an evaluation dataset in an IPython environment."""
+ if not _is_ipython_env():
+ logger.warning("Skipping display: not in an IPython environment.")
+ return
+ else:
+ from IPython import display
+
+ if (
+ eval_dataset_obj.eval_dataset_df is None
+ or eval_dataset_obj.eval_dataset_df.empty
+ ):
+ logger.warning("No inference data to display.")
+ return
+
+ processed_rows = []
+ df = eval_dataset_obj.eval_dataset_df
+
+ for _, row in df.iterrows():
+ processed_row = {}
+ for col_name, cell_value in row.items():
+ if col_name in ["prompt", "request", "response"]:
+ processed_row[col_name] = _extract_text_and_raw_json(cell_value)
+ elif col_name == "rubric_groups":
+ # Special handling for rubric_groups to keep it as a dict
+ if isinstance(cell_value, dict):
+ processed_row[col_name] = {
+ k: [ # type: ignore[misc]
+ (
+ v_item.model_dump(mode="json")
+ if hasattr(v_item, "model_dump")
+ else v_item
+ )
+ for v_item in v
+ ]
+ for k, v in cell_value.items()
+ }
+ else:
+ processed_row[col_name] = cell_value
+ else:
+ if isinstance(cell_value, (dict, list)):
+ processed_row[col_name] = json.dumps( # type: ignore[assignment]
+ cell_value, ensure_ascii=False, default=_pydantic_serializer
+ )
+ else:
+ processed_row[col_name] = cell_value
+ processed_rows.append(processed_row)
+
+ dataframe_json_string = json.dumps(processed_rows, ensure_ascii=False, default=str)
+ html_content = get_inference_html(dataframe_json_string)
+ display.display(display.HTML(html_content))
+
+
+def get_loss_analysis_html(loss_analysis_json: str) -> str:
+ """Returns self-contained HTML for loss pattern analysis visualization."""
+ payload_b64 = _encode_to_base64(loss_analysis_json)
+ return textwrap.dedent(
+ f"""
+
+
+
+
+ Loss Pattern Analysis
+
+
+
+
+
+
+
+
+"""
+ )
+
+
+def display_loss_clusters_response(
+ response_obj: "types.GenerateLossClustersResponse",
+) -> None:
+ """Displays a GenerateLossClustersResponse in an IPython environment."""
+ if not _is_ipython_env():
+ logger.warning("Skipping display: not in an IPython environment.")
+ return
+ else:
+ from IPython import display
+
+ try:
+ result_dump = response_obj.model_dump(mode="json", exclude_none=True)
+ except Exception as e:
+ logger.error(
+ "Failed to serialize GenerateLossClustersResponse: %s",
+ e,
+ exc_info=True,
+ )
+ raise
+
+ html_content = get_loss_analysis_html(
+ json.dumps(result_dump, ensure_ascii=False, default=_pydantic_serializer)
+ )
+ display.display(display.HTML(html_content))
+
+
+def display_loss_analysis_result(
+ result_obj: "types.LossAnalysisResult",
+) -> None:
+ """Displays a single LossAnalysisResult in an IPython environment."""
+ if not _is_ipython_env():
+ logger.warning("Skipping display: not in an IPython environment.")
+ return
+ else:
+ from IPython import display
+
+ try:
+ # Wrap in a response-like structure for the shared HTML generator
+ wrapped = {"results": [result_obj.model_dump(mode="json", exclude_none=True)]}
+ except Exception as e:
+ logger.error(
+ "Failed to serialize LossAnalysisResult: %s",
+ e,
+ exc_info=True,
+ )
+ raise
+
+ html_content = get_loss_analysis_html(
+ json.dumps(wrapped, ensure_ascii=False, default=_pydantic_serializer)
+ )
+ display.display(display.HTML(html_content))
+
+
+def _get_status_html(status: str, error_message: Optional[str] = None) -> str:
+ """Returns a simple HTML string for displaying a status and optional error."""
+ error_html = ""
+ if error_message:
+ error_html = f"""
+
+ Error:
+
{html.escape(error_message)}
+
+ """
+
+ return textwrap.dedent(
+ f"""
+
+
Status: {html.escape(status)}
+ {error_html}
+
+ """
+ )
+
+
+def _enrich_loss_examples_with_eval_items(
+ results: list["types.LossAnalysisResult"],
+ eval_item_map: Optional[dict[str, dict[str, Any]]],
+) -> list[dict[str, Any]]:
+ """Enriches loss analysis examples with eval item data for visualization.
+
+ For the eval run path, loss examples only have ``evaluation_item``
+ (a resource name) but no ``evaluation_result``. The JS visualization
+ needs ``evaluation_result`` to extract scenario previews and rubric
+ descriptions. This function joins the loss examples with the eval
+ item map so the visualization works identically to the LRO path.
+
+ Args:
+ results: Loss analysis results from the eval run.
+ eval_item_map: Optional mapping from evaluation item resource name
+ to serialized evaluation response data (built by
+ ``_evals_common._build_eval_item_map``).
+
+ Returns:
+ A list of dicts ready for JSON serialization, with ``evaluation_result``
+ populated on each example where a match is found.
+ """
+ result_dicts = []
+ for r in results:
+ r_dump = r.model_dump(mode="json", exclude_none=True)
+ if eval_item_map:
+ clusters = r_dump.get("clusters", [])
+ for cluster in clusters:
+ examples = cluster.get("examples", [])
+ for ex in examples:
+ # Skip if evaluation_result is already populated (LRO path)
+ if ex.get("evaluation_result"):
+ continue
+ # Match by evaluation_item resource name
+ eval_item_ref = ex.get("evaluation_item")
+ if eval_item_ref and eval_item_ref in eval_item_map:
+ ex["evaluation_result"] = eval_item_map[eval_item_ref]
+ result_dicts.append(r_dump)
+ return result_dicts
+
+
+def display_loss_analysis_results(
+ results: list["types.LossAnalysisResult"],
+ eval_item_map: Optional[dict[str, dict[str, Any]]] = None,
+) -> None:
+ """Displays loss analysis results from an EvaluationRun.
+
+ Wraps the list of LossAnalysisResult objects into the same JSON
+ structure used by GenerateLossClustersResponse and renders using
+ the shared get_loss_analysis_html() function.
+
+ When ``eval_item_map`` is provided (from
+ ``get_evaluation_run(include_evaluation_items=True)``), the examples
+ are enriched with scenario and rubric data for the visualization.
+
+ Args:
+ results: A list of LossAnalysisResult objects from
+ EvaluationRunResults.loss_analysis_results.
+ eval_item_map: Optional mapping from evaluation item resource name
+ to serialized evaluation response data for enrichment.
+ """
+ if not _is_ipython_env():
+ logger.warning("Skipping display: not in an IPython environment.")
+ return
+ else:
+ from IPython import display
+
+ try:
+ result_dicts = _enrich_loss_examples_with_eval_items(results, eval_item_map)
+ wrapped = {"results": result_dicts}
+ except Exception as e:
+ logger.error(
+ "Failed to serialize loss analysis results: %s",
+ e,
+ exc_info=True,
+ )
+ raise
+
+ html_content = get_loss_analysis_html(
+ json.dumps(wrapped, ensure_ascii=False, default=_pydantic_serializer)
+ )
+ display.display(display.HTML(html_content))
+
+
+def display_evaluation_run_status(eval_run_obj: "types.EvaluationRun") -> None:
+ """Displays the status of an evaluation run in an IPython environment."""
+ if not _is_ipython_env():
+ logger.warning("Skipping display: not in an IPython environment.")
+ return
+ else:
+ from IPython import display
+
+ status = eval_run_obj.state.name if eval_run_obj.state else "UNKNOWN"
+ error_message = str(eval_run_obj.error) if eval_run_obj.error else None
+ html_content = _get_status_html(status, error_message)
+ display.display(display.HTML(html_content))
+
+
+# Backward-compatible private aliases for the public HTML generators.
+# These are kept temporarily to avoid breaking existing callers that depend on
+# the previous private names. New code should use the public names above.
+_get_evaluation_html = get_evaluation_html
+_get_comparison_html = get_comparison_html
+_get_inference_html = get_inference_html
+_get_loss_analysis_html = get_loss_analysis_html
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_gcs_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_gcs_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..176f2109e451898f9e3d0f449440ea6ff671aa36
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_gcs_utils.py
@@ -0,0 +1,192 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import io
+import json
+import logging
+from typing import Any, Union
+
+from google.cloud import storage # type: ignore[attr-defined]
+from google.cloud.aiplatform.utils.gcs_utils import blob_from_uri
+from google.genai._api_client import BaseApiClient
+import pandas as pd
+import uuid
+
+
+logger = logging.getLogger(__name__)
+
+
+GCS_PREFIX = "gs://"
+
+
+class GcsUtils:
+ """Handles File I/O operations with Google Cloud Storage (GCS)"""
+
+ def __init__(self, api_client: BaseApiClient):
+ self.api_client = api_client
+ self.storage_client = storage.Client(
+ project=self.api_client.project,
+ credentials=self.api_client._credentials,
+ )
+
+ def parse_gcs_path(self, gcs_path: str) -> tuple[str, str]:
+ """Helper to parse gs://bucket/path into (bucket_name, blob_path)."""
+ if not gcs_path.startswith(GCS_PREFIX):
+ raise ValueError(
+ f"Invalid GCS path: '{gcs_path}'. It must start with '{GCS_PREFIX}'."
+ )
+ path_without_prefix = gcs_path[len(GCS_PREFIX) :]
+ if "/" not in path_without_prefix:
+ return path_without_prefix, ""
+ bucket_name, blob_path = path_without_prefix.split("/", 1)
+ return bucket_name, blob_path
+
+ def upload_file_to_gcs(self, upload_gcs_path: str, filename: str) -> None:
+ """Uploads the provided file to a Google Cloud Storage location."""
+
+ blob_from_uri(
+ uri=upload_gcs_path, client=self.storage_client
+ ).upload_from_filename(filename)
+
+ def upload_dataframe(
+ self,
+ df: "pd.DataFrame",
+ gcs_destination_blob_path: str,
+ file_type: str = "jsonl",
+ ) -> None:
+ """Uploads a Pandas DataFrame to a Google Cloud Storage location.
+
+ Args:
+ df: The Pandas DataFrame to upload.
+ gcs_destination_blob_path: The full GCS path for the destination blob
+ (e.g., 'gs://bucket/data/my_dataframe.jsonl').
+ file_type: The format to save the DataFrame ('jsonl' or 'csv'). Defaults
+ to 'jsonl'.
+ """
+ bucket_name, blob_name = self.parse_gcs_path(gcs_destination_blob_path)
+ if not blob_name:
+ raise ValueError(
+ f"Invalid GCS path for blob: '{gcs_destination_blob_path}'. "
+ "It must include the object name (e.g., gs://bucket/file.csv)."
+ )
+ bucket = self.storage_client.bucket(bucket_name)
+ blob = bucket.blob(blob_name)
+
+ buffer = io.StringIO()
+ if file_type == "csv":
+ df.to_csv(buffer, index=False)
+ content_type = "text/csv"
+ elif file_type == "jsonl":
+ df.to_json(buffer, orient="records", lines=True)
+ content_type = "application/jsonl"
+ else:
+ raise ValueError(
+ f"Unsupported file type: '{file_type}'. "
+ "Please provide 'jsonl' or 'csv'."
+ )
+ blob.upload_from_string(buffer.getvalue(), content_type=content_type)
+
+ logger.info(
+ f"DataFrame successfully uploaded to: gs://{bucket.name}/{blob.name}"
+ )
+
+ def upload_json(self, data: dict[str, Any], gcs_destination_blob_path: str) -> None:
+ """Uploads a dictionary as a JSON file to Google Cloud Storage."""
+ bucket_name, blob_name = self.parse_gcs_path(gcs_destination_blob_path)
+ if not blob_name:
+ raise ValueError(
+ f"Invalid GCS path for blob: '{gcs_destination_blob_path}'. "
+ "It must include the object name (e.g., gs://bucket/file.json)."
+ )
+ bucket = self.storage_client.bucket(bucket_name)
+ blob = bucket.blob(blob_name)
+
+ json_data = json.dumps(data, indent=2)
+ blob.upload_from_string(json_data, content_type="application/json")
+
+ logger.info(
+ f"JSON data successfully uploaded to: gs://{bucket_name}/{blob_name}"
+ )
+
+ def upload_json_to_prefix(
+ self,
+ data: dict[str, Any],
+ gcs_dest_prefix: str,
+ filename_prefix: str = "data",
+ ) -> str:
+ """Uploads a dictionary to a GCS prefix with a UUID JSON filename.
+
+ Args:
+ data: The dictionary to upload.
+ gcs_dest_prefix: The GCS prefix (e.g., 'gs://bucket/path/prefix/').
+ filename_prefix: Prefix for the generated filename. Defaults to 'data'.
+
+ Returns:
+ The full GCS path where the file was uploaded.
+
+ Raises:
+ ValueError: If the gcs_dest_prefix is not a valid GCS path.
+ """
+ if not gcs_dest_prefix.startswith(GCS_PREFIX):
+ raise ValueError(
+ f"Invalid GCS destination prefix: '{gcs_dest_prefix}'. Must start"
+ f" with '{GCS_PREFIX}'."
+ )
+
+ gcs_path_without_scheme = gcs_dest_prefix[len(GCS_PREFIX) :]
+ bucket_name, *path_parts = gcs_path_without_scheme.split("/")
+
+ user_prefix_path = "/".join(path_parts)
+ if user_prefix_path and not user_prefix_path.endswith("/"):
+ user_prefix_path += "/"
+
+ filename = f"{filename_prefix}_{uuid.uuid4()}.json"
+
+ blob_name = f"{user_prefix_path}{filename}"
+
+ full_gcs_path = f"{GCS_PREFIX}{bucket_name}/{blob_name}"
+
+ self.upload_json(data, full_gcs_path)
+ return full_gcs_path
+
+ def read_file_contents(self, gcs_filepath: str) -> Union[str, Any]:
+ """Reads the contents of a file from Google Cloud Storage."""
+
+ bucket_name, blob_path = self.parse_gcs_path(gcs_filepath)
+ if not blob_path:
+ raise ValueError(
+ f"Invalid GCS file path: '{gcs_filepath}'. Path must point to a file,"
+ " not just a bucket."
+ )
+ bucket = self.storage_client.bucket(bucket_name)
+ blob = bucket.blob(blob_path)
+ content = blob.download_as_bytes().decode("utf-8")
+ logger.info(f"Successfully read content from '{gcs_filepath}'")
+ return content
+
+ def read_gcs_file_to_dataframe(
+ self, gcs_filepath: str, file_type: str
+ ) -> "pd.DataFrame":
+ """Reads a file from Google Cloud Storage into a Pandas DataFrame."""
+ file_contents = self.read_file_contents(gcs_filepath)
+ if file_type == "csv":
+ return pd.read_csv(io.StringIO(file_contents), encoding="utf-8")
+ elif file_type == "jsonl":
+ return pd.read_json(io.StringIO(file_contents), lines=True)
+ else:
+ raise ValueError(
+ f"Unsupported file type: '{file_type}'. Please provide 'jsonl' or"
+ " 'csv'."
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_logging_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_logging_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cee6b23df411869f56e6b6598d291437c90b9b41
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_logging_utils.py
@@ -0,0 +1,47 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import functools
+from typing import Any, Callable
+from google.genai import _common
+import warnings
+
+
+def show_deprecation_warning_once(
+ message: str,
+) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
+ """Decorator to show a deprecation warning once for a function."""
+
+ def decorator(func: Any) -> Any:
+ warning_done = False
+
+ @functools.wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ nonlocal warning_done
+ if not warning_done:
+ warning_done = True
+ warnings.warn(message, DeprecationWarning, stacklevel=2)
+
+ # Suppress ExperimentalWarning while executing the deprecated wrapper
+ with warnings.catch_warnings():
+ # We ignore ExperimentalWarning because the user will see it
+ # when they migrate to the new prompts module
+ warnings.simplefilter("ignore", category=_common.ExperimentalWarning)
+ return func(*args, **kwargs)
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_observability_data_converter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_observability_data_converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5bef28d9c4b7bf501f63613a9ef81c399266a3c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_observability_data_converter.py
@@ -0,0 +1,186 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Dataset converter for Google Observability GenAI data."""
+
+import json
+import logging
+from typing import Any, Optional
+
+from google.genai import types as genai_types
+from typing_extensions import override
+
+from . import _evals_utils
+from . import types
+
+
+logger = logging.getLogger("agentplatform_genai._observability_data_converters")
+
+
+def _load_jsonl(data: Any, case_id: str) -> list[dict[Any, Any]]:
+ """Parses the raw JSONL data into a list of dict possible."""
+ if isinstance(data, str):
+ json_list = []
+ for line in data.splitlines():
+ loaded_json = json.loads(line)
+ if not isinstance(loaded_json, dict):
+ raise TypeError(
+ f"Decoded JSON payload is not a dict for case "
+ f"{case_id}. Type found: {type(loaded_json).__name__}"
+ )
+ json_list.append(loaded_json)
+ return json_list
+ else:
+ raise TypeError(
+ f"Payload is not a JSONL string for case {case_id}. Type "
+ f"found: {type(data).__name__}"
+ )
+
+
+class ObservabilityDataConverter(_evals_utils.EvalDataConverter):
+ """Converter for dataset in GCP Observability GenAI format."""
+
+ def _message_to_content(self, message: dict[str, Any]) -> genai_types.Content:
+ """Converts Observability GenAI Message format to Content."""
+ parts = []
+ message_parts = message.get("parts", [])
+ if isinstance(message_parts, list):
+ for message_part in message_parts:
+ part = None
+ part_type = message_part.get("type", "")
+ if part_type == "text":
+ part = genai_types.Part(text=message_part.get("content", ""))
+ elif part_type == "blob":
+ part = genai_types.Part(
+ inline_data=genai_types.Blob(
+ data=message_part.get("data", ""),
+ mime_type=message_part.get("mime_type", ""),
+ )
+ )
+ elif part_type == "file_data":
+ part = genai_types.Part(
+ file_data=genai_types.FileData(
+ file_uri=message_part.get("file_uri", ""),
+ mime_type=message_part.get("mime_type", ""),
+ )
+ )
+ elif part_type == "tool_call":
+ # O11y format requires use of id in place of name
+ part = genai_types.Part(
+ function_call=genai_types.FunctionCall(
+ id=message_part.get("id", ""),
+ name=message_part.get("id", ""),
+ args=message_part.get("arguments", {}),
+ )
+ )
+ elif part_type == "tool_call_response":
+ # O11y format requires use of id in place of name
+ part = genai_types.Part(
+ function_response=genai_types.FunctionResponse(
+ id=message_part.get("id", ""),
+ name=message_part.get("id", ""),
+ response=message_part.get("result", {}),
+ )
+ )
+ else:
+ logger.warning(
+ "Skipping message part due to unrecognized message "
+ "part type of '%s'",
+ part_type,
+ )
+
+ if part is not None:
+ parts.append(part)
+
+ return genai_types.Content(parts=parts, role=message.get("role", ""))
+
+ def _parse_messages(
+ self,
+ eval_case_id: str,
+ request_msgs: list[Any],
+ response_msgs: list[Any],
+ system_instruction_msg: Optional[dict[str, Any]] = None,
+ ) -> types.EvalCase:
+ """Parses a set of Observability messages into an EvalCase."""
+ # System instruction message
+ system_instruction = None
+ if system_instruction_msg is not None:
+ system_instruction = self._message_to_content(system_instruction_msg)
+
+ # Request messages
+ prompt = None
+ conversation_history = []
+ if request_msgs:
+ # Extract latest message as prompt
+ prompt = self._message_to_content(request_msgs[-1])
+
+ # All previous messages are conversation history
+ if len(request_msgs) > 1:
+ for i, msg in enumerate(request_msgs[:-1]):
+ conversation_history.append(
+ types.evals.Message(
+ turn_id=str(i),
+ content=self._message_to_content(msg),
+ author=msg.get("role", ""),
+ )
+ )
+
+ # Output messages
+ responses = []
+ for msg in response_msgs:
+ response = types.ResponseCandidate(response=self._message_to_content(msg))
+ responses.append(response)
+
+ return types.EvalCase(
+ eval_case_id=eval_case_id,
+ prompt=prompt,
+ responses=responses,
+ system_instruction=system_instruction,
+ conversation_history=conversation_history,
+ reference=None,
+ )
+
+ @override
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
+ """Converts a list of GCP Observability GenAI cases into an EvaluationDataset."""
+ eval_cases = []
+
+ for i, case in enumerate(raw_data):
+ eval_case_id = f"observability_eval_case_{i}"
+
+ if "request" not in case or "response" not in case:
+ logger.warning(
+ "Skipping case %s due to missing 'request' or 'response' key.",
+ eval_case_id,
+ )
+ continue
+
+ request_data = case.get("request", [])
+ request_list = _load_jsonl(request_data, eval_case_id)
+
+ response_data = case.get("response", [])
+ response_list = _load_jsonl(response_data, eval_case_id)
+
+ system_dict = None
+ if "system_instruction" in case:
+ system_data = case.get("system_instruction", {})
+ system_list = _load_jsonl(system_data, eval_case_id)
+ system_dict = system_list[0] if system_list else {}
+
+ eval_case = self._parse_messages(
+ eval_case_id, request_list, response_list, system_dict
+ )
+ eval_cases.append(eval_case)
+
+ return types.EvaluationDataset(eval_cases=eval_cases)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_management_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_management_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8de400c0d8bf14a468e365fe08550febb864611
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_management_utils.py
@@ -0,0 +1,147 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Utility functions for prompt management."""
+
+from typing import Optional
+
+from google.genai import types as genai_types
+
+from . import types
+
+
+DEFAULT_API_SCHEMA_VERSION = "1.0.0"
+PROMPT_SCHEMA_URI = (
+ "gs://google-cloud-aiplatform/schema/dataset/metadata/text_prompt_1.0.0.yaml"
+)
+PROMPT_TYPE = "multimodal_freeform"
+
+
+def _create_dataset_metadata_from_prompt(
+ prompt: types.Prompt,
+ variables: Optional[list[dict[str, genai_types.Part]]] = None,
+) -> types.SchemaTextPromptDatasetMetadata:
+ """Convert a types.Prompt into types.SchemaTextPromptDatasetMetadata."""
+
+ prompt_metadata = types.SchemaTextPromptDatasetMetadata()
+
+ prompt_api_schema = types.SchemaPromptApiSchema()
+ prompt_api_schema.multimodal_prompt = types.SchemaPromptSpecMultimodalPrompt(
+ prompt_message=prompt.prompt_data
+ )
+
+ prompt_api_schema.api_schema_version = DEFAULT_API_SCHEMA_VERSION
+
+ prompt_metadata.has_prompt_variable = bool(variables)
+
+ if variables:
+ prompt_execution_list = []
+ for prompt_var in variables:
+ prompt_instance_execution = types.SchemaPromptInstancePromptExecution()
+ prompt_instance_execution.arguments = {}
+ for key, val in prompt_var.items():
+ prompt_instance_execution.arguments[key] = (
+ types.SchemaPromptInstanceVariableValue(
+ part_list=types.SchemaPromptSpecPartList(parts=[val])
+ )
+ )
+ prompt_execution_list.append(prompt_instance_execution)
+ prompt_api_schema.executions = prompt_execution_list
+
+ # Need to exclude variables from the prompt message as it is a client side
+ # only field
+ if prompt_api_schema.multimodal_prompt.prompt_message:
+ prompt_message_dict = (
+ prompt_api_schema.multimodal_prompt.prompt_message.model_dump(
+ exclude=["variables"], exclude_none=True
+ )
+ )
+ prompt_api_schema.multimodal_prompt.prompt_message = (
+ types.SchemaPromptSpecPromptMessage(**prompt_message_dict)
+ )
+ prompt_metadata.prompt_api_schema = prompt_api_schema
+
+ prompt_metadata.prompt_type = PROMPT_TYPE
+
+ return prompt_metadata
+
+
+def _create_prompt_from_dataset_metadata(
+ dataset: types.Dataset,
+) -> types.Prompt:
+ """Constructs a types.Prompt from a types.Dataset resource returned from the API.
+
+ Args:
+ dataset: The types.Dataset object containing the prompt metadata.
+
+ Returns:
+ A types.Prompt object reconstructed from the dataset metadata.
+ """
+ if (
+ not hasattr(dataset, "metadata")
+ or dataset.metadata is None
+ or not isinstance(dataset.metadata, types.SchemaTextPromptDatasetMetadata)
+ ):
+ raise ValueError(
+ "Error retrieving prompt: prompt dataset resource is missing 'metadata'."
+ )
+ api_schema = dataset.metadata.prompt_api_schema
+ prompt = types.Prompt()
+
+ if api_schema is None:
+ return prompt
+
+ if api_schema.multimodal_prompt:
+
+ prompt_message = api_schema.multimodal_prompt.prompt_message
+ prompt.prompt_data = prompt_message
+
+ if api_schema.executions:
+ executions = api_schema.executions
+ if executions and prompt.prompt_data is not None:
+ prompt.prompt_data.variables = []
+ for execution in executions:
+ if execution.arguments:
+ args = execution.arguments
+ var_map = {}
+ for key, val in args.items():
+ if (
+ val.part_list is not None
+ and val.part_list.parts is not None
+ ):
+ part_list = val.part_list.parts
+ if part_list and part_list[0].text:
+ var_map[key] = part_list[0]
+ if var_map and prompt.prompt_data.variables is not None:
+ prompt.prompt_data.variables.append(var_map)
+
+ return prompt
+
+
+def _raise_for_invalid_prompt(
+ prompt: types.Prompt,
+) -> None:
+
+ if not prompt.prompt_data:
+ raise ValueError("Prompt data must be provided.")
+ if not prompt.prompt_data.contents:
+ raise ValueError("Prompt contents must be provided.")
+ if not prompt.prompt_data.model:
+ raise ValueError("Model name must be provided.")
+ if (
+ prompt.prompt_data
+ and prompt.prompt_data.contents
+ and len(prompt.prompt_data.contents) > 1
+ ):
+ raise ValueError("Multi-turn prompts are not currently supported.")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_optimizer_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_optimizer_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a218432ee167534d081e3f0e7b9363be73ee52e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_optimizer_utils.py
@@ -0,0 +1,215 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Utility functions for prompt optimizer."""
+
+import json
+from typing import Any, Optional, Union
+from typing_extensions import TypeAlias
+
+from pydantic import ValidationError
+
+from . import types
+
+try:
+ import pandas as pd # pylint: disable=g-import-not-at-top
+
+ PandasDataFrame: TypeAlias = pd.DataFrame
+except ImportError:
+ pd = None
+ PandasDataFrame = Any # type: ignore[misc]
+
+
+def _construct_input_prompt(
+ example_df: PandasDataFrame,
+ *,
+ prompt_col_name: str,
+ model_response_col_name: str,
+ rubrics_col_name: str,
+ rubrics_evaluations_col_name: str,
+ target_response_col_name: str,
+ system_instruction: Optional[str] = None,
+) -> str:
+ """Construct the input prompt for the few shot prompt optimizer."""
+
+ all_prompts = []
+ for row in example_df.to_dict(orient="records"):
+ example_data = {
+ "prompt": row[prompt_col_name],
+ "model_response": row[model_response_col_name],
+ }
+ if rubrics_col_name:
+ example_data["rubrics"] = row[rubrics_col_name]
+ if rubrics_evaluations_col_name:
+ example_data["rubrics_evaluations"] = row[rubrics_evaluations_col_name]
+ if target_response_col_name:
+ example_data["target_response"] = row[target_response_col_name]
+
+ json_str = json.dumps(example_data, indent=2)
+ all_prompts.append(f"```JSON\n{json_str}\n```")
+
+ all_prompts_str = "\n\n".join(all_prompts)
+
+ if system_instruction is None:
+ system_instruction = ""
+
+ return "\n".join(
+ [
+ "Original System Instructions:\n",
+ system_instruction,
+ "Examples:\n",
+ all_prompts_str,
+ "\nNew Output:\n",
+ ]
+ )
+
+
+def _get_few_shot_prompt(
+ system_instruction: str,
+ config: types.OptimizeConfig,
+) -> str:
+ """Builds the few shot prompt."""
+
+ if config.examples_dataframe is None:
+ raise ValueError("The 'examples_dataframe' is required in the config.")
+
+ if "prompt" not in config.examples_dataframe.columns:
+ raise ValueError("'prompt' is required in the examples_dataframe.")
+
+ if "prompt" not in config.examples_dataframe.columns:
+ raise ValueError("'prompt' is required in the examples_dataframe.")
+ prompt_col_name = "prompt"
+
+ if "model_response" not in config.examples_dataframe.columns:
+ raise ValueError("'model_response' is required in the example_df.")
+ model_response_col_name = "model_response"
+
+ target_response_col_name = ""
+ rubrics_col_name = ""
+ rubrics_evaluations_col_name = ""
+
+ if (
+ config.optimization_target
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
+ ):
+ if "target_response" not in config.examples_dataframe.columns:
+ raise ValueError("'target_response' is required in the examples_dataframe.")
+ target_response_col_name = "target_response"
+ if "rubrics" in config.examples_dataframe.columns:
+ raise ValueError(
+ "Only 'target_response' should be provided "
+ "for OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE "
+ "but 'rubrics' was provided."
+ )
+
+ elif (
+ config.optimization_target
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS
+ ):
+ if not {"rubrics", "rubrics_evaluations"}.issubset(
+ config.examples_dataframe.columns
+ ):
+ raise ValueError(
+ "rubrics and rubrics_evaluations is required in the"
+ "examples_dataframe when rubrics is set."
+ )
+
+ rubrics_col_name = "rubrics"
+ rubrics_evaluations_col_name = "rubrics_evaluations"
+ if "target_response" in config.examples_dataframe.columns:
+ raise ValueError(
+ "Only 'rubrics' and 'rubrics_evaluations' should be provided "
+ "for OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS "
+ "but target_response was provided."
+ )
+ else:
+ raise ValueError("One of 'target_response' or 'rubrics' must be provided.")
+
+ return _construct_input_prompt(
+ config.examples_dataframe,
+ prompt_col_name=prompt_col_name,
+ model_response_col_name=model_response_col_name,
+ rubrics_col_name=rubrics_col_name,
+ rubrics_evaluations_col_name=rubrics_evaluations_col_name,
+ target_response_col_name=target_response_col_name,
+ system_instruction=system_instruction,
+ )
+
+
+def _get_service_account(
+ config: types.PromptOptimizerConfigOrDict,
+) -> str:
+ """Get the service account from the config for the custom job."""
+ if isinstance(config, dict):
+ config = types.PromptOptimizerConfig.model_validate(config)
+
+ if (
+ config.service_account and config.service_account_project_number
+ ): # pytype: disable=attribute-error
+ raise ValueError(
+ "Only one of service_account or "
+ "service_account_project_number can be provided."
+ )
+ elif config.service_account: # pytype: disable=attribute-error
+ return config.service_account # pytype: disable=attribute-error
+ elif config.service_account_project_number: # pytype: disable=attribute-error
+ return f"{config.service_account_project_number}-compute@developer.gserviceaccount.com" # pytype: disable=attribute-error
+ else:
+ raise ValueError(
+ "Either service_account or service_account_project_number " "is required."
+ )
+
+
+def _clean_and_parse_optimized_prompt(output_str: str) -> Optional[Any]:
+ """Cleans a string response returned from the prompt optimizer endpoint.
+
+ Args:
+ output_str: The optimized prompt string containing the JSON data,
+ potentially with markdown formatting like ```json ... ```.
+
+ Returns:
+ The parsed JSON data, or None if parsing fails.
+ """
+ lines = output_str.strip().split("\n")
+ # Remove markdown delimiters
+ if lines and lines[0].strip().startswith("```"):
+ cleaned_string = "\n".join(lines[1:-1])
+ else:
+ cleaned_string = output_str
+
+ # remove any 'json' labels if they exist on the first line.
+ if cleaned_string.strip().startswith("json"):
+ cleaned_string = cleaned_string.strip()[4:].strip()
+
+ try:
+ return json.loads(cleaned_string)
+ except json.JSONDecodeError as e:
+ # TODO(b/437144880): raise errors.ClientError here instead
+ raise ValueError(
+ f"Failed to parse the response from prompt optimizer endpoint. {e}"
+ ) from e
+
+
+def _parse(
+ output_str: str,
+) -> Union[
+ types.prompts.ParsedResponse,
+ types.prompts.ParsedResponseFewShot,
+]:
+ """Parses the output string from the prompt optimizer endpoint."""
+ parsed_out = _clean_and_parse_optimized_prompt(output_str)
+ try:
+ return types.prompts.ParsedResponse(**parsed_out)
+ except ValidationError:
+ return types.prompts.ParsedResponseFewShot(**parsed_out)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_skills_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_skills_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d46a3e0ea93da234711fb0415622cc01f2c60a93
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_skills_utils.py
@@ -0,0 +1,147 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Utility functions for Skills."""
+
+import asyncio
+import base64
+import datetime
+import io
+import os
+import pathlib
+import time
+from typing import Any, Awaitable, Callable
+import zipfile
+
+
+def zip_directory(directory_path: pathlib.Path | str) -> bytes:
+ """Zips a directory into memory and returns the bytes.
+
+ Args:
+ directory_path (pathlib.Path | str): Required. The local path to the
+ directory.
+
+ Returns:
+ bytes: The zipped directory content.
+ """
+ directory_str = os.fspath(directory_path)
+ if not os.path.isdir(directory_str):
+ raise ValueError(f"Path is not a directory: {directory_str}")
+
+ zip_buffer = io.BytesIO()
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
+ for root, _, files in os.walk(directory_str):
+ for file in files:
+ file_path = os.path.join(root, file)
+ arcname = os.path.relpath(file_path, directory_str)
+
+ # Read actual file data
+ with open(file_path, "rb") as f:
+ file_data = f.read()
+
+ # Use deterministic ZipInfo (mtime: 1980-01-01 00:00:00)
+ zinfo = zipfile.ZipInfo(arcname, date_time=(1980, 1, 1, 0, 0, 0))
+ zinfo.compress_type = zipfile.ZIP_DEFLATED
+ zinfo.external_attr = 0o644 << 16 # Constant file permissions
+
+ zip_file.writestr(zinfo, file_data)
+ return zip_buffer.getvalue()
+
+
+def get_zipped_filesystem_payload(directory_path: pathlib.Path | str) -> str:
+ """Zips a directory and base64-encodes the result to a UTF-8 string.
+
+ Args:
+ directory_path (pathlib.Path | str): Required. The local path to the
+ directory.
+
+ Returns:
+ str: The base64-encoded zipped directory.
+ """
+ zip_bytes = zip_directory(directory_path)
+ return base64.b64encode(zip_bytes).decode("utf-8")
+
+
+def await_operation(
+ *,
+ operation_name: str,
+ get_operation_fn: Callable[..., Any],
+ poll_interval: datetime.timedelta | float = 10.0,
+ timeout_seconds: float = 300.0,
+) -> Any:
+ """Waits for a long running operation to complete.
+
+ Args:
+ operation_name (str): Required. The name of the operation.
+ get_operation_fn (Callable): Required. Function to get the operation
+ status.
+ poll_interval (datetime.timedelta | float): The interval between polls.
+ timeout_seconds (float): The maximum wait duration in seconds.
+
+ Returns:
+ Any: The completed operation.
+ """
+ if isinstance(poll_interval, datetime.timedelta):
+ poll_seconds = poll_interval.total_seconds()
+ else:
+ poll_seconds = float(poll_interval)
+
+ start_time = time.time()
+ operation = get_operation_fn(operation_name=operation_name)
+ while not operation.done:
+ if (time.time() - start_time) > timeout_seconds:
+ raise TimeoutError(
+ f"Operation {operation_name} did not complete within the timeout "
+ f"of {timeout_seconds} seconds."
+ )
+ time.sleep(poll_seconds)
+ operation = get_operation_fn(operation_name=operation.name)
+ return operation
+
+
+async def await_operation_async(
+ *,
+ operation_name: str,
+ get_operation_fn: Callable[..., Awaitable[Any]],
+ poll_interval: datetime.timedelta | float = 10.0,
+ timeout_seconds: float = 300.0,
+) -> Any:
+ """Waits for a long running operation to complete asynchronously.
+
+ Args:
+ operation_name (str): Required. The name of the operation.
+ get_operation_fn (Callable): Required. Async function to get the operation
+ status.
+ poll_interval (datetime.timedelta | float): The interval between polls.
+ timeout_seconds (float): The maximum wait duration in seconds.
+
+ Returns:
+ Any: The completed operation.
+ """
+ if isinstance(poll_interval, datetime.timedelta):
+ poll_seconds = poll_interval.total_seconds()
+ else:
+ poll_seconds = float(poll_interval)
+
+ start_time = time.time()
+ operation = await get_operation_fn(operation_name=operation_name)
+ while not operation.done:
+ if (time.time() - start_time) > timeout_seconds:
+ raise TimeoutError(
+ f"Operation {operation_name} did not complete within the timeout "
+ f"of {timeout_seconds} seconds."
+ )
+ await asyncio.sleep(poll_seconds)
+ operation = await get_operation_fn(operation_name=operation.name)
+ return operation
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_transformers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb6f477cf868e1597a04494b282c593ea7c292e7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_transformers.py
@@ -0,0 +1,538 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Transformers module for Vertex addons."""
+import json
+import re
+from typing import Any
+
+from google.genai._common import get_value_by_path as getv
+
+from . import _evals_constant
+from . import _evals_data_converters
+from . import types
+
+_METRIC_RES_NAME_RE = r"^projects/[^/]+/locations/[^/]+/evaluationMetrics/[^/]+$"
+
+
+def t_metrics(
+ metrics: "list[types.MetricSubclass]",
+ set_default_aggregation_metrics: bool = False,
+) -> list[dict[str, Any]]:
+ """Prepares the metric payload for the evaluation request.
+
+ Args:
+ metrics: A list of metrics used for evaluation.
+ set_default_aggregation_metrics: Whether to set default aggregation metrics.
+ Returns:
+ A list of resolved metric payloads for the evaluation request.
+ """
+ metrics_payload = []
+
+ for metric in metrics:
+ metric_payload_item: dict[str, Any] = {}
+
+ metric_id = getv(metric, ["metric"]) or getv(metric, ["name"])
+ metric_name = metric_id.lower() if metric_id else None
+
+ if set_default_aggregation_metrics:
+ metric_payload_item["aggregation_metrics"] = [
+ "AVERAGE",
+ "STANDARD_DEVIATION",
+ ]
+
+ if metric_name == "exact_match":
+ metric_payload_item["exact_match_spec"] = {}
+ elif metric_name == "bleu":
+ metric_payload_item["bleu_spec"] = {}
+ elif metric_name and metric_name.startswith("rouge"):
+ rouge_type = metric_name.replace("_", "")
+ metric_payload_item["rouge_spec"] = {"rouge_type": rouge_type}
+ # API Pre-defined metrics
+ elif (
+ metric_name and metric_name in _evals_constant.SUPPORTED_PREDEFINED_METRICS
+ ):
+ metric_payload_item["predefined_metric_spec"] = {
+ "metric_spec_name": metric_name,
+ "metric_spec_parameters": metric.metric_spec_parameters,
+ }
+ # Custom Code Execution Metric
+ elif (
+ hasattr(metric, "remote_custom_function") and metric.remote_custom_function
+ ):
+ metric_payload_item["custom_code_execution_spec"] = {
+ "evaluation_function": metric.remote_custom_function
+ }
+ elif (
+ isinstance(metric, types.CodeExecutionMetric)
+ or (
+ isinstance(metric, types.Metric)
+ and isinstance(getattr(metric, "custom_function", None), str)
+ )
+ ) and getattr(metric, "custom_function", None):
+ metric_payload_item["custom_code_execution_spec"] = {
+ "evaluation_function": metric.custom_function
+ }
+ # LLM-based metrics
+ elif hasattr(metric, "prompt_template") and metric.prompt_template:
+ llm_based_spec: dict[str, Any] = {
+ "metric_prompt_template": metric.prompt_template
+ }
+ system_instruction = getv(metric, ["judge_model_system_instruction"])
+ if system_instruction:
+ llm_based_spec["system_instruction"] = system_instruction
+ rubric_group_name = getv(metric, ["rubric_group_name"])
+ if rubric_group_name:
+ llm_based_spec["rubric_group_key"] = rubric_group_name
+ return_raw_output = getv(metric, ["return_raw_output"])
+ if return_raw_output:
+ llm_based_spec["custom_output_format_config"] = {
+ "return_raw_output": return_raw_output
+ }
+
+ autorater_config: dict[str, Any] = {}
+ if hasattr(metric, "judge_model") and metric.judge_model:
+ autorater_config["autorater_model"] = metric.judge_model
+ if (
+ hasattr(metric, "judge_model_generation_config")
+ and metric.judge_model_generation_config
+ ):
+ autorater_config["generation_config"] = (
+ metric.judge_model_generation_config
+ )
+ if (
+ hasattr(metric, "judge_model_sampling_count")
+ and metric.judge_model_sampling_count
+ ):
+ autorater_config["sampling_count"] = metric.judge_model_sampling_count
+
+ if autorater_config:
+ llm_based_spec["judge_autorater_config"] = autorater_config
+
+ result_parsing_function = getv(metric, ["result_parsing_function"])
+ if result_parsing_function:
+ llm_based_spec["result_parser_config"] = {
+ "custom_code_parser_config": {
+ "parsing_function": result_parsing_function
+ }
+ }
+
+ metric_payload_item["llm_based_metric_spec"] = llm_based_spec
+ elif getattr(metric, "metric_resource_name", None) is not None:
+ # Safe pass
+ pass
+ else:
+ raise ValueError(
+ f"Unsupported metric type or invalid metric name: {metric_name}"
+ )
+ metrics_payload.append(metric_payload_item)
+ return metrics_payload
+
+
+def t_metric_sources(metrics: list[Any]) -> list[dict[str, Any]]:
+ """Prepares the MetricSource payload."""
+ sources_payload = []
+ for metric in metrics:
+ resource_name = getattr(metric, "metric_resource_name", None)
+ if (
+ not resource_name
+ and isinstance(metric, str)
+ and re.match(_METRIC_RES_NAME_RE, metric)
+ ):
+ resource_name = metric
+
+ if resource_name:
+ sources_payload.append({"metric_resource_name": resource_name})
+ else:
+ if hasattr(metric, "metric") and not isinstance(metric, str):
+ metric = metric.metric
+
+ if not hasattr(metric, "name"):
+ metric = types.Metric(name=str(metric))
+
+ metric_payload = t_metrics([metric])[0]
+ sources_payload.append({"metric": metric_payload})
+ return sources_payload
+
+
+def t_user_scenario_generation_config(
+ config: "types.evals.UserScenarioGenerationConfigOrDict",
+) -> dict[str, Any]:
+ """Transforms UserScenarioGenerationConfig to Vertex AI format."""
+ payload: dict[str, Any] = {}
+ config_dict = config if isinstance(config, dict) else config.model_dump()
+
+ if getv(config_dict, ["count"]) is not None:
+ payload["user_scenario_count"] = getv(config_dict, ["count"])
+ if getv(config_dict, ["generation_instruction"]) is not None:
+ payload["simulation_instruction"] = getv(
+ config_dict, ["generation_instruction"]
+ )
+ if getv(config_dict, ["environment_context"]) is not None:
+ payload["environment_data"] = getv(config_dict, ["environment_context"])
+ if getv(config_dict, ["model_name"]) is not None:
+ payload["model_name"] = getv(config_dict, ["model_name"])
+
+ return payload
+
+
+def t_metric_for_registry(
+ metric: "types.Metric",
+) -> dict[str, Any]:
+ """Prepares the metric payload specifically for EvaluationMetric registration."""
+ metric_payload_item: dict[str, Any] = {}
+ metric_name = getattr(metric, "name", None)
+ if metric_name:
+ metric_name = metric_name.lower()
+
+ # Custom Code Execution Metric
+ if hasattr(metric, "remote_custom_function") and metric.remote_custom_function:
+ metric_payload_item["custom_code_execution_spec"] = {
+ "evaluation_function": metric.remote_custom_function
+ }
+ elif (
+ isinstance(metric, types.CodeExecutionMetric)
+ or (
+ isinstance(metric, types.Metric)
+ and isinstance(getattr(metric, "custom_function", None), str)
+ )
+ ) and getattr(metric, "custom_function", None):
+ metric_payload_item["custom_code_execution_spec"] = {
+ "evaluation_function": metric.custom_function
+ }
+
+ # LLM-based metric
+ elif (hasattr(metric, "prompt_template") and metric.prompt_template) or (
+ hasattr(metric, "rubric_group_name") and metric.rubric_group_name
+ ):
+ llm_based_spec: dict[str, Any] = {}
+
+ if hasattr(metric, "prompt_template") and metric.prompt_template:
+ llm_based_spec["metric_prompt_template"] = metric.prompt_template
+ system_instruction = getv(metric, ["judge_model_system_instruction"])
+ if system_instruction:
+ llm_based_spec["system_instruction"] = system_instruction
+ rubric_group_name = getv(metric, ["rubric_group_name"])
+ if rubric_group_name:
+ llm_based_spec["rubric_group_key"] = rubric_group_name
+
+ autorater_config: dict[str, Any] = {}
+ if hasattr(metric, "judge_model") and metric.judge_model:
+ autorater_config["autorater_model"] = metric.judge_model
+ if (
+ hasattr(metric, "judge_model_generation_config")
+ and metric.judge_model_generation_config
+ ):
+ autorater_config["generation_config"] = metric.judge_model_generation_config
+ if (
+ hasattr(metric, "judge_model_sampling_count")
+ and metric.judge_model_sampling_count
+ ):
+ autorater_config["sampling_count"] = metric.judge_model_sampling_count
+
+ if autorater_config:
+ llm_based_spec["judge_autorater_config"] = autorater_config
+
+ result_parsing_function = getv(metric, ["result_parsing_function"])
+ if result_parsing_function:
+ llm_based_spec["result_parser_config"] = {
+ "custom_code_parser_config": {
+ "parsing_function": result_parsing_function
+ }
+ }
+
+ metric_payload_item["llm_based_metric_spec"] = llm_based_spec
+
+ else:
+ raise ValueError(f"Unsupported metric type: {metric_name}")
+
+ return metric_payload_item
+
+
+_ALLOWED_PART_FIELDS = frozenset(
+ {
+ "text",
+ "inline_data",
+ "file_data",
+ "function_call",
+ "function_response",
+ "video_metadata",
+ "thought",
+ "thought_signature",
+ "code_execution_result",
+ "executable_code",
+ "media_resolution",
+ }
+)
+
+
+def _sanitize_agent_data(agent_data: dict[str, Any]) -> dict[str, Any]:
+ """Strips SDK-only fields from agent_data so the API accepts the payload.
+
+ The SDK's AgentData model may contain fields like 'tool_call',
+ 'tool_response', 'part_metadata', and 'will_continue' that don't exist
+ in the API's AgentData / Content proto. This function recursively removes
+ them from content parts and keeps only API-recognized top-level fields.
+ """
+ if not isinstance(agent_data, dict):
+ return agent_data
+
+ sanitized: dict[str, Any] = {}
+ for key, value in agent_data.items():
+ if key == "turns" and isinstance(value, list):
+ sanitized["turns"] = [
+ _sanitize_turn(t) for t in value if isinstance(t, dict)
+ ]
+ elif key == "agents" and isinstance(value, dict):
+ sanitized["agents"] = {
+ k: _sanitize_agent_config(v) if isinstance(v, dict) else v
+ for k, v in value.items()
+ }
+ # Skip unknown top-level fields (e.g. "error" from failed agent runs).
+ return sanitized
+
+
+def _sanitize_agent_config(config: dict[str, Any]) -> dict[str, Any]:
+ """Sanitizes an AgentConfig dict, keeping only API-known fields."""
+ allowed = {
+ "agent_id",
+ "agent_type",
+ "description",
+ "instruction",
+ "tools",
+ "sub_agents",
+ }
+ return {k: v for k, v in config.items() if k in allowed}
+
+
+def _sanitize_turn(turn: dict[str, Any]) -> dict[str, Any]:
+ """Sanitizes a ConversationTurn dict."""
+ sanitized: dict[str, Any] = {}
+ for key, value in turn.items():
+ if key == "events" and isinstance(value, list):
+ sanitized["events"] = [
+ _sanitize_event(e) for e in value if isinstance(e, dict)
+ ]
+ else:
+ sanitized[key] = value
+ return sanitized
+
+
+def _sanitize_event(event: dict[str, Any]) -> dict[str, Any]:
+ """Sanitizes an AgentEvent dict."""
+ sanitized: dict[str, Any] = {}
+ for key, value in event.items():
+ if key == "content" and isinstance(value, dict):
+ sanitized["content"] = _sanitize_content(value)
+ elif key in ("author", "event_time", "state_delta", "active_tools"):
+ sanitized[key] = value
+ # Skip unknown event-level fields.
+ return sanitized
+
+
+def _sanitize_content(content: dict[str, Any]) -> dict[str, Any]:
+ """Sanitizes a Content dict, stripping unknown fields from parts."""
+ sanitized: dict[str, Any] = {}
+ for key, value in content.items():
+ if key == "parts" and isinstance(value, list):
+ sanitized["parts"] = [
+ _sanitize_part(p) for p in value if isinstance(p, dict)
+ ]
+ elif key == "role":
+ sanitized["role"] = value
+ return sanitized
+
+
+def _sanitize_part(part: dict[str, Any]) -> dict[str, Any]:
+ """Keeps only API-recognized fields in a Part dict."""
+ sanitized: dict[str, Any] = {}
+ for key, value in part.items():
+ if key in _ALLOWED_PART_FIELDS:
+ if key == "function_response" and isinstance(value, dict):
+ # Strip unknown sub-fields like 'will_continue'.
+ sanitized[key] = {
+ k: v for k, v in value.items() if k in ("name", "id", "response")
+ }
+ else:
+ sanitized[key] = value
+ return sanitized
+
+
+def _extract_agent_data_from_df(
+ eval_dataset: Any,
+ case_idx: int,
+) -> Any:
+ """Extracts agent_data from a DataFrame-based EvaluationDataset by row index."""
+ if not eval_dataset:
+ return None
+ ds = eval_dataset[0] if isinstance(eval_dataset, list) else eval_dataset
+ df = getv(ds, ["eval_dataset_df"])
+ if df is None or not hasattr(df, "iloc"):
+ return None
+ if case_idx < 0 or case_idx >= len(df):
+ return None
+ row = df.iloc[case_idx]
+ if "agent_data" not in row or row["agent_data"] is None:
+ return None
+ return row["agent_data"]
+
+
+def t_inline_results(
+ eval_results: list[Any],
+) -> list[dict[str, Any]]:
+ """Transforms a list of SDK EvaluationResults into API EvaluationResults."""
+ api_results: list[dict[str, Any]] = []
+
+ for eval_result in eval_results:
+ metadata = getv(eval_result, ["metadata"])
+ candidate_names = getv(metadata, ["candidate_names"]) if metadata else []
+ candidate_names = candidate_names or []
+
+ eval_dataset = getv(eval_result, ["evaluation_dataset"])
+ eval_cases: list[Any] = []
+ if isinstance(eval_dataset, list) and eval_dataset:
+ eval_cases = getv(eval_dataset[0], ["eval_cases"]) or []
+
+ eval_case_results = getv(eval_result, ["eval_case_results"]) or []
+
+ for case_result in eval_case_results:
+ case_idx = getv(case_result, ["eval_case_index"]) or 0
+
+ eval_case = None
+ if 0 <= case_idx < len(eval_cases):
+ eval_case = eval_cases[case_idx]
+
+ prompt_payload: dict[str, Any] = {}
+ if eval_case:
+ agent_data = getv(eval_case, ["agent_data"])
+ prompt = getv(eval_case, ["prompt"])
+
+ if agent_data:
+ if hasattr(agent_data, "model_dump"):
+ prompt_payload["agent_data"] = _sanitize_agent_data(
+ agent_data.model_dump(exclude_none=True)
+ )
+ elif isinstance(agent_data, dict):
+ prompt_payload["agent_data"] = _sanitize_agent_data(agent_data)
+ else:
+ prompt_payload["agent_data"] = agent_data
+ elif prompt:
+ text = _evals_data_converters._get_content_text(
+ prompt
+ ) # pylint: disable=protected-access
+ if text:
+ prompt_payload["text"] = str(text)
+
+ # Fallback: extract agent_data from the DataFrame when eval_cases
+ # are not available (e.g., run_inference -> evaluate flow).
+ if not prompt_payload:
+ df_agent_data = _extract_agent_data_from_df(eval_dataset, case_idx)
+ if df_agent_data is not None:
+ if hasattr(df_agent_data, "model_dump"):
+ prompt_payload["agent_data"] = _sanitize_agent_data(
+ df_agent_data.model_dump(exclude_none=True)
+ )
+ elif isinstance(df_agent_data, str):
+ try:
+ parsed = json.loads(df_agent_data)
+ if isinstance(parsed, dict) and "error" in parsed:
+ pass # Skip error payloads from failed agent runs.
+ else:
+ prompt_payload["agent_data"] = _sanitize_agent_data(
+ parsed
+ )
+ except (json.JSONDecodeError, ValueError):
+ pass
+ elif isinstance(df_agent_data, dict):
+ if "error" not in df_agent_data:
+ prompt_payload["agent_data"] = _sanitize_agent_data(
+ df_agent_data
+ )
+
+ cand_results = getv(case_result, ["response_candidate_results"]) or []
+ for resp_cand_result in cand_results:
+ resp_idx = getv(resp_cand_result, ["response_index"]) or 0
+ cand_name = f"candidate-{resp_idx}"
+ if 0 <= resp_idx < len(candidate_names):
+ cand_name = candidate_names[resp_idx]
+
+ metric_results = getv(resp_cand_result, ["metric_results"]) or {}
+
+ for metric_name, metric_res in metric_results.items():
+ api_rubric_verdicts: list[dict[str, Any]] = []
+ rubric_verdicts = getv(metric_res, ["rubric_verdicts"]) or []
+
+ for verdict in rubric_verdicts:
+ verdict_dict: dict[str, Any] = {}
+ eval_rubric = getv(verdict, ["evaluated_rubric"])
+
+ if eval_rubric:
+ rubric_dict: dict[str, Any] = {}
+ rubric_id = getv(eval_rubric, ["rubric_id"])
+ if rubric_id:
+ rubric_dict["rubric_id"] = str(rubric_id)
+
+ rubric_content = getv(eval_rubric, ["content"])
+ if rubric_content:
+ text = getv(rubric_content, ["text"])
+ prop = getv(rubric_content, ["property"])
+
+ content_dict: dict[str, Any] = {}
+ if text:
+ content_dict["text"] = str(text)
+ if prop:
+ desc = getv(prop, ["description"])
+ if desc:
+ content_dict["property"] = {
+ "description": str(desc)
+ }
+ rubric_dict["content"] = content_dict
+ verdict_dict["evaluated_rubric"] = rubric_dict
+
+ verdict_bool = getv(verdict, ["verdict"])
+ if verdict_bool is not None:
+ verdict_dict["verdict"] = bool(verdict_bool)
+
+ reasoning = getv(verdict, ["reasoning"])
+ if reasoning:
+ verdict_dict["reasoning"] = str(reasoning)
+
+ if verdict_dict:
+ api_rubric_verdicts.append(verdict_dict)
+
+ score = getv(metric_res, ["score"])
+ explanation = getv(metric_res, ["explanation"])
+
+ candidate_result_payload: dict[str, Any] = {
+ "candidate": str(cand_name),
+ "metric": str(metric_name),
+ }
+ if score is not None:
+ candidate_result_payload["score"] = float(score)
+ if explanation:
+ candidate_result_payload["explanation"] = str(explanation)
+ if api_rubric_verdicts:
+ candidate_result_payload["rubric_verdicts"] = (
+ api_rubric_verdicts
+ )
+
+ api_eval_result = {
+ "request": {"prompt": prompt_payload},
+ "metric": str(metric_name),
+ "candidate_results": [candidate_result_payload],
+ }
+ api_results.append(api_eval_result)
+
+ return api_results
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/a2a_task_events.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/a2a_task_events.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae122b3d10d15ad88c8ac9847822719294e50bbe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/a2a_task_events.py
@@ -0,0 +1,508 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import json
+import logging
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.a2ataskevents")
+
+logger.setLevel(logging.INFO)
+
+
+def _AppendAgentEngineTaskEventRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["task_events"]) is not None:
+ setv(
+ to_object,
+ ["taskEvents"],
+ [item for item in getv(from_object, ["task_events"])],
+ )
+
+ return to_object
+
+
+def _AppendAgentEngineTaskEventResponse_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ return to_object
+
+
+def _ListAgentEngineTaskEventsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ if getv(from_object, ["order_by"]) is not None:
+ setv(parent_object, ["_query", "orderBy"], getv(from_object, ["order_by"]))
+
+ return to_object
+
+
+def _ListAgentEngineTaskEventsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineTaskEventsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class A2aTaskEvents(_api_module.BaseModule):
+
+ def append(
+ self,
+ *,
+ name: str,
+ task_events: list[types.TaskEventOrDict],
+ config: Optional[types.AppendAgentEngineTaskEventConfigOrDict] = None,
+ ) -> types.AppendAgentEngineTaskEventResponse:
+ """
+ Adds events to an Agent Engine task.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to append the events to. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{a2a_task_id}`.
+ task_events (list[TaskEvent]):
+ Required. The events to append to the task.
+
+ Returns:
+ AppendAgentEngineTaskEventResponse: The response for appending the task events.
+
+ """
+
+ parameter_model = types._AppendAgentEngineTaskEventRequestParameters(
+ name=name,
+ task_events=task_events,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AppendAgentEngineTaskEventRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:appendEvents".format_map(request_url_dict)
+ else:
+ path = "{name}:appendEvents"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AppendAgentEngineTaskEventResponse_from_vertex(
+ response_dict
+ )
+
+ return_value = types.AppendAgentEngineTaskEventResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTaskEventsConfigOrDict] = None,
+ ) -> types.ListAgentEngineTaskEventsResponse:
+ """
+ Lists Agent Engine task events.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to list events for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{a2a_task_id}`.
+ config (ListAgentEngineTaskEventsConfig):
+ Optional. Additional configurations for listing the Agent Engine tasks.
+
+ Returns:
+ ListAgentEngineTaskEventsResponse: The requested Agent Engine tasks.
+
+ """
+
+ parameter_model = types._ListAgentEngineTaskEventsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineTaskEventsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/events".format_map(request_url_dict)
+ else:
+ path = "{name}/events"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineTaskEventsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTaskEventsConfigOrDict] = None,
+ ) -> Iterator[types.TaskEvent]:
+ """Lists the A2A tasks of an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list tasks for.
+ config (List):
+ Optional. The configuration for the tasks to list.
+
+ Returns:
+ Iterable[TaskEvent]: An iterable of Task events.
+ """
+
+ return Pager(
+ "taskEvents",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+
+class AsyncA2aTaskEvents(_api_module.BaseModule):
+
+ async def append(
+ self,
+ *,
+ name: str,
+ task_events: list[types.TaskEventOrDict],
+ config: Optional[types.AppendAgentEngineTaskEventConfigOrDict] = None,
+ ) -> types.AppendAgentEngineTaskEventResponse:
+ """
+ Adds events to an Agent Engine task.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to append the events to. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{a2a_task_id}`.
+ task_events (list[TaskEvent]):
+ Required. The events to append to the task.
+
+ Returns:
+ AppendAgentEngineTaskEventResponse: The response for appending the task events.
+
+ """
+
+ parameter_model = types._AppendAgentEngineTaskEventRequestParameters(
+ name=name,
+ task_events=task_events,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AppendAgentEngineTaskEventRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:appendEvents".format_map(request_url_dict)
+ else:
+ path = "{name}:appendEvents"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AppendAgentEngineTaskEventResponse_from_vertex(
+ response_dict
+ )
+
+ return_value = types.AppendAgentEngineTaskEventResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTaskEventsConfigOrDict] = None,
+ ) -> types.ListAgentEngineTaskEventsResponse:
+ """
+ Lists Agent Engine task events.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to list events for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{a2a_task_id}`.
+ config (ListAgentEngineTaskEventsConfig):
+ Optional. Additional configurations for listing the Agent Engine tasks.
+
+ Returns:
+ ListAgentEngineTaskEventsResponse: The requested Agent Engine tasks.
+
+ """
+
+ parameter_model = types._ListAgentEngineTaskEventsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineTaskEventsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/events".format_map(request_url_dict)
+ else:
+ path = "{name}/events"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineTaskEventsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTaskEventsConfigOrDict] = None,
+ ) -> AsyncPager[types.TaskEvent]:
+ """Lists the A2A tasks of an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list tasks for.
+ config (List):
+ Optional. The configuration for the tasks to list.
+
+ Returns:
+ AsyncPager[TaskEvent]: An async pager of Task events.
+ """
+
+ return AsyncPager(
+ "taskEvents",
+ functools.partial(self._list, name=name),
+ await self._list(name=name, config=config),
+ config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/a2a_tasks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/a2a_tasks.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cb74c1d8e264b5c246f62a211002c465bf0cc67
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/a2a_tasks.py
@@ -0,0 +1,861 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import importlib
+import json
+import logging
+import typing
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import types
+
+if typing.TYPE_CHECKING:
+ from . import a2a_task_events as a2a_task_events_module
+
+ _ = a2a_task_events_module
+
+
+logger = logging.getLogger("agentplatform_genai.a2atasks")
+
+logger.setLevel(logging.INFO)
+
+
+def _CreateAgentEngineTaskConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["context_id"]) is not None:
+ setv(parent_object, ["contextId"], getv(from_object, ["context_id"]))
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(parent_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["status_details"]) is not None:
+ setv(parent_object, ["statusDetails"], getv(from_object, ["status_details"]))
+
+ if getv(from_object, ["output"]) is not None:
+ setv(parent_object, ["output"], getv(from_object, ["output"]))
+
+ return to_object
+
+
+def _CreateAgentEngineTaskRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["a2a_task_id"]) is not None:
+ setv(to_object, ["_query", "a2a_task_id"], getv(from_object, ["a2a_task_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _CreateAgentEngineTaskConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _DeleteAgentEngineTaskRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GetAgentEngineTaskRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ListAgentEngineTasksConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ if getv(from_object, ["order_by"]) is not None:
+ setv(parent_object, ["_query", "orderBy"], getv(from_object, ["order_by"]))
+
+ return to_object
+
+
+def _ListAgentEngineTasksRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineTasksConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+class A2aTasks(_api_module.BaseModule):
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineTaskConfigOrDict] = None,
+ ) -> None:
+ """
+ Deletes an agent engine task.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to delete. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{task_id}`.
+ config (DeleteAgentEngineTaskConfig):
+ Optional. Additional configurations for deleting the Agent Engine task.
+
+ Returns:
+ None
+
+ """
+
+ parameter_model = types._DeleteAgentEngineTaskRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineTaskRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ self._api_client.request("delete", path, request_dict, http_options)
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineTaskConfigOrDict] = None,
+ ) -> types.A2aTask:
+ """
+ Gets an agent engine task.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{task_id}`.
+ config (GetAgentEngineTaskConfig):
+ Optional. Additional configurations for getting the Agent Engine task.
+
+ Returns:
+ AgentEngineTask: The requested Agent Engine task.
+
+ """
+
+ parameter_model = types._GetAgentEngineTaskRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineTaskRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.A2aTask._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTasksConfigOrDict] = None,
+ ) -> types.ListAgentEngineTasksResponse:
+ """
+ Lists Agent Engine tasks.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to list tasks for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineTasksConfig):
+ Optional. Additional configurations for listing the Agent Engine tasks.
+
+ Returns:
+ ListAgentEngineTasksResponse: The requested Agent Engine tasks.
+
+ """
+
+ parameter_model = types._ListAgentEngineTasksRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineTasksRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/a2aTasks".format_map(request_url_dict)
+ else:
+ path = "{name}/a2aTasks"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineTasksResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def create(
+ self,
+ *,
+ name: str,
+ a2a_task_id: str,
+ config: Optional[types.CreateAgentEngineTaskConfigOrDict] = None,
+ ) -> types.A2aTask:
+ """
+ Creates a new task in the Agent Engine.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to create the task under. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ a2a_task_id (str): Required. The user ID of the task.
+ context_id (str): Required. The ID of the context to use for the task.
+ config (CreateAgentEngineTaskConfig):
+ Optional. Additional configurations for creating the Agent Engine task.
+
+ Returns:
+ A2aTask: The created Agent Engine task.
+
+ """
+
+ parameter_model = types._CreateAgentEngineTaskRequestParameters(
+ name=name,
+ a2a_task_id=a2a_task_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineTaskRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/a2aTasks".format_map(request_url_dict)
+ else:
+ path = "{name}/a2aTasks"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.A2aTask._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _events = None
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTasksConfigOrDict] = None,
+ ) -> Iterator[types.A2aTask]:
+ """Lists the A2A tasks of an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list tasks for.
+ config (List):
+ Optional. The configuration for the tasks to list.
+
+ Returns:
+ Iterable[A2aTask]: An iterable of A2A tasks.
+ """
+
+ return Pager(
+ "a2aTasks",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+ @property
+ def events(self) -> "a2a_task_events_module.A2aTaskEvents":
+ if self._events is None:
+ try:
+ # We need to lazy load the events module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._events = importlib.import_module(".a2a_task_events", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.a2a_tasks.events' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._events.A2aTaskEvents(self._api_client) # type: ignore[no-any-return]
+
+
+class AsyncA2aTasks(_api_module.BaseModule):
+
+ async def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineTaskConfigOrDict] = None,
+ ) -> None:
+ """
+ Deletes an agent engine task.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to delete. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{task_id}`.
+ config (DeleteAgentEngineTaskConfig):
+ Optional. Additional configurations for deleting the Agent Engine task.
+
+ Returns:
+ None
+
+ """
+
+ parameter_model = types._DeleteAgentEngineTaskRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineTaskRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ await self._api_client.async_request("delete", path, request_dict, http_options)
+
+ async def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineTaskConfigOrDict] = None,
+ ) -> types.A2aTask:
+ """
+ Gets an agent engine task.
+
+ Args:
+ name (str): Required. The name of the Agent Engine task to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/a2aTasks/{task_id}`.
+ config (GetAgentEngineTaskConfig):
+ Optional. Additional configurations for getting the Agent Engine task.
+
+ Returns:
+ AgentEngineTask: The requested Agent Engine task.
+
+ """
+
+ parameter_model = types._GetAgentEngineTaskRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineTaskRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.A2aTask._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTasksConfigOrDict] = None,
+ ) -> types.ListAgentEngineTasksResponse:
+ """
+ Lists Agent Engine tasks.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to list tasks for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineTasksConfig):
+ Optional. Additional configurations for listing the Agent Engine tasks.
+
+ Returns:
+ ListAgentEngineTasksResponse: The requested Agent Engine tasks.
+
+ """
+
+ parameter_model = types._ListAgentEngineTasksRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineTasksRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/a2aTasks".format_map(request_url_dict)
+ else:
+ path = "{name}/a2aTasks"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineTasksResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def create(
+ self,
+ *,
+ name: str,
+ a2a_task_id: str,
+ config: Optional[types.CreateAgentEngineTaskConfigOrDict] = None,
+ ) -> types.A2aTask:
+ """
+ Creates a new task in the Agent Engine.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to create the task under. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ a2a_task_id (str): Required. The user ID of the task.
+ context_id (str): Required. The ID of the context to use for the task.
+ config (CreateAgentEngineTaskConfig):
+ Optional. Additional configurations for creating the Agent Engine task.
+
+ Returns:
+ A2aTask: The created Agent Engine task.
+
+ """
+
+ parameter_model = types._CreateAgentEngineTaskRequestParameters(
+ name=name,
+ a2a_task_id=a2a_task_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineTaskRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/a2aTasks".format_map(request_url_dict)
+ else:
+ path = "{name}/a2aTasks"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.A2aTask._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _events = None
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineTasksConfigOrDict] = None,
+ ) -> AsyncPager[types.A2aTask]:
+ """Lists the A2A tasks of an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list tasks for.
+ config (List):
+ Optional. The configuration for the tasks to list.
+
+ Returns:
+ AsyncPager[A2aTask]: An async pager of A2A tasks.
+ """
+
+ return AsyncPager(
+ "a2aTasks",
+ functools.partial(self._list, name=name),
+ await self._list(name=name, config=config),
+ config,
+ )
+
+ @property
+ def events(self) -> "a2a_task_events_module.AsyncA2aTaskEvents":
+ if self._events is None:
+ try:
+ # We need to lazy load the events module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._events = importlib.import_module(".a2a_task_events", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.a2a_tasks.events' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._events.AsyncA2aTaskEvents(self._api_client) # type: ignore[no-any-return]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/agent_engines.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/agent_engines.py
new file mode 100644
index 0000000000000000000000000000000000000000..f160d7327b62b96bfbe035788a7222f9d7c882e4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/agent_engines.py
@@ -0,0 +1,4114 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import datetime
+import importlib
+import json
+import logging
+import typing
+from typing import Any, AsyncIterator, Iterator, Optional, Sequence, Tuple, Union
+from urllib.parse import urlencode
+import warnings
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai import types as genai_types
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import Pager
+
+from . import _agent_engines_utils
+from . import types
+
+if typing.TYPE_CHECKING:
+ from . import sessions as sessions_module
+ from . import memories as memories_module
+ from . import a2a_tasks as a2a_tasks_module
+ from . import runtimes as runtimes_module
+
+ _ = sessions_module
+ __ = memories_module
+ ___ = a2a_tasks_module
+ ____ = runtimes_module
+
+
+logger = logging.getLogger("agentplatform_genai.agentengines")
+
+logger.setLevel(logging.INFO)
+
+
+def _AgentEngineOperation_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["done"]) is not None:
+ setv(to_object, ["done"], getv(from_object, ["done"]))
+
+ if getv(from_object, ["error"]) is not None:
+ setv(to_object, ["error"], getv(from_object, ["error"]))
+
+ if getv(from_object, ["response"]) is not None:
+ setv(
+ to_object,
+ ["response"],
+ _ReasoningEngine_from_vertex(getv(from_object, ["response"]), to_object),
+ )
+
+ return to_object
+
+
+def _CancelQueryJobAgentEngineConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(parent_object, ["operationName"], getv(from_object, ["operation_name"]))
+
+ return to_object
+
+
+def _CancelQueryJobAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _CancelQueryJobAgentEngineConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _CheckQueryJobAgentEngineConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["retrieve_result"]) is not None:
+ setv(parent_object, ["retrieveResult"], getv(from_object, ["retrieve_result"]))
+
+ return to_object
+
+
+def _CheckQueryJobAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _CheckQueryJobAgentEngineConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _CheckQueryJobResult_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(parent_object, ["operationName"]) is not None:
+ setv(to_object, ["operation_name"], getv(parent_object, ["operationName"]))
+
+ if getv(parent_object, ["outputGcsUri"]) is not None:
+ setv(to_object, ["output_gcs_uri"], getv(parent_object, ["outputGcsUri"]))
+
+ if getv(parent_object, ["status"]) is not None:
+ setv(to_object, ["status"], getv(parent_object, ["status"]))
+
+ if getv(parent_object, ["result"]) is not None:
+ setv(to_object, ["result"], getv(parent_object, ["result"]))
+
+ return to_object
+
+
+def _CreateAgentEngineConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["spec"]) is not None:
+ setv(parent_object, ["spec"], getv(from_object, ["spec"]))
+
+ if getv(from_object, ["context_spec"]) is not None:
+ setv(
+ parent_object,
+ ["contextSpec"],
+ _ReasoningEngineContextSpec_to_vertex(
+ getv(from_object, ["context_spec"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["psc_interface_config"]) is not None:
+ setv(
+ parent_object,
+ ["pscInterfaceConfig"],
+ getv(from_object, ["psc_interface_config"]),
+ )
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(parent_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(parent_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["source_packages"]) is not None:
+ setv(parent_object, ["sourcePackages"], getv(from_object, ["source_packages"]))
+
+ if getv(from_object, ["entrypoint_module"]) is not None:
+ setv(
+ parent_object,
+ ["entrypointModule"],
+ getv(from_object, ["entrypoint_module"]),
+ )
+
+ if getv(from_object, ["entrypoint_object"]) is not None:
+ setv(
+ parent_object,
+ ["entrypointObject"],
+ getv(from_object, ["entrypoint_object"]),
+ )
+
+ if getv(from_object, ["requirements_file"]) is not None:
+ setv(
+ parent_object,
+ ["requirementsFile"],
+ getv(from_object, ["requirements_file"]),
+ )
+
+ if getv(from_object, ["agent_framework"]) is not None:
+ setv(parent_object, ["agentFramework"], getv(from_object, ["agent_framework"]))
+
+ if getv(from_object, ["python_version"]) is not None:
+ setv(parent_object, ["pythonVersion"], getv(from_object, ["python_version"]))
+
+ if getv(from_object, ["agent_gateway_config"]) is not None:
+ setv(
+ parent_object,
+ ["agentGatewayConfig"],
+ getv(from_object, ["agent_gateway_config"]),
+ )
+
+ return to_object
+
+
+def _CreateAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["config"]) is not None:
+ _CreateAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _DeleteAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["force"]) is not None:
+ setv(to_object, ["force"], getv(from_object, ["force"]))
+
+ return to_object
+
+
+def _GetAgentEngineOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ListAgentEngineConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _ListReasoningEnginesResponse_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["sdkHttpResponse"]) is not None:
+ setv(to_object, ["sdk_http_response"], getv(from_object, ["sdkHttpResponse"]))
+
+ if getv(from_object, ["nextPageToken"]) is not None:
+ setv(to_object, ["next_page_token"], getv(from_object, ["nextPageToken"]))
+
+ if getv(from_object, ["reasoningEngines"]) is not None:
+ setv(
+ to_object,
+ ["reasoning_engines"],
+ [
+ _ReasoningEngine_from_vertex(item, to_object)
+ for item in getv(from_object, ["reasoningEngines"])
+ ],
+ )
+
+ return to_object
+
+
+def _QueryAgentEngineConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["class_method"]) is not None:
+ setv(parent_object, ["classMethod"], getv(from_object, ["class_method"]))
+
+ if getv(from_object, ["input"]) is not None:
+ setv(parent_object, ["input"], getv(from_object, ["input"]))
+
+ if getv(from_object, ["include_all_fields"]) is not None:
+ setv(to_object, ["includeAllFields"], getv(from_object, ["include_all_fields"]))
+
+ return to_object
+
+
+def _QueryAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _QueryAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _ReasoningEngineContextSpecMemoryBankConfig_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["customizationConfigs"]) is not None:
+ setv(
+ to_object,
+ ["customization_configs"],
+ [item for item in getv(from_object, ["customizationConfigs"])],
+ )
+
+ if getv(from_object, ["disableMemoryRevisions"]) is not None:
+ setv(
+ to_object,
+ ["disable_memory_revisions"],
+ getv(from_object, ["disableMemoryRevisions"]),
+ )
+
+ if getv(from_object, ["generationConfig"]) is not None:
+ setv(to_object, ["generation_config"], getv(from_object, ["generationConfig"]))
+
+ if getv(from_object, ["similaritySearchConfig"]) is not None:
+ setv(
+ to_object,
+ ["similarity_search_config"],
+ getv(from_object, ["similaritySearchConfig"]),
+ )
+
+ if getv(from_object, ["ttlConfig"]) is not None:
+ setv(to_object, ["ttl_config"], getv(from_object, ["ttlConfig"]))
+
+ if getv(from_object, ["structuredMemoryConfigs"]) is not None:
+ setv(
+ to_object,
+ ["structured_memory_configs"],
+ [
+ _StructuredMemoryConfig_from_vertex(item, to_object)
+ for item in getv(from_object, ["structuredMemoryConfigs"])
+ ],
+ )
+
+ return to_object
+
+
+def _ReasoningEngineContextSpecMemoryBankConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["customization_configs"]) is not None:
+ setv(
+ to_object,
+ ["customizationConfigs"],
+ [item for item in getv(from_object, ["customization_configs"])],
+ )
+
+ if getv(from_object, ["disable_memory_revisions"]) is not None:
+ setv(
+ to_object,
+ ["disableMemoryRevisions"],
+ getv(from_object, ["disable_memory_revisions"]),
+ )
+
+ if getv(from_object, ["generation_config"]) is not None:
+ setv(to_object, ["generationConfig"], getv(from_object, ["generation_config"]))
+
+ if getv(from_object, ["similarity_search_config"]) is not None:
+ setv(
+ to_object,
+ ["similaritySearchConfig"],
+ getv(from_object, ["similarity_search_config"]),
+ )
+
+ if getv(from_object, ["ttl_config"]) is not None:
+ setv(to_object, ["ttlConfig"], getv(from_object, ["ttl_config"]))
+
+ if getv(from_object, ["structured_memory_configs"]) is not None:
+ setv(
+ to_object,
+ ["structuredMemoryConfigs"],
+ [
+ _StructuredMemoryConfig_to_vertex(item, to_object)
+ for item in getv(from_object, ["structured_memory_configs"])
+ ],
+ )
+
+ return to_object
+
+
+def _ReasoningEngineContextSpec_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["memoryBankConfig"]) is not None:
+ setv(
+ to_object,
+ ["memory_bank_config"],
+ _ReasoningEngineContextSpecMemoryBankConfig_from_vertex(
+ getv(from_object, ["memoryBankConfig"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _ReasoningEngineContextSpec_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["memory_bank_config"]) is not None:
+ setv(
+ to_object,
+ ["memoryBankConfig"],
+ _ReasoningEngineContextSpecMemoryBankConfig_to_vertex(
+ getv(from_object, ["memory_bank_config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _ReasoningEngine_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["encryptionSpec"]) is not None:
+ setv(to_object, ["encryption_spec"], getv(from_object, ["encryptionSpec"]))
+
+ if getv(from_object, ["contextSpec"]) is not None:
+ setv(
+ to_object,
+ ["context_spec"],
+ _ReasoningEngineContextSpec_from_vertex(
+ getv(from_object, ["contextSpec"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["createTime"]) is not None:
+ setv(to_object, ["create_time"], getv(from_object, ["createTime"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["displayName"]) is not None:
+ setv(to_object, ["display_name"], getv(from_object, ["displayName"]))
+
+ if getv(from_object, ["etag"]) is not None:
+ setv(to_object, ["etag"], getv(from_object, ["etag"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["spec"]) is not None:
+ setv(to_object, ["spec"], getv(from_object, ["spec"]))
+
+ if getv(from_object, ["updateTime"]) is not None:
+ setv(to_object, ["update_time"], getv(from_object, ["updateTime"]))
+
+ if getv(from_object, ["trafficConfig"]) is not None:
+ setv(to_object, ["traffic_config"], getv(from_object, ["trafficConfig"]))
+
+ return to_object
+
+
+def _RunQueryJobAgentEngineConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["input_gcs_uri"]) is not None:
+ setv(parent_object, ["inputGcsUri"], getv(from_object, ["input_gcs_uri"]))
+
+ if getv(from_object, ["output_gcs_uri"]) is not None:
+ setv(parent_object, ["outputGcsUri"], getv(from_object, ["output_gcs_uri"]))
+
+ return to_object
+
+
+def _RunQueryJobAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _RunQueryJobAgentEngineConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _StructuredMemoryConfig_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["schemaConfigs"]) is not None:
+ setv(
+ to_object,
+ ["schema_configs"],
+ [
+ _StructuredMemorySchemaConfig_from_vertex(item, to_object)
+ for item in getv(from_object, ["schemaConfigs"])
+ ],
+ )
+
+ if getv(from_object, ["scopeKeys"]) is not None:
+ setv(to_object, ["scope_keys"], getv(from_object, ["scopeKeys"]))
+
+ return to_object
+
+
+def _StructuredMemoryConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["schema_configs"]) is not None:
+ setv(
+ to_object,
+ ["schemaConfigs"],
+ [
+ _StructuredMemorySchemaConfig_to_vertex(item, to_object)
+ for item in getv(from_object, ["schema_configs"])
+ ],
+ )
+
+ if getv(from_object, ["scope_keys"]) is not None:
+ setv(to_object, ["scopeKeys"], getv(from_object, ["scope_keys"]))
+
+ return to_object
+
+
+def _StructuredMemorySchemaConfig_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["schema"]) is not None:
+ setv(to_object, ["memory_schema"], getv(from_object, ["schema"]))
+
+ if getv(from_object, ["id"]) is not None:
+ setv(to_object, ["id"], getv(from_object, ["id"]))
+
+ if getv(from_object, ["memoryType"]) is not None:
+ setv(to_object, ["memory_type"], getv(from_object, ["memoryType"]))
+
+ return to_object
+
+
+def _StructuredMemorySchemaConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["memory_schema"]) is not None:
+ setv(to_object, ["schema"], getv(from_object, ["memory_schema"]))
+
+ if getv(from_object, ["id"]) is not None:
+ setv(to_object, ["id"], getv(from_object, ["id"]))
+
+ if getv(from_object, ["memory_type"]) is not None:
+ setv(to_object, ["memoryType"], getv(from_object, ["memory_type"]))
+
+ return to_object
+
+
+def _UpdateAgentEngineConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["spec"]) is not None:
+ setv(parent_object, ["spec"], getv(from_object, ["spec"]))
+
+ if getv(from_object, ["context_spec"]) is not None:
+ setv(
+ parent_object,
+ ["contextSpec"],
+ _ReasoningEngineContextSpec_to_vertex(
+ getv(from_object, ["context_spec"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["psc_interface_config"]) is not None:
+ setv(
+ parent_object,
+ ["pscInterfaceConfig"],
+ getv(from_object, ["psc_interface_config"]),
+ )
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(parent_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(parent_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["source_packages"]) is not None:
+ setv(parent_object, ["sourcePackages"], getv(from_object, ["source_packages"]))
+
+ if getv(from_object, ["entrypoint_module"]) is not None:
+ setv(
+ parent_object,
+ ["entrypointModule"],
+ getv(from_object, ["entrypoint_module"]),
+ )
+
+ if getv(from_object, ["entrypoint_object"]) is not None:
+ setv(
+ parent_object,
+ ["entrypointObject"],
+ getv(from_object, ["entrypoint_object"]),
+ )
+
+ if getv(from_object, ["requirements_file"]) is not None:
+ setv(
+ parent_object,
+ ["requirementsFile"],
+ getv(from_object, ["requirements_file"]),
+ )
+
+ if getv(from_object, ["agent_framework"]) is not None:
+ setv(parent_object, ["agentFramework"], getv(from_object, ["agent_framework"]))
+
+ if getv(from_object, ["python_version"]) is not None:
+ setv(parent_object, ["pythonVersion"], getv(from_object, ["python_version"]))
+
+ if getv(from_object, ["agent_gateway_config"]) is not None:
+ setv(
+ parent_object,
+ ["agentGatewayConfig"],
+ getv(from_object, ["agent_gateway_config"]),
+ )
+
+ if getv(from_object, ["update_mask"]) is not None:
+ setv(
+ parent_object, ["_query", "updateMask"], getv(from_object, ["update_mask"])
+ )
+
+ if getv(from_object, ["traffic_config"]) is not None:
+ setv(parent_object, ["trafficConfig"], getv(from_object, ["traffic_config"]))
+
+ return to_object
+
+
+def _UpdateAgentEngineRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _UpdateAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+class AgentEngines(_api_module.BaseModule):
+
+ def cancel_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types.CancelQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.CancelQueryJobResult:
+ """
+ Cancels a long-running query job on an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The reasoning engine resource name.
+ config (CancelQueryJobAgentEngineConfigOrDict):
+ Optional. The configuration for the cancel_query_job.
+
+ """
+
+ parameter_model = types._CancelQueryJobAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CancelQueryJobAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:cancelAsyncQuery".format_map(request_url_dict)
+ else:
+ path = "{name}:cancelAsyncQuery"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.CancelQueryJobResult._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _check_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types.CheckQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.CheckQueryJobResult:
+ """
+ Query an Agent Engine asynchronously.
+ """
+
+ parameter_model = types._CheckQueryJobAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CheckQueryJobAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:checkQueryJob".format_map(request_url_dict)
+ else:
+ path = "{name}:checkQueryJob"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CheckQueryJobResult_from_vertex(response_dict)
+
+ return_value = types.CheckQueryJobResult._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _run_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types._RunQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.AgentEngineOperation:
+ """
+ Run a query job on an agent engine.
+ """
+
+ parameter_model = types._RunQueryJobAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RunQueryJobAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:asyncQuery".format_map(request_url_dict)
+ else:
+ path = "{name}:asyncQuery"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create(
+ self, *, config: Optional[types.CreateAgentEngineConfigOrDict] = None
+ ) -> types.AgentEngineOperation:
+ """
+ Creates a new Agent Engine.
+ """
+
+ parameter_model = types._CreateAgentEngineRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "reasoningEngines".format_map(request_url_dict)
+ else:
+ path = "reasoningEngines"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete(
+ self,
+ *,
+ name: str,
+ force: Optional[bool] = None,
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineOperation:
+ """
+ Delete an Agent Engine resource.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
+ or `reasoningEngines/{resource_id}`.
+ force (bool):
+ Optional. If set to True, child resources will also be deleted.
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
+ the Agent Engine has undeleted child resources. Defaults to False.
+ config (DeleteAgentEngineConfig):
+ Optional. Additional configurations for deleting the Agent Engine.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineRequestParameters(
+ name=name,
+ force=force,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get(
+ self, *, name: str, config: Optional[types.GetAgentEngineConfigOrDict] = None
+ ) -> types.ReasoningEngine:
+ """
+ Get an Agent Engine instance.
+ """
+
+ parameter_model = types._GetAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _ReasoningEngine_from_vertex(response_dict)
+
+ return_value = types.ReasoningEngine._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
+ ) -> types.ListReasoningEnginesResponse:
+ """
+ Lists Agent Engines.
+ """
+
+ parameter_model = types._ListAgentEngineRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "reasoningEngines".format_map(request_url_dict)
+ else:
+ path = "reasoningEngines"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _ListReasoningEnginesResponse_from_vertex(response_dict)
+
+ return_value = types.ListReasoningEnginesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_agent_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineOperation:
+ parameter_model = types._GetAgentEngineOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineOperationParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _query(
+ self, *, name: str, config: Optional[types.QueryAgentEngineConfigOrDict] = None
+ ) -> types.QueryReasoningEngineResponse:
+ """
+ Query an Agent Engine.
+ """
+
+ parameter_model = types._QueryAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:query".format_map(request_url_dict)
+ else:
+ path = "{name}:query"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.QueryReasoningEngineResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _update(
+ self, *, name: str, config: Optional[types.UpdateAgentEngineConfigOrDict] = None
+ ) -> types.AgentEngineOperation:
+ """
+ Updates an Agent Engine.
+ """
+
+ parameter_model = types._UpdateAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("patch", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _a2a_tasks = None
+ _memories = None
+ _sandboxes = None
+ _sessions = None
+ _runtimes = None
+
+ @property
+ def runtimes(self) -> "runtimes_module.Runtimes":
+ if self._runtimes is None:
+ try:
+ # We need to lazy load the runtimes module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._runtimes = importlib.import_module(".runtimes", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.runtimes' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._runtimes.Runtimes(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def a2a_tasks(self) -> "a2a_tasks_module.A2aTasks":
+ if self._a2a_tasks is None:
+ try:
+ # We need to lazy load the a2a_tasks module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._a2a_tasks = importlib.import_module(".a2a_tasks", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.a2a_tasks' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._a2a_tasks.A2aTasks(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def memories(self) -> "memories_module.Memories":
+ if self._memories is None:
+ try:
+ # We need to lazy load the memories module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._memories = importlib.import_module(".memories", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.memories' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._memories.Memories(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def sandboxes(self) -> Any:
+ if self._sandboxes is None:
+ try:
+ # We need to lazy load the sandboxes module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._sandboxes = importlib.import_module(".sandboxes", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The agent_engines.sandboxes module requires additional packages. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._sandboxes.Sandboxes(self._api_client)
+
+ @property
+ def sessions(self) -> "sessions_module.Sessions":
+ if self._sessions is None:
+ try:
+ # We need to lazy load the sessions module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._sessions = importlib.import_module(".sessions", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The agent_engines.sessions module requires additional packages. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._sessions.Sessions(self._api_client) # type: ignore[no-any-return]
+
+ def _list_pager(
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
+ ) -> Pager[types.ReasoningEngine]:
+ return Pager(
+ "reasoning_engines",
+ self._list,
+ self._list(config=config),
+ config,
+ )
+
+ def check_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types.CheckQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.CheckQueryJobResult:
+ """Checks a query job on an agent engine and optionally returns the results.
+
+ Args:
+ name (str):
+ Required. A fully-qualified resource name or ID.
+ config (CheckQueryJobAgentEngineConfigOrDict):
+ Optional. The configuration for the check_query_job. If not provided,
+ the default configuration will be used. This can be used to specify
+ the following fields:
+ - retrieve_result: Whether to retrieve the results of the query job.
+ """
+ from google.cloud import storage # type: ignore[attr-defined]
+ import json
+
+ if config is None:
+ config = types.CheckQueryJobAgentEngineConfig()
+ elif isinstance(config, dict):
+ config = types.CheckQueryJobAgentEngineConfig(**config)
+
+ raw_response = self._api_client.request("get", name, {})
+ if hasattr(raw_response, "body"):
+ operation = (
+ json.loads(raw_response.body)
+ if isinstance(raw_response.body, str)
+ else raw_response.body
+ )
+ else:
+ operation = raw_response
+
+ status = "RUNNING"
+ if isinstance(operation, dict):
+ if operation.get("done"):
+ status = "FAILED" if operation.get("error") else "SUCCESS"
+
+ response_dict = operation.get("response", {})
+ output_gcs_uri = response_dict.get("outputGcsUri") or response_dict.get(
+ "output_gcs_uri"
+ )
+ error = operation.get("error")
+ else:
+ if getattr(operation, "done", False):
+ status = "FAILED" if getattr(operation, "error", None) else "SUCCESS"
+
+ response_obj = getattr(operation, "response", None)
+ if isinstance(response_obj, dict):
+ output_gcs_uri = response_obj.get("outputGcsUri") or response_obj.get(
+ "output_gcs_uri"
+ )
+ else:
+ output_gcs_uri = (
+ getattr(
+ response_obj,
+ "output_gcs_uri",
+ getattr(response_obj, "outputGcsUri", None),
+ )
+ if response_obj
+ else None
+ )
+ error = getattr(operation, "error", None)
+
+ result_str = None
+ if status == "SUCCESS" and config.retrieve_result and output_gcs_uri:
+ storage_client = storage.Client(
+ project=self._api_client.project,
+ credentials=self._api_client._credentials,
+ )
+ bucket_name = output_gcs_uri.replace("gs://", "").split("/")[0]
+ blob_name = output_gcs_uri.replace(f"gs://{bucket_name}/", "")
+ bucket = storage_client.bucket(bucket_name)
+ blob = bucket.blob(blob_name)
+ if blob.exists():
+ result_str = blob.download_as_string().decode("utf-8")
+ else:
+ raise ValueError(
+ f"Failed to retrieve blob results for {output_gcs_uri}"
+ )
+
+ elif status == "FAILED" and error:
+ result_str = str(error)
+
+ return types.CheckQueryJobResult(
+ operation_name=name,
+ output_gcs_uri=output_gcs_uri,
+ status=status,
+ result=result_str,
+ )
+
+ def _is_lightweight_creation(
+ self, agent: Any, config: types.AgentEngineConfig
+ ) -> bool:
+ if (
+ agent
+ or config.source_packages
+ or config.developer_connect_source
+ or config.agent_config_source
+ or config.container_spec
+ ):
+ return False
+ return True
+
+ def run_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types.RunQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.RunQueryJobResult:
+ """Launches a long-running query job on an Agent Engine
+
+ Args:
+ name (str):
+ Required. A fully-qualified resource name or ID.
+ config (RunQueryJobAgentEngineConfigOrDict):
+ Optional. The configuration for the async query. If not provided,
+ the default configuration will be used. This can be used to specify
+ the following fields:
+ - query: The query to send to the agent engine.
+ - output_gcs_uri: The GCS URI to use for the output.
+ """
+ from google.cloud import storage # type: ignore[attr-defined]
+ from google.api_core import exceptions
+ import uuid
+
+ if config is None:
+ config = types.RunQueryJobAgentEngineConfig()
+ elif isinstance(config, dict):
+ config = types.RunQueryJobAgentEngineConfig(**config)
+
+ if not config.query:
+ raise ValueError("`query` is required in the config object.")
+ if not config.output_gcs_uri:
+ raise ValueError("`output_gcs_uri` is required in the config object.")
+
+ output_gcs_uri = config.output_gcs_uri
+ is_file = False
+ last_part = ""
+ if not output_gcs_uri.endswith("/"):
+ last_part = output_gcs_uri.split("/")[-1]
+ if "." in last_part:
+ is_file = True
+
+ if is_file:
+ path_parts = output_gcs_uri.split("/")
+ file_name = path_parts[-1]
+ base_uri = "/".join(path_parts[:-1])
+ name_parts = file_name.rsplit(".", 1)
+ if len(name_parts) == 2:
+ name_part, ext = name_parts[0], "." + name_parts[1]
+ else:
+ name_part = name_parts[0]
+ ext = ""
+ input_gcs_uri = f"{base_uri}/{name_part}_input{ext}"
+ else:
+ job_uuid = uuid.uuid4().hex
+ gcs_path = output_gcs_uri.rstrip("/")
+ input_gcs_uri = f"{gcs_path}/{job_uuid}_input.json"
+ output_gcs_uri = f"{gcs_path}/{job_uuid}_output.json"
+
+ storage_client = storage.Client(
+ project=self._api_client.project, credentials=self._api_client._credentials
+ )
+
+ # Handle creating the bucket if it does not exist
+ bucket_name = config.output_gcs_uri.replace("gs://", "").split("/")[0]
+ bucket = storage_client.bucket(bucket_name)
+
+ try:
+ bucket_exists = bucket.exists()
+ except exceptions.Forbidden as e:
+ raise ValueError(
+ f"Permission denied to check existence of bucket '{bucket_name}'. "
+ "The service account may lack 'storage.buckets.get' permission."
+ ) from e
+
+ if not bucket_exists:
+ try:
+ bucket.create()
+ except exceptions.Forbidden as e:
+ raise ValueError(
+ f"Permission denied to create bucket '{bucket_name}'. "
+ "The service account may lack 'storage.buckets.create' permission."
+ ) from e
+
+ input_blob_name = input_gcs_uri.replace(f"gs://{bucket_name}/", "")
+ blob = bucket.blob(input_blob_name)
+ blob.upload_from_string(config.query)
+
+ new_config = types._RunQueryJobAgentEngineConfig(
+ input_gcs_uri=input_gcs_uri,
+ output_gcs_uri=output_gcs_uri,
+ )
+
+ # Proceed with sending the async query via the auto-generated method
+ operation = self._run_query_job(name=name, config=new_config)
+
+ return types.RunQueryJobResult(
+ job_name=operation.name,
+ input_gcs_uri=input_gcs_uri,
+ output_gcs_uri=output_gcs_uri,
+ )
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineConfigOrDict] = None,
+ ) -> types.AgentEngine:
+ """Gets an agent engine.
+
+ Args:
+ name (str):
+ Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456" or
+ a shortened name such as "reasoningEngines/456".
+ """
+ api_resource = self._get(name=name, config=config)
+ agent_engine = types.AgentEngine(
+ api_client=self,
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
+ api_resource=api_resource,
+ )
+ if api_resource.spec:
+ self._register_api_methods(agent_engine=agent_engine)
+ return agent_engine
+
+ def delete(
+ self,
+ *,
+ name: str,
+ force: Optional[bool] = None,
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineOperation:
+ """
+ Delete an Agent Engine resource.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
+ or `reasoningEngines/{resource_id}`.
+ force (bool):
+ Optional. If set to True, child resources will also be deleted.
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
+ the Agent Engine has undeleted child resources. Defaults to False.
+ config (DeleteAgentEngineConfig):
+ Optional. Additional configurations for deleting the Agent Engine.
+
+ """
+ logger.info(f"Deleting AgentEngine resource: {name}")
+ operation = self._delete(name=name, force=force, config=config)
+ logger.info(f"Started AgentEngine delete operation: {operation.name}")
+ return operation
+
+ def create(
+ self,
+ *,
+ agent_engine: Any = None,
+ agent: Any = None,
+ config: Optional[types.AgentEngineConfigOrDict] = None,
+ ) -> types.AgentEngine:
+ """Creates an agent engine.
+
+ The Agent Engine will be an instance of the `agent_engine` that
+ was passed in, running remotely on Vertex AI.
+
+ Sample ``src_dir`` contents (e.g. ``./user_src_dir``):
+
+ .. code-block:: python
+
+ user_src_dir/
+ |-- main.py
+ |-- requirements.txt
+ |-- user_code/
+ | |-- utils.py
+ | |-- ...
+ |-- ...
+
+ To build an Agent Engine with the above files, run:
+
+ .. code-block:: python
+
+ client = agentplatform.Client(
+ project="your-project",
+ location="us-central1",
+ )
+ remote_agent = client.agent_engines.create(
+ agent=local_agent,
+ config=dict(
+ requirements=[
+ # I.e. the PyPI dependencies listed in requirements.txt
+ "google-cloud-aiplatform[agent_engines,adk]",
+ ...
+ ],
+ extra_packages=[
+ "./user_src_dir/main.py", # a single file
+ "./user_src_dir/user_code", # a directory
+ ...
+ ],
+ ),
+ )
+
+ Args:
+ agent (Any):
+ Optional. The Agent to be created. If not specified, this will
+ correspond to a lightweight instance that cannot be queried
+ (but can be updated to future instances that can be queried).
+ agent_engine (Any):
+ Optional. This is deprecated. Please use `agent` instead.
+ config (AgentEngineConfig):
+ Optional. The configurations to use for creating the Agent Engine.
+
+ Returns:
+ AgentEngine: The created Agent Engine instance.
+
+ Raises:
+ ValueError: If the `project` was not set using `client.Client`.
+ ValueError: If the `location` was not set using `client.Client`.
+ ValueError: If `config.staging_bucket` was not set when `agent`
+ is specified.
+ ValueError: If `config.staging_bucket` does not start with "gs://".
+ ValueError: If `config.extra_packages` is specified but `agent`
+ is None.
+ ValueError: If `config.requirements` is specified but `agent` is None.
+ ValueError: If `config.env_vars` has a dictionary entry that does not
+ correspond to an environment variable value or a SecretRef.
+ TypeError: If `config.env_vars` is not a dictionary.
+ FileNotFoundError: If `config.extra_packages` includes a file or
+ directory that does not exist.
+ IOError: If ``config.requirements` is a string that corresponds to a
+ nonexistent file.
+ """
+ if config is None:
+ config = {}
+ if isinstance(config, dict):
+ config = types.AgentEngineConfig.model_validate(config)
+ elif not isinstance(config, types.AgentEngineConfig):
+ raise TypeError(
+ f"config must be a dict or AgentEngineConfig, but got {type(config)}."
+ )
+ context_spec = config.context_spec
+ if context_spec is not None:
+ # Conversion to a dict for _create_config
+ context_spec = json.loads(context_spec.model_dump_json())
+ developer_connect_source = config.developer_connect_source
+ if developer_connect_source is not None:
+ developer_connect_source = json.loads(
+ developer_connect_source.model_dump_json()
+ )
+ agent_config_source = config.agent_config_source
+ if agent_config_source is not None:
+ agent_config_source = json.loads(agent_config_source.model_dump_json())
+ keep_alive_probe = config.keep_alive_probe
+ if keep_alive_probe is not None:
+ keep_alive_probe = json.loads(
+ keep_alive_probe.model_dump_json(exclude_none=True)
+ )
+ if agent and agent_engine:
+ raise ValueError("Please specify only one of `agent` or `agent_engine`.")
+ elif agent_engine:
+ raise DeprecationWarning(
+ "The `agent_engine` argument is deprecated. Please use `agent` instead."
+ )
+ agent = agent or agent_engine
+ api_config = self._create_config(
+ mode="create",
+ agent=agent,
+ identity_type=config.identity_type,
+ staging_bucket=config.staging_bucket,
+ requirements=config.requirements,
+ display_name=config.display_name,
+ description=config.description,
+ gcs_dir_name=config.gcs_dir_name,
+ extra_packages=config.extra_packages,
+ env_vars=config.env_vars,
+ service_account=config.service_account,
+ context_spec=context_spec,
+ psc_interface_config=config.psc_interface_config,
+ agent_gateway_config=config.agent_gateway_config,
+ min_instances=config.min_instances,
+ max_instances=config.max_instances,
+ resource_limits=config.resource_limits,
+ container_concurrency=config.container_concurrency,
+ encryption_spec=config.encryption_spec,
+ agent_server_mode=config.agent_server_mode,
+ labels=config.labels,
+ class_methods=config.class_methods,
+ source_packages=config.source_packages,
+ developer_connect_source=developer_connect_source,
+ entrypoint_module=config.entrypoint_module,
+ entrypoint_object=config.entrypoint_object,
+ requirements_file=config.requirements_file,
+ agent_framework=config.agent_framework,
+ python_version=config.python_version,
+ build_options=config.build_options,
+ image_spec=config.image_spec,
+ agent_config_source=agent_config_source,
+ container_spec=config.container_spec,
+ keep_alive_probe=keep_alive_probe,
+ )
+ operation = self._create(config=api_config)
+ reasoning_engine_id = _agent_engines_utils._get_reasoning_engine_id(
+ operation_name=operation.name
+ )
+ logger.info(
+ "View progress and logs at https://console.cloud.google.com/logs/query?"
+ f"project={self._api_client.project}"
+ "&query=resource.type%3D%22aiplatform.googleapis.com%2FReasoningEngine%22%0A"
+ f"resource.labels.reasoning_engine_id%3D%22{reasoning_engine_id}%22."
+ )
+ if not self._is_lightweight_creation(agent, config):
+ poll_interval_seconds = 10
+ else:
+ poll_interval_seconds = 1 # Lightweight agent engine resource creation.
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_agent_operation,
+ poll_interval_seconds=poll_interval_seconds,
+ )
+
+ agent_engine = types.AgentEngine(
+ api_client=self,
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
+ api_resource=operation.response,
+ )
+ if agent_engine.api_resource:
+ logger.info("Agent Engine created. To use it in another session:")
+ logger.info(
+ f"agent_engine=client.agent_engines.get(name='{agent_engine.api_resource.name}')"
+ )
+ elif operation.error:
+ raise RuntimeError(f"Failed to create Agent Engine: {operation.error}")
+ else:
+ logger.warning("The operation returned an empty response.")
+ if not self._is_lightweight_creation(agent, config):
+ # If the user did not provide an agent_engine (e.g. lightweight
+ # provisioning), it will not have any API methods registered.
+ agent_engine = self._register_api_methods(agent_engine=agent_engine)
+ return agent_engine # type: ignore[no-any-return]
+
+ def _set_source_code_spec(
+ self,
+ *,
+ spec: types.ReasoningEngineSpecDict,
+ update_masks: list[str],
+ source_packages: Optional[Sequence[str]] = None,
+ developer_connect_source: Optional[
+ types.ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
+ ] = None,
+ class_methods: Optional[Sequence[dict[str, Any]]] = None,
+ entrypoint_module: Optional[str] = None,
+ entrypoint_object: Optional[str] = None,
+ requirements_file: Optional[str] = None,
+ sys_version: str,
+ build_options: Optional[dict[str, list[str]]] = None,
+ image_spec: Optional[
+ types.ReasoningEngineSpecSourceCodeSpecImageSpecDict
+ ] = None,
+ agent_config_source: Optional[
+ types.ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict
+ ] = None,
+ ) -> None:
+ """Sets source_code_spec for agent engine inside the `spec`."""
+ source_code_spec = types.ReasoningEngineSpecSourceCodeSpecDict()
+ if source_packages and not agent_config_source:
+ source_packages = _agent_engines_utils._validate_packages_or_raise(
+ packages=source_packages,
+ build_options=build_options,
+ )
+ update_masks.append("spec.source_code_spec.inline_source.source_archive")
+ source_code_spec["inline_source"] = { # type: ignore[typeddict-item]
+ "source_archive": _agent_engines_utils._create_base64_encoded_tarball(
+ source_packages=source_packages
+ )
+ }
+ elif developer_connect_source:
+ update_masks.append("spec.source_code_spec.developer_connect_source")
+ source_code_spec["developer_connect_source"] = {
+ "config": developer_connect_source
+ }
+ elif not agent_config_source:
+ raise ValueError(
+ "Please specify one of `source_packages`, `developer_connect_source`, "
+ "or `agent_config_source`."
+ )
+ if class_methods is not None:
+ update_masks.append("spec.class_methods")
+ class_methods_spec_list = (
+ _agent_engines_utils._class_methods_to_class_methods_spec(
+ class_methods=class_methods
+ )
+ )
+ spec["class_methods"] = [
+ _agent_engines_utils._to_dict(class_method_spec)
+ for class_method_spec in class_methods_spec_list
+ ]
+ elif image_spec is None:
+ raise ValueError(
+ "`class_methods` must be specified if `source_packages`, "
+ "`developer_connect_source`, or `agent_config_source` is "
+ "specified without a Dockerfile or `image_spec`."
+ )
+ if image_spec is not None:
+ if entrypoint_module or entrypoint_object or requirements_file:
+ raise ValueError(
+ "`image_spec` cannot be specified alongside `entrypoint_module`, "
+ "`entrypoint_object`, or `requirements_file`, as they are "
+ "mutually exclusive."
+ )
+ if agent_config_source:
+ raise ValueError(
+ "`image_spec` cannot be specified alongside `agent_config_source`, "
+ "as they are mutually exclusive."
+ )
+ update_masks.append("spec.source_code_spec.image_spec")
+ source_code_spec["image_spec"] = image_spec
+ spec["source_code_spec"] = source_code_spec
+ return
+
+ update_masks.append("spec.source_code_spec.python_spec.version")
+ python_spec: types.ReasoningEngineSpecSourceCodeSpecPythonSpecDict = {
+ "version": sys_version,
+ }
+ if agent_config_source is not None:
+ if entrypoint_module or entrypoint_object:
+ logger.warning(
+ "`entrypoint_module` and `entrypoint_object` are ignored when "
+ "`agent_config_source` is specified, as they are pre-defined."
+ )
+ if source_packages:
+ source_packages = _agent_engines_utils._validate_packages_or_raise(
+ packages=source_packages,
+ build_options=build_options,
+ )
+ update_masks.append(
+ "spec.source_code_spec.agent_config_source.inline_source.source_archive"
+ )
+ agent_config_source["inline_source"] = { # type: ignore[typeddict-item]
+ "source_archive": _agent_engines_utils._create_base64_encoded_tarball(
+ source_packages=source_packages
+ )
+ }
+ update_masks.append("spec.source_code_spec.agent_config_source")
+ source_code_spec["agent_config_source"] = agent_config_source
+
+ if requirements_file is not None:
+ update_masks.append(
+ "spec.source_code_spec.python_spec.requirements_file"
+ )
+ python_spec["requirements_file"] = requirements_file
+ source_code_spec["python_spec"] = python_spec
+
+ spec["source_code_spec"] = source_code_spec
+ return
+
+ if not entrypoint_module:
+ raise ValueError(
+ "`entrypoint_module` must be specified if `source_packages` or `developer_connect_source` is specified."
+ )
+ update_masks.append("spec.source_code_spec.python_spec.entrypoint_module")
+ python_spec["entrypoint_module"] = entrypoint_module
+ if not entrypoint_object:
+ raise ValueError(
+ "`entrypoint_object` must be specified if `source_packages` or `developer_connect_source` is specified."
+ )
+ update_masks.append("spec.source_code_spec.python_spec.entrypoint_object")
+ python_spec["entrypoint_object"] = entrypoint_object
+ if requirements_file is not None:
+ update_masks.append("spec.source_code_spec.python_spec.requirements_file")
+ python_spec["requirements_file"] = requirements_file
+ source_code_spec["python_spec"] = python_spec
+ spec["source_code_spec"] = source_code_spec
+
+ def _set_package_spec(
+ self,
+ *,
+ spec: types.ReasoningEngineSpecDict,
+ update_masks: list[str],
+ agent: Any,
+ staging_bucket: Optional[str] = None,
+ requirements: Optional[Union[str, Sequence[str]]] = None,
+ gcs_dir_name: Optional[str] = None,
+ extra_packages: Optional[Sequence[str]] = None,
+ class_methods: Optional[Sequence[dict[str, Any]]] = None,
+ sys_version: str,
+ build_options: Optional[dict[str, list[str]]] = None,
+ ) -> None:
+ """Sets package spec for agent engine."""
+ project = self._api_client.project
+ if project is None:
+ raise ValueError("project must be set using `agentplatform.Client`.")
+ location = self._api_client.location
+ if location is None:
+ raise ValueError("location must be set using `agentplatform.Client`.")
+ gcs_dir_name = gcs_dir_name or _agent_engines_utils._DEFAULT_GCS_DIR_NAME
+ staging_bucket = _agent_engines_utils._validate_staging_bucket_or_raise(
+ staging_bucket=staging_bucket,
+ )
+ requirements = _agent_engines_utils._validate_requirements_or_raise(
+ agent=agent,
+ requirements=requirements,
+ )
+ extra_packages = _agent_engines_utils._validate_packages_or_raise(
+ packages=extra_packages,
+ build_options=build_options,
+ )
+ # Prepares the Agent Engine for creation/update in Vertex AI. This
+ # involves packaging and uploading the artifacts for agent_engine,
+ # requirements and extra_packages to `staging_bucket/gcs_dir_name`.
+ _agent_engines_utils._prepare(
+ agent=agent,
+ requirements=requirements,
+ project=project,
+ location=location,
+ staging_bucket=staging_bucket,
+ gcs_dir_name=gcs_dir_name,
+ extra_packages=extra_packages,
+ credentials=self._api_client._credentials,
+ )
+ # Update the package spec.
+ update_masks.append("spec.package_spec.pickle_object_gcs_uri")
+ package_spec: types.ReasoningEngineSpecPackageSpecDict = {
+ "python_version": sys_version,
+ "pickle_object_gcs_uri": "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _agent_engines_utils._BLOB_FILENAME,
+ ),
+ }
+ if extra_packages:
+ update_masks.append("spec.package_spec.dependency_files_gcs_uri")
+ package_spec["dependency_files_gcs_uri"] = "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _agent_engines_utils._EXTRA_PACKAGES_FILE,
+ )
+ if requirements:
+ update_masks.append("spec.package_spec.requirements_gcs_uri")
+ package_spec["requirements_gcs_uri"] = "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _agent_engines_utils._REQUIREMENTS_FILE,
+ )
+ spec["package_spec"] = package_spec
+
+ update_masks.append("spec.class_methods")
+ if class_methods is not None:
+ class_methods_spec_list = (
+ _agent_engines_utils._class_methods_to_class_methods_spec(
+ class_methods=class_methods
+ )
+ )
+ else:
+ class_methods_spec_list = (
+ _agent_engines_utils._generate_class_methods_spec_or_raise(
+ agent=agent,
+ operations=_agent_engines_utils._get_registered_operations(
+ agent=agent
+ ),
+ )
+ )
+ spec["class_methods"] = [
+ _agent_engines_utils._to_dict(class_method_spec)
+ for class_method_spec in class_methods_spec_list
+ ]
+
+ def _create_config(
+ self,
+ *,
+ mode: str,
+ agent: Any = None,
+ identity_type: Optional[types.IdentityType] = None,
+ staging_bucket: Optional[str] = None,
+ requirements: Optional[Union[str, Sequence[str]]] = None,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ gcs_dir_name: Optional[str] = None,
+ extra_packages: Optional[Sequence[str]] = None,
+ env_vars: Optional[dict[str, Union[str, Any]]] = None,
+ service_account: Optional[str] = None,
+ context_spec: Optional[types.ReasoningEngineContextSpecDict] = None,
+ psc_interface_config: Optional[types.PscInterfaceConfigDict] = None,
+ agent_gateway_config: Optional[
+ types.ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
+ ] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecDict] = None,
+ labels: Optional[dict[str, str]] = None,
+ agent_server_mode: Optional[types.AgentServerMode] = None,
+ class_methods: Optional[Sequence[dict[str, Any]]] = None,
+ source_packages: Optional[Sequence[str]] = None,
+ developer_connect_source: Optional[
+ types.ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
+ ] = None,
+ entrypoint_module: Optional[str] = None,
+ entrypoint_object: Optional[str] = None,
+ requirements_file: Optional[str] = None,
+ agent_framework: Optional[str] = None,
+ python_version: Optional[str] = None,
+ build_options: Optional[dict[str, list[str]]] = None,
+ image_spec: Optional[
+ types.ReasoningEngineSpecSourceCodeSpecImageSpecDict
+ ] = None,
+ agent_config_source: Optional[
+ types.ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict
+ ] = None,
+ container_spec: Optional[types.ReasoningEngineSpecContainerSpecDict] = None,
+ keep_alive_probe: Optional[dict[str, Any]] = None,
+ traffic_config: Optional[types.ReasoningEngineTrafficConfigDict] = None,
+ ) -> types.UpdateAgentEngineConfigDict:
+ import sys
+
+ config: types.UpdateAgentEngineConfigDict = {}
+ update_masks = []
+ if mode not in ["create", "update"]:
+ raise ValueError(f"Unsupported mode: {mode}")
+ if agent is None:
+ if requirements is not None:
+ raise ValueError("requirements must be None if agent is None.")
+ if extra_packages is not None:
+ raise ValueError("extra_packages must be None if agent is None.")
+ if display_name is not None:
+ update_masks.append("display_name")
+ config["display_name"] = display_name
+ if description is not None:
+ update_masks.append("description")
+ config["description"] = description
+ if context_spec is not None:
+ update_masks.append("context_spec")
+ config["context_spec"] = context_spec
+ if encryption_spec is not None:
+ update_masks.append("encryption_spec")
+ config["encryption_spec"] = encryption_spec
+ if labels is not None:
+ update_masks.append("labels")
+ config["labels"] = labels
+ if traffic_config is not None:
+ update_masks.append("traffic_config")
+ config["traffic_config"] = traffic_config
+
+ if agent_framework == "google-adk":
+ env_vars = _agent_engines_utils._add_telemetry_enablement_env(env_vars)
+
+ if python_version:
+ sys_version = python_version
+ else:
+ sys_version = f"{sys.version_info.major}.{sys.version_info.minor}"
+
+ if agent:
+ if source_packages:
+ raise ValueError(
+ "If you have provided `source_packages` in `config`, please "
+ "do not specify `agent` in `agent_engines.create()` or "
+ "`agent_engines.update()`."
+ )
+ if developer_connect_source:
+ raise ValueError(
+ "If you have provided `developer_connect_source` in `config`, please "
+ "do not specify `agent` in `agent_engines.create()` or "
+ "`agent_engines.update()`."
+ )
+ elif source_packages and developer_connect_source:
+ raise ValueError(
+ "Please specify only one of `source_packages` or `developer_connect_source` in `config`."
+ )
+
+ if container_spec:
+ if agent:
+ raise ValueError(
+ "If you have provided `container_spec` in `config`, please "
+ "do not specify `agent` in `agent_engines.create()` or "
+ "`agent_engines.update()`."
+ )
+ if source_packages or developer_connect_source:
+ raise ValueError(
+ "If you have provided `container_spec` in `config`, please "
+ "do not specify `source_packages` or `developer_connect_source` in `config`."
+ )
+
+ agent_engine_spec: Any = None
+ if agent:
+ agent_engine_spec = {}
+ agent = _agent_engines_utils._validate_agent_or_raise(agent=agent)
+ if _agent_engines_utils._is_adk_agent(agent):
+ env_vars = _agent_engines_utils._add_telemetry_enablement_env(env_vars)
+ self._set_package_spec(
+ spec=agent_engine_spec,
+ update_masks=update_masks,
+ agent=agent,
+ staging_bucket=staging_bucket,
+ requirements=requirements,
+ gcs_dir_name=gcs_dir_name,
+ extra_packages=extra_packages,
+ class_methods=class_methods,
+ sys_version=sys_version,
+ build_options=build_options,
+ )
+ elif (
+ source_packages
+ or developer_connect_source
+ or image_spec
+ or agent_config_source
+ ):
+ agent_engine_spec = {}
+ self._set_source_code_spec(
+ spec=agent_engine_spec,
+ update_masks=update_masks,
+ source_packages=source_packages,
+ developer_connect_source=developer_connect_source,
+ class_methods=class_methods,
+ entrypoint_module=entrypoint_module,
+ entrypoint_object=entrypoint_object,
+ requirements_file=requirements_file,
+ sys_version=sys_version,
+ build_options=build_options,
+ image_spec=image_spec,
+ agent_config_source=agent_config_source,
+ )
+ elif container_spec:
+ agent_engine_spec = {}
+ if class_methods is not None:
+ update_masks.append("spec.class_methods")
+ class_methods_spec_list = (
+ _agent_engines_utils._class_methods_to_class_methods_spec(
+ class_methods=class_methods
+ )
+ )
+ agent_engine_spec["class_methods"] = [
+ _agent_engines_utils._to_dict(class_method_spec)
+ for class_method_spec in class_methods_spec_list
+ ]
+ update_masks.append("spec.container_spec")
+ agent_engine_spec["container_spec"] = container_spec
+
+ is_deployment_spec_updated = (
+ env_vars is not None
+ or psc_interface_config is not None
+ or agent_gateway_config is not None
+ or min_instances is not None
+ or max_instances is not None
+ or resource_limits is not None
+ or container_concurrency is not None
+ or keep_alive_probe is not None
+ )
+ if agent_engine_spec is None and is_deployment_spec_updated:
+ raise ValueError(
+ "To update `env_vars`, `psc_interface_config`, `min_instances`, "
+ "`max_instances`, `resource_limits`, `container_concurrency`, or "
+ "`keep_alive_probe`, you must also provide the `agent` variable or "
+ "the source code options (`source_packages`, "
+ "`developer_connect_source` or `agent_config_source`)."
+ )
+
+ if agent_engine_spec is not None:
+ if is_deployment_spec_updated:
+ (
+ deployment_spec,
+ deployment_update_masks,
+ ) = self._generate_deployment_spec_or_raise(
+ env_vars=env_vars,
+ psc_interface_config=psc_interface_config,
+ agent_gateway_config=agent_gateway_config,
+ min_instances=min_instances,
+ max_instances=max_instances,
+ resource_limits=resource_limits,
+ container_concurrency=container_concurrency,
+ keep_alive_probe=keep_alive_probe,
+ )
+ update_masks.extend(deployment_update_masks)
+ agent_engine_spec["deployment_spec"] = deployment_spec
+
+ if agent_server_mode:
+ if not agent_engine_spec.get("deployment_spec"):
+ agent_engine_spec["deployment_spec"] = (
+ types.ReasoningEngineSpecDeploymentSpecDict()
+ )
+ agent_engine_spec["deployment_spec"][
+ "agent_server_mode"
+ ] = agent_server_mode
+
+ agent_engine_spec["agent_framework"] = (
+ _agent_engines_utils._get_agent_framework(
+ agent_framework=agent_framework,
+ agent=agent,
+ )
+ )
+
+ if hasattr(agent, "agent_card"):
+ agent_card = getattr(agent, "agent_card")
+ if agent_card:
+ try:
+ from google.protobuf import json_format
+
+ agent_engine_spec["agent_card"] = json_format.MessageToDict(
+ agent_card
+ )
+ except Exception as e:
+ raise ValueError(
+ f"Failed to convert agent card to dict (serialization error): {e}"
+ ) from e
+ update_masks.append("spec.agent_framework")
+
+ if identity_type is not None or service_account is not None:
+ if agent_engine_spec is None:
+ agent_engine_spec = {}
+
+ if identity_type is not None:
+ agent_engine_spec["identity_type"] = identity_type
+ update_masks.append("spec.identity_type")
+ if service_account is not None:
+ # Clear the field in case of empty service_account.
+ if service_account:
+ agent_engine_spec["service_account"] = service_account
+ update_masks.append("spec.service_account")
+
+ if agent_engine_spec is not None:
+ config["spec"] = agent_engine_spec
+
+ if update_masks and mode == "update":
+ config["update_mask"] = ",".join(update_masks)
+ return config
+
+ def _generate_deployment_spec_or_raise(
+ self,
+ *,
+ env_vars: Optional[dict[str, Union[str, Any]]] = None,
+ psc_interface_config: Optional[types.PscInterfaceConfigDict] = None,
+ agent_gateway_config: Optional[
+ types.ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
+ ] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+ keep_alive_probe: Optional[dict[str, Any]] = None,
+ ) -> Tuple[dict[str, Any], Sequence[str]]:
+ deployment_spec: dict[str, Any] = {}
+ update_masks = []
+ if env_vars:
+ deployment_spec["env"] = []
+ deployment_spec["secret_env"] = []
+ if isinstance(env_vars, dict):
+ self._update_deployment_spec_with_env_vars_dict_or_raise(
+ deployment_spec=deployment_spec,
+ env_vars=env_vars,
+ )
+ else:
+ raise TypeError(f"env_vars must be a dict, but got {type(env_vars)}.")
+ if deployment_spec.get("env"):
+ update_masks.append("spec.deployment_spec.env")
+ if deployment_spec.get("secret_env"):
+ update_masks.append("spec.deployment_spec.secret_env")
+ if psc_interface_config:
+ deployment_spec["psc_interface_config"] = psc_interface_config
+ update_masks.append("spec.deployment_spec.psc_interface_config")
+ if agent_gateway_config:
+ deployment_spec["agent_gateway_config"] = agent_gateway_config
+ update_masks.append("spec.deployment_spec.agent_gateway_config")
+ if min_instances is not None:
+ if not 0 <= min_instances <= 10:
+ raise ValueError(
+ f"min_instances must be between 0 and 10. Got {min_instances}"
+ )
+ deployment_spec["min_instances"] = min_instances
+ update_masks.append("spec.deployment_spec.min_instances")
+ if max_instances is not None:
+ if psc_interface_config and not 1 <= max_instances <= 100:
+ raise ValueError(
+ f"max_instances must be between 1 and 100 when PSC-I is enabled. Got {max_instances}"
+ )
+ elif not psc_interface_config and not 1 <= max_instances <= 1000:
+ raise ValueError(
+ f"max_instances must be between 1 and 1000. Got {max_instances}"
+ )
+ deployment_spec["max_instances"] = max_instances
+ update_masks.append("spec.deployment_spec.max_instances")
+ if resource_limits:
+ _agent_engines_utils._validate_resource_limits_or_raise(
+ resource_limits=resource_limits
+ )
+ deployment_spec["resource_limits"] = resource_limits
+ update_masks.append("spec.deployment_spec.resource_limits")
+ if container_concurrency:
+ deployment_spec["container_concurrency"] = container_concurrency
+ update_masks.append("spec.deployment_spec.container_concurrency")
+ if keep_alive_probe is not None:
+ deployment_spec["keep_alive_probe"] = keep_alive_probe
+ update_masks.append("spec.deployment_spec.keep_alive_probe")
+ return deployment_spec, update_masks
+
+ def _update_deployment_spec_with_env_vars_dict_or_raise(
+ self,
+ *,
+ deployment_spec: dict[str, Any],
+ env_vars: dict[str, Any],
+ ) -> None:
+ for key, value in env_vars.items():
+ if isinstance(value, dict):
+ if "secret_env" not in deployment_spec:
+ deployment_spec["secret_env"] = []
+ deployment_spec["secret_env"].append({"name": key, "secret_ref": value})
+ elif isinstance(value, str):
+ if "env" not in deployment_spec:
+ deployment_spec["env"] = []
+ deployment_spec["env"].append({"name": key, "value": value})
+ else:
+ raise TypeError(
+ f"Unknown value type in env_vars for {key}. "
+ f"Must be a str or SecretRef: {value}"
+ )
+
+ def _register_api_methods(
+ self,
+ *,
+ agent_engine: types.AgentEngine,
+ ) -> types.AgentEngine:
+ """Registers the API methods for the agent engine."""
+ try:
+ _agent_engines_utils._register_api_methods_or_raise(
+ agent_engine=agent_engine,
+ wrap_operation_fn={
+ "": _agent_engines_utils._wrap_query_operation, # type: ignore[dict-item]
+ "async": _agent_engines_utils._wrap_async_query_operation, # type: ignore[dict-item]
+ "stream": _agent_engines_utils._wrap_stream_query_operation, # type: ignore[dict-item]
+ "async_stream": _agent_engines_utils._wrap_async_stream_query_operation, # type: ignore[dict-item]
+ "a2a_extension": _agent_engines_utils._wrap_a2a_operation,
+ },
+ )
+ except Exception as e:
+ logger.warning(
+ _agent_engines_utils._FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e
+ )
+ return agent_engine
+
+ def list(
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
+ ) -> Iterator[types.AgentEngine]:
+ """List all instances of Agent Engine matching the filter.
+
+ Example Usage:
+
+ .. code-block:: python
+ import agentplatform
+
+ client = agentplatform.Client(project="my_project", location="us-central1")
+ for agent in client.agent_engines.list(
+ config={"filter": "'display_name="My Custom Agent"'},
+ ):
+ print(agent.api_resource.name)
+
+ Args:
+ config (ListAgentEngineConfig):
+ Optional. The config (e.g. filter) for the agents to be listed.
+
+ Returns:
+ Iterable[AgentEngine]: An iterable of Agent Engines matching the filter.
+ """
+
+ for reasoning_engine in self._list_pager(config=config):
+ yield types.AgentEngine(
+ api_client=self,
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
+ api_resource=reasoning_engine,
+ )
+
+ def update(
+ self,
+ *,
+ name: str,
+ agent: Any = None,
+ agent_engine: Any = None,
+ config: types.AgentEngineConfigOrDict,
+ ) -> types.AgentEngine:
+ """Updates an existing Agent Engine.
+
+ This method updates the configuration of an existing Agent Engine running
+ remotely, which is identified by its name.
+
+ Args:
+ name (str): Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456" or a
+ shortened name such as "reasoningEngines/456".
+ agent (Any):
+ Optional. The instance to be used as the updated Agent Engine.
+ If it is not specified, the existing instance will be used.
+ agent_engine (Any):
+ Optional. This is deprecated. Please use `agent` instead.
+ config (AgentEngineConfig):
+ Optional. The configurations to use for updating the Agent Engine.
+
+ Returns:
+ AgentEngine: The updated Agent Engine.
+
+ Raises:
+ ValueError: If the `project` was not set using `client.Client`.
+ ValueError: If the `location` was not set using `client.Client`.
+ ValueError: If `config.staging_bucket` was not set when `agent_engine`
+ is specified.
+ ValueError: If `config.staging_bucket` does not start with "gs://".
+ ValueError: If `config.extra_packages` is specified but `agent_engine`
+ is None.
+ ValueError: If `config.requirements` is specified but `agent_engine` is
+ None.
+ ValueError: If `config.env_vars` has a dictionary entry that does not
+ correspond to an environment variable value or a SecretRef.
+ TypeError: If `config.env_vars` is not a dictionary.
+ FileNotFoundError: If `config.extra_packages` includes a file or
+ directory that does not exist.
+ IOError: If `config.requirements` is a string that corresponds to a
+ nonexistent file.
+ """
+ if isinstance(config, dict):
+ config = types.AgentEngineConfig.model_validate(config)
+ elif not isinstance(config, types.AgentEngineConfig):
+ raise TypeError(
+ f"config must be a dict or AgentEngineConfig, but got {type(config)}."
+ )
+ context_spec = config.context_spec
+ if context_spec is not None:
+ # Conversion to a dict for _create_config
+ context_spec = json.loads(context_spec.model_dump_json())
+ developer_connect_source = config.developer_connect_source
+ if developer_connect_source is not None:
+ developer_connect_source = json.loads(
+ developer_connect_source.model_dump_json()
+ )
+ agent_config_source = config.agent_config_source
+ if agent_config_source is not None:
+ agent_config_source = json.loads(agent_config_source.model_dump_json())
+ keep_alive_probe = config.keep_alive_probe
+ if keep_alive_probe is not None:
+ keep_alive_probe = json.loads(
+ keep_alive_probe.model_dump_json(exclude_none=True)
+ )
+ traffic_config = config.traffic_config
+ if traffic_config is not None:
+ traffic_config = json.loads(traffic_config.model_dump_json())
+ if agent and agent_engine:
+ raise ValueError("Please specify only one of `agent` or `agent_engine`.")
+ elif agent_engine:
+ raise DeprecationWarning(
+ "The `agent_engine` argument is deprecated. Please use `agent` instead."
+ )
+ image_spec = config.image_spec
+ if image_spec is not None:
+ # Conversion to a dict for _create_config
+ image_spec = json.loads(image_spec.model_dump_json())
+ container_spec = config.container_spec
+ if container_spec is not None:
+ # Conversion to a dict for _create_config
+ container_spec = json.loads(container_spec.model_dump_json())
+ agent = agent or agent_engine
+ api_config = self._create_config(
+ mode="update",
+ agent=agent,
+ identity_type=config.identity_type,
+ staging_bucket=config.staging_bucket,
+ requirements=config.requirements,
+ display_name=config.display_name,
+ description=config.description,
+ gcs_dir_name=config.gcs_dir_name,
+ extra_packages=config.extra_packages,
+ env_vars=config.env_vars,
+ service_account=config.service_account,
+ context_spec=context_spec,
+ psc_interface_config=config.psc_interface_config,
+ agent_gateway_config=config.agent_gateway_config,
+ min_instances=config.min_instances,
+ max_instances=config.max_instances,
+ resource_limits=config.resource_limits,
+ container_concurrency=config.container_concurrency,
+ labels=config.labels,
+ class_methods=config.class_methods,
+ source_packages=config.source_packages,
+ developer_connect_source=developer_connect_source,
+ entrypoint_module=config.entrypoint_module,
+ entrypoint_object=config.entrypoint_object,
+ requirements_file=config.requirements_file,
+ agent_framework=config.agent_framework,
+ python_version=config.python_version,
+ build_options=config.build_options,
+ image_spec=image_spec,
+ agent_config_source=agent_config_source,
+ container_spec=container_spec,
+ keep_alive_probe=keep_alive_probe,
+ traffic_config=traffic_config,
+ )
+ operation = self._update(name=name, config=api_config)
+ reasoning_engine_id = _agent_engines_utils._get_reasoning_engine_id(
+ resource_name=name
+ )
+ logger.info(
+ "View progress and logs at https://console.cloud.google.com/logs/query?"
+ f"project={self._api_client.project}"
+ "&query=resource.type%3D%22aiplatform.googleapis.com%2FReasoningEngine%22%0A"
+ f"resource.labels.reasoning_engine_id%3D%22{reasoning_engine_id}%22."
+ )
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_agent_operation,
+ )
+ agent_engine = types.AgentEngine(
+ api_client=self,
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
+ api_resource=operation.response,
+ )
+ if agent_engine.api_resource:
+ logger.info("Agent Engine updated. To use it in another session:")
+ logger.info(
+ f"agent_engine=client.agent_engines.get(name='{agent_engine.api_resource.name}')"
+ )
+ elif operation.error:
+ raise RuntimeError(f"Failed to update Agent Engine: {operation.error}")
+ if agent_engine.api_resource.spec:
+ self._register_api_methods(agent_engine=agent_engine)
+ return agent_engine # type: ignore[no-any-return]
+
+ def _stream_query(
+ self, *, name: str, config: Optional[types.QueryAgentEngineConfigOrDict] = None
+ ) -> Iterator[Any]:
+ """Streams the response of the agent engine."""
+ parameter_model = types._QueryAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:streamQuery?alt=sse".format_map(request_url_dict)
+ else:
+ path = "{name}:streamQuery?alt=sse"
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+ http_options = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+ for response in self._api_client.request_streamed(
+ "post", path, request_dict, http_options
+ ):
+ yield response
+
+ # TODO: b/436704146 - Replace with generated methods
+ # TODO: b/437129724 - Add replay test for async stream query
+ async def _async_stream_query(
+ self,
+ *,
+ name: str,
+ config: Optional[types.QueryAgentEngineConfigOrDict] = None,
+ ) -> AsyncIterator[Any]:
+ """Streams the response of the agent engine asynchronously."""
+ parameter_model = types._QueryAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:streamQuery?alt=sse".format_map(request_url_dict)
+ else:
+ path = "{name}:streamQuery?alt=sse"
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+ http_options = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+ async_iterator = await self._api_client.async_request_streamed(
+ "post", path, request_dict, http_options
+ )
+ async for response in async_iterator:
+ yield response
+
+ def create_memory(
+ self,
+ *,
+ name: str,
+ fact: str,
+ scope: dict[str, str],
+ config: Optional[types.AgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ """Deprecated. Use agent_engines.memories.create instead."""
+ warnings.warn(
+ (
+ "agent_engines.create_memory is deprecated. "
+ "Use agent_engines.memories.create instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.memories.create(
+ name=name,
+ fact=fact,
+ scope=scope,
+ config=config,
+ )
+
+ def delete_memory(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineMemoryOperation:
+ """Deprecated. Use agent_engines.memories.delete instead."""
+ warnings.warn(
+ (
+ "agent_engines.delete_memory is deprecated. "
+ "Use agent_engines.memories.delete instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.memories.delete(name=name, config=config)
+
+ def generate_memories(
+ self,
+ *,
+ name: str,
+ vertex_session_source: Optional[
+ types.GenerateMemoriesRequestVertexSessionSourceOrDict
+ ] = None,
+ direct_contents_source: Optional[
+ types.GenerateMemoriesRequestDirectContentsSourceOrDict
+ ] = None,
+ direct_memories_source: Optional[
+ types.GenerateMemoriesRequestDirectMemoriesSourceOrDict
+ ] = None,
+ scope: Optional[dict[str, str]] = None,
+ config: Optional[types.GenerateAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEngineGenerateMemoriesOperation:
+ """Deprecated. Use agent_engines.memories.generate instead."""
+ warnings.warn(
+ (
+ "agent_engines.generate_memories is deprecated. "
+ "Use agent_engines.memories.generate instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.memories.generate(
+ name=name,
+ vertex_session_source=vertex_session_source,
+ direct_contents_source=direct_contents_source,
+ direct_memories_source=direct_memories_source,
+ scope=scope,
+ config=config,
+ )
+
+ def get_memory(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.Memory:
+ """Deprecated. Use agent_engines.memories.get instead."""
+ warnings.warn(
+ (
+ "agent_engines.get_memory is deprecated. "
+ "Use agent_engines.memories.get instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.memories.get(name=name, config=config)
+
+ def list_memories(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryConfigOrDict] = None,
+ ) -> Iterator[types.Memory]:
+ """Deprecated. Use agent_engines.memories.list instead."""
+ warnings.warn(
+ (
+ "agent_engines.list_memories is deprecated. "
+ "Use agent_engines.memories.list instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.memories.list(name=name, config=config)
+
+ def retrieve_memories(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ similarity_search_params: Optional[
+ types.RetrieveMemoriesRequestSimilaritySearchParamsOrDict
+ ] = None,
+ simple_retrieval_params: Optional[
+ types.RetrieveMemoriesRequestSimpleRetrievalParamsOrDict
+ ] = None,
+ config: Optional[types.RetrieveAgentEngineMemoriesConfigOrDict] = None,
+ ) -> Iterator[types.RetrieveMemoriesResponseRetrievedMemory]:
+ """Deprecated. Use agent_engines.memories.retrieve instead."""
+ warnings.warn(
+ (
+ "agent_engines.retrieve_memories is deprecated. "
+ "Use agent_engines.memories.retrieve instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.memories.retrieve(
+ name=name,
+ scope=scope,
+ similarity_search_params=similarity_search_params,
+ simple_retrieval_params=simple_retrieval_params,
+ config=config,
+ )
+
+ def create_session(
+ self,
+ *,
+ name: str,
+ user_id: str,
+ config: Optional[types.CreateAgentEngineSessionConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ """Deprecated. Use agent_engines.sessions.create instead."""
+ warnings.warn(
+ (
+ "agent_engines.create_session is deprecated. "
+ "Use agent_engines.sessions.create instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.sessions.create(name=name, user_id=user_id, config=config)
+
+ def delete_session(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineSessionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineSessionOperation:
+ """Deprecated. Use agent_engines.sessions.delete instead."""
+ warnings.warn(
+ (
+ "agent_engines.delete_session is deprecated. "
+ "Use agent_engines.sessions.delete instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.sessions.delete(name=name, config=config)
+
+ def get_session(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineSessionConfigOrDict] = None,
+ ) -> types.Session:
+ """Deprecated. Use agent_engines.sessions.get instead."""
+ warnings.warn(
+ (
+ "agent_engines.get_session is deprecated. "
+ "Use agent_engines.sessions.get instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.sessions.get(name=name, config=config)
+
+ def list_sessions(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionsConfigOrDict] = None,
+ ) -> Iterator[types.Session]:
+ """Deprecated. Use agent_engines.sessions.list instead."""
+ warnings.warn(
+ (
+ "agent_engines.list_sessions is deprecated. "
+ "Use agent_engines.sessions.list instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.sessions.list(name=name, config=config)
+
+ def append_session_event(
+ self,
+ *,
+ name: str,
+ author: str,
+ invocation_id: str,
+ timestamp: datetime.datetime,
+ config: Optional[types.AppendAgentEngineSessionEventConfigOrDict] = None,
+ ) -> types.AppendAgentEngineSessionEventResponse:
+ """Deprecated. Use agent_engines.sessions.events.append instead."""
+ warnings.warn(
+ (
+ "agent_engines.append_session_event is deprecated. "
+ "Use agent_engines.sessions.events.append instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.sessions.events.append(
+ name=name,
+ author=author,
+ invocation_id=invocation_id,
+ timestamp=timestamp,
+ config=config,
+ )
+
+ def list_session_events(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionEventsConfigOrDict] = None,
+ ) -> Iterator[types.SessionEvent]:
+ """Deprecated. Use agent_engines.sessions.events.list instead."""
+ warnings.warn(
+ (
+ "agent_engines.list_session_events is deprecated. "
+ "Use agent_engines.sessions.events.list instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.sessions.events.list(name=name, config=config)
+
+
+class AsyncAgentEngines(_api_module.BaseModule):
+
+ async def cancel_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types.CancelQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.CancelQueryJobResult:
+ """
+ Cancels a long-running query job on an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The reasoning engine resource name.
+ config (CancelQueryJobAgentEngineConfigOrDict):
+ Optional. The configuration for the cancel_query_job.
+
+ """
+
+ parameter_model = types._CancelQueryJobAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CancelQueryJobAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:cancelAsyncQuery".format_map(request_url_dict)
+ else:
+ path = "{name}:cancelAsyncQuery"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.CancelQueryJobResult._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _check_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types.CheckQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.CheckQueryJobResult:
+ """
+ Query an Agent Engine asynchronously.
+ """
+
+ parameter_model = types._CheckQueryJobAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CheckQueryJobAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:checkQueryJob".format_map(request_url_dict)
+ else:
+ path = "{name}:checkQueryJob"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CheckQueryJobResult_from_vertex(response_dict)
+
+ return_value = types.CheckQueryJobResult._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _run_query_job(
+ self,
+ *,
+ name: str,
+ config: Optional[types._RunQueryJobAgentEngineConfigOrDict] = None,
+ ) -> types.AgentEngineOperation:
+ """
+ Run a query job on an agent engine.
+ """
+
+ parameter_model = types._RunQueryJobAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RunQueryJobAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:asyncQuery".format_map(request_url_dict)
+ else:
+ path = "{name}:asyncQuery"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create(
+ self, *, config: Optional[types.CreateAgentEngineConfigOrDict] = None
+ ) -> types.AgentEngineOperation:
+ """
+ Creates a new Agent Engine.
+ """
+
+ parameter_model = types._CreateAgentEngineRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "reasoningEngines".format_map(request_url_dict)
+ else:
+ path = "reasoningEngines"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete(
+ self,
+ *,
+ name: str,
+ force: Optional[bool] = None,
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineOperation:
+ """
+ Delete an Agent Engine resource.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
+ or `reasoningEngines/{resource_id}`.
+ force (bool):
+ Optional. If set to True, child resources will also be deleted.
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
+ the Agent Engine has undeleted child resources. Defaults to False.
+ config (DeleteAgentEngineConfig):
+ Optional. Additional configurations for deleting the Agent Engine.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineRequestParameters(
+ name=name,
+ force=force,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get(
+ self, *, name: str, config: Optional[types.GetAgentEngineConfigOrDict] = None
+ ) -> types.ReasoningEngine:
+ """
+ Get an Agent Engine instance.
+ """
+
+ parameter_model = types._GetAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _ReasoningEngine_from_vertex(response_dict)
+
+ return_value = types.ReasoningEngine._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
+ ) -> types.ListReasoningEnginesResponse:
+ """
+ Lists Agent Engines.
+ """
+
+ parameter_model = types._ListAgentEngineRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "reasoningEngines".format_map(request_url_dict)
+ else:
+ path = "reasoningEngines"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _ListReasoningEnginesResponse_from_vertex(response_dict)
+
+ return_value = types.ListReasoningEnginesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_agent_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineOperation:
+ parameter_model = types._GetAgentEngineOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineOperationParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _query(
+ self, *, name: str, config: Optional[types.QueryAgentEngineConfigOrDict] = None
+ ) -> types.QueryReasoningEngineResponse:
+ """
+ Query an Agent Engine.
+ """
+
+ parameter_model = types._QueryAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:query".format_map(request_url_dict)
+ else:
+ path = "{name}:query"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.QueryReasoningEngineResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _update(
+ self, *, name: str, config: Optional[types.UpdateAgentEngineConfigOrDict] = None
+ ) -> types.AgentEngineOperation:
+ """
+ Updates an Agent Engine.
+ """
+
+ parameter_model = types._UpdateAgentEngineRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateAgentEngineRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "patch", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
+
+ return_value = types.AgentEngineOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _a2a_tasks = None
+ _memories = None
+ _sessions = None
+ _runtimes = None
+
+ async def delete(
+ self,
+ *,
+ name: str,
+ force: Optional[bool] = None,
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineOperation:
+ """
+ Delete an Agent Engine resource.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
+ or `reasoningEngines/{resource_id}`.
+ force (bool):
+ Optional. If set to True, child resources will also be deleted.
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
+ the Agent Engine has undeleted child resources. Defaults to False.
+ config (DeleteAgentEngineConfig):
+ Optional. Additional configurations for deleting the Agent Engine.
+
+ """
+ logger.info(f"Deleting AgentEngine resource: {name}")
+ operation = await self._delete(name=name, force=force, config=config)
+ logger.info(f"Started AgentEngine delete operation: {operation.name}")
+ return operation
+
+ @property
+ def runtimes(self) -> "runtimes_module.AsyncRuntimes":
+ if self._runtimes is None:
+ try:
+ # We need to lazy load the runtimes module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._runtimes = importlib.import_module(".runtimes", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.runtimes' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._runtimes.AsyncRuntimes(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def a2a_tasks(self) -> "a2a_tasks_module.AsyncA2aTasks":
+ if self._a2a_tasks is None:
+ try:
+ # We need to lazy load the a2a_tasks module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._a2a_tasks = importlib.import_module(".a2a_tasks", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.a2a_tasks' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._a2a_tasks.AsyncA2aTasks(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def memories(self) -> "memories_module.AsyncMemories":
+ if self._memories is None:
+ try:
+ # We need to lazy load the memories module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._memories = importlib.import_module(".memories", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.memories' module requires additional "
+ "packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._memories.AsyncMemories(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def sessions(self) -> "sessions_module.AsyncSessions":
+ if self._sessions is None:
+ try:
+ # We need to lazy load the sessions module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._sessions = importlib.import_module(".sessions", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The agent_engines.sessions module requires additional packages. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._sessions.AsyncSessions(self._api_client) # type: ignore[no-any-return]
+
+ async def append_session_event(
+ self,
+ *,
+ name: str,
+ author: str,
+ invocation_id: str,
+ timestamp: datetime.datetime,
+ config: Optional[types.AppendAgentEngineSessionEventConfigOrDict] = None,
+ ) -> types.AppendAgentEngineSessionEventResponse:
+ """Deprecated. Use agent_engines.sessions.events.append instead."""
+ warnings.warn(
+ (
+ "agent_engines.append_session_event is deprecated. "
+ "Use agent_engines.sessions.events.append instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return await self.sessions.events.append(
+ name=name,
+ author=author,
+ invocation_id=invocation_id,
+ timestamp=timestamp,
+ config=config,
+ )
+
+ async def delete_memory(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineMemoryOperation:
+ """Deprecated. Use agent_engines.memories.delete instead."""
+ warnings.warn(
+ (
+ "agent_engines.delete_memory is deprecated. "
+ "Use agent_engines.memories.delete instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return await self.memories.delete(name=name, config=config)
+
+ async def delete_session(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineSessionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineSessionOperation:
+ """Deprecated. Use agent_engines.sessions.delete instead."""
+ warnings.warn(
+ (
+ "agent_engines.delete_session is deprecated. "
+ "Use agent_engines.sessions.delete instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return await self.sessions.delete(name=name, config=config)
+
+ async def get_memory(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.Memory:
+ """Deprecated. Use agent_engines.memories.get instead."""
+ warnings.warn(
+ (
+ "agent_engines.get_memory is deprecated. "
+ "Use agent_engines.memories.get instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return await self.memories.get(name=name, config=config)
+
+ async def get_session(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineSessionConfigOrDict] = None,
+ ) -> types.Session:
+ """Deprecated. Use agent_engines.sessions.get instead."""
+ warnings.warn(
+ (
+ "agent_engines.get_session is deprecated. "
+ "Use agent_engines.sessions.get instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return await self.sessions.get(name=name, config=config)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..5372c72811130468d91ddaeb4e627367e31f5e2f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/client.py
@@ -0,0 +1,375 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import asyncio
+import importlib
+import sys
+from typing import Optional, Union, TYPE_CHECKING
+from types import TracebackType, ModuleType
+
+import google.auth
+from google.cloud.aiplatform import version as aip_version
+from google.genai import _common
+from google.genai import client as genai_client
+from google.genai import types
+from google.genai import version as genai_version
+from google.genai import _api_client as genai_api_client
+from . import live
+
+if TYPE_CHECKING:
+ from agentplatform._genai import (
+ agent_engines as agent_engines_module,
+ )
+ from agentplatform._genai import datasets as datasets_module
+ from agentplatform._genai import evals as evals_module
+ from agentplatform._genai import (
+ prompt_optimizer as prompt_optimizer_module,
+ )
+ from agentplatform._genai import prompts as prompts_module
+ from agentplatform._genai import skills as skills_module
+ from agentplatform._genai import live as live_module
+
+
+_GENAI_MODULES_TELEMETRY_HEADER = "agentplatform-genai-modules"
+
+
+def _custom_append_library_version_headers(headers: dict[str, str]) -> None:
+ """Overridde GenAI SDK header injection to use custom vertex-genai-modules header."""
+ genai_sdk_version = genai_version.__version__
+ module_version = aip_version.__version__
+ python_version = sys.version.split()[0]
+
+ combined_label = f"google-genai-sdk/{genai_sdk_version}+{_GENAI_MODULES_TELEMETRY_HEADER}/{module_version}"
+ full_header = f"{combined_label} gl-python/{python_version}"
+
+ if "user-agent" not in headers or combined_label not in headers["user-agent"]:
+ headers["user-agent"] = f"{full_header} " + headers.get("user-agent", "")
+ headers["user-agent"] = headers["user-agent"].strip()
+
+ if (
+ "x-goog-api-client" not in headers
+ or combined_label not in headers["x-goog-api-client"]
+ ):
+ headers["x-goog-api-client"] = f"{full_header} " + headers.get(
+ "x-goog-api-client", ""
+ )
+ headers["x-goog-api-client"] = headers["x-goog-api-client"].strip()
+
+
+genai_api_client.append_library_version_headers = _custom_append_library_version_headers
+
+
+class AsyncClient:
+ """Async Gen AI Client for the Vertex SDK."""
+
+ def __init__(self, api_client: genai_client.BaseApiClient): # type: ignore[name-defined]
+ self._api_client = api_client
+ self._live = live.AsyncLive(self._api_client)
+ self._evals: Optional[ModuleType] = None
+ self._agent_engines: Optional[ModuleType] = None
+ self._prompt_optimizer: Optional[ModuleType] = None
+ self._prompts: Optional[ModuleType] = None
+ self._datasets: Optional[ModuleType] = None
+ self._skills: Optional[ModuleType] = None
+
+ @property
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI live module is experimental, and may change in future "
+ "versions."
+ )
+ def live(self) -> "live_module.AsyncLive":
+ return self._live
+
+ @property
+ def evals(self) -> "evals_module.AsyncEvals":
+ if self._evals is None:
+ try:
+ # We need to lazy load the evals module to avoid ImportError when
+ # pandas/tqdm are not installed.
+ self._evals = importlib.import_module(".evals", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'evals' module requires 'pandas' and 'tqdm'. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[evaluation]"
+ ) from e
+ return self._evals.AsyncEvals(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def prompt_optimizer(self) -> "prompt_optimizer_module.AsyncPromptOptimizer":
+ if self._prompt_optimizer is None:
+ self._prompt_optimizer = importlib.import_module(
+ ".prompt_optimizer", __package__
+ )
+ return self._prompt_optimizer.AsyncPromptOptimizer(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def agent_engines(self) -> "agent_engines_module.AsyncAgentEngines":
+ if self._agent_engines is None:
+ try:
+ # We need to lazy load the agent_engines module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._agent_engines = importlib.import_module(
+ ".agent_engines",
+ __package__,
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines' module requires 'additional packages'. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._agent_engines.AsyncAgentEngines(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def prompts(self) -> "prompts_module.AsyncPrompts":
+ if self._prompts is None:
+ self._prompts = importlib.import_module(
+ ".prompts",
+ __package__,
+ )
+ return self._prompts.AsyncPrompts(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI async datasets module is experimental, "
+ "and may change in future versions."
+ )
+ def datasets(self) -> "datasets_module.AsyncDatasets":
+ if self._datasets is None:
+ self._datasets = importlib.import_module(
+ ".datasets",
+ __package__,
+ )
+ return self._datasets.AsyncDatasets(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def skills(self) -> "skills_module.AsyncSkills":
+ if self._skills is None:
+ self._skills = importlib.import_module(
+ ".skills",
+ __package__,
+ )
+ return self._skills.AsyncSkills(self._api_client) # type: ignore[no-any-return]
+
+ async def aclose(self) -> None:
+ """Closes the async client explicitly.
+
+ Example usage:
+
+ from agentplatform import Client
+
+ async_client = agentplatform.Client(
+ project='my-project-id', location='us-central1'
+ ).aio
+ prompt_1 = await async_client.prompts.create(...)
+ prompt_2 = await async_client.prompts.create(...)
+ # Close the client to release resources.
+ await async_client.aclose()
+ """
+ await self._api_client.aclose()
+
+ async def __aenter__(self) -> "AsyncClient":
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: Optional[Exception],
+ exc_value: Optional[Exception],
+ traceback: Optional[TracebackType],
+ ) -> None:
+ await self.aclose()
+
+ def __del__(self) -> None:
+ try:
+ asyncio.get_running_loop().create_task(self.aclose())
+ except Exception:
+ pass
+
+
+class Client:
+ """Gen AI Client for the Vertex SDK.
+
+ Use this client to interact with Vertex-specific Gemini features.
+ """
+
+ def __init__(
+ self,
+ *,
+ api_key: Optional[str] = None,
+ credentials: Optional[google.auth.credentials.Credentials] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ debug_config: Optional[genai_client.DebugConfig] = None,
+ http_options: Optional[Union[types.HttpOptions, types.HttpOptionsDict]] = None,
+ ):
+ """Initializes the client.
+
+ Args:
+ api_key (str): The `API key
+ `_
+ to use for authentication. Applies to Vertex AI in express mode only.
+ credentials (google.auth.credentials.Credentials): The credentials to use
+ for authentication when calling the Vertex AI APIs. Credentials can be
+ obtained from environment variables and default credentials. For more
+ information, see `Set up Application Default Credentials
+ `_.
+ project (str): The `Google Cloud project ID
+ `_ to
+ use for quota. Can be obtained from environment variables (for example,
+ ``GOOGLE_CLOUD_PROJECT``).
+ location (str): The `location
+ `_
+ to send API requests to (for example, ``us-central1``). Can be obtained
+ from environment variables.
+ debug_config (DebugConfig): Config settings that control network behavior
+ of the client. This is typically used when running test code.
+ http_options (Union[HttpOptions, HttpOptionsDict]): Http options to use
+ for the client.
+ """
+
+ self._debug_config = debug_config or genai_client.DebugConfig()
+ if isinstance(http_options, dict):
+ http_options = types.HttpOptions(**http_options)
+ if http_options is None:
+ http_options = types.HttpOptions()
+ if http_options.headers is None:
+ http_options.headers = {}
+
+ # Set the base URL for MREP locations.
+ if location in ["us", "eu"] and not http_options.base_url:
+ http_options.base_url = f"https://aiplatform.{location}.rep.googleapis.com/"
+
+ self._api_client = genai_client.Client._get_api_client(
+ vertexai=True,
+ api_key=api_key,
+ credentials=credentials,
+ project=project,
+ location=location,
+ debug_config=self._debug_config,
+ http_options=http_options,
+ )
+ self._aio = AsyncClient(self._api_client)
+ self._evals: Optional[ModuleType] = None
+ self._prompt_optimizer: Optional[ModuleType] = None
+ self._agent_engines: Optional[ModuleType] = None
+ self._prompts: Optional[ModuleType] = None
+ self._datasets: Optional[ModuleType] = None
+ self._skills: Optional[ModuleType] = None
+
+ @property
+ def evals(self) -> "evals_module.Evals":
+ if self._evals is None:
+ try:
+ # We need to lazy load the evals module to avoid ImportError when
+ # pandas/tqdm are not installed.
+ self._evals = importlib.import_module(".evals", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'evals' module requires additional dependencies. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[evaluation]"
+ ) from e
+ return self._evals.Evals(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def prompt_optimizer(self) -> "prompt_optimizer_module.PromptOptimizer":
+ if self._prompt_optimizer is None:
+ self._prompt_optimizer = importlib.import_module(
+ ".prompt_optimizer", __package__
+ )
+ return self._prompt_optimizer.PromptOptimizer(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def aio(self) -> "AsyncClient":
+ return self._aio
+
+ # This is only used for replay tests
+ @staticmethod
+ def _get_api_client(
+ api_key: Optional[str] = None,
+ credentials: Optional[google.auth.credentials.Credentials] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ debug_config: Optional[genai_client.DebugConfig] = None,
+ http_options: Optional[types.HttpOptions] = None,
+ ) -> Optional[genai_client.BaseApiClient]: # type: ignore[name-defined]
+ if debug_config and debug_config.client_mode in [
+ "record",
+ "replay",
+ "auto",
+ ]:
+ return genai_client.ReplayApiClient( # type: ignore[attr-defined]
+ mode=debug_config.client_mode,
+ replay_id=debug_config.replay_id,
+ replays_directory=debug_config.replays_directory,
+ vertexai=True,
+ api_key=api_key,
+ credentials=credentials,
+ project=project,
+ location=location,
+ http_options=http_options,
+ )
+ return None
+
+ @property
+ def agent_engines(self) -> "agent_engines_module.AgentEngines":
+ if self._agent_engines is None:
+ try:
+ # We need to lazy load the agent_engines module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._agent_engines = importlib.import_module(
+ ".agent_engines",
+ __package__,
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines' module requires 'additional packages'. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._agent_engines.AgentEngines(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def prompts(self) -> "prompts_module.Prompts":
+ if self._prompts is None:
+ # Lazy loading the prompts module
+ self._prompts = importlib.import_module(
+ ".prompts",
+ __package__,
+ )
+ return self._prompts.Prompts(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI datasets module is experimental, "
+ "and may change in future versions."
+ )
+ def datasets(self) -> "datasets_module.Datasets":
+ if self._datasets is None:
+ self._datasets = importlib.import_module(
+ ".datasets",
+ __package__,
+ )
+ return self._datasets.Datasets(self._api_client) # type: ignore[no-any-return]
+
+ @property
+ def skills(self) -> "skills_module.Skills":
+ if self._skills is None:
+ self._skills = importlib.import_module(
+ ".skills",
+ __package__,
+ )
+ return self._skills.Skills(self._api_client) # type: ignore[no-any-return]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/datasets.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..57528681fb3e187ddf316459d14e46d4b438c15d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/datasets.py
@@ -0,0 +1,2799 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import asyncio
+import json
+import logging
+import time
+from typing import Any, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai import types as genai_types
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+import pandas as pd
+
+from . import _datasets_utils
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.datasets")
+
+
+def _AssembleDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["gemini_request_read_config"]) is not None:
+ setv(
+ to_object,
+ ["geminiRequestReadConfig"],
+ getv(from_object, ["gemini_request_read_config"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _AssessDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["gemini_request_read_config"]) is not None:
+ setv(
+ to_object,
+ ["geminiRequestReadConfig"],
+ getv(from_object, ["gemini_request_read_config"]),
+ )
+
+ if getv(from_object, ["tuning_resource_usage_assessment_config"]) is not None:
+ setv(
+ to_object,
+ ["tuningResourceUsageAssessmentConfig"],
+ getv(from_object, ["tuning_resource_usage_assessment_config"]),
+ )
+
+ if getv(from_object, ["tuning_validation_assessment_config"]) is not None:
+ setv(
+ to_object,
+ ["tuningValidationAssessmentConfig"],
+ getv(from_object, ["tuning_validation_assessment_config"]),
+ )
+
+ if (
+ getv(from_object, ["batch_prediction_resource_usage_assessment_config"])
+ is not None
+ ):
+ setv(
+ to_object,
+ ["batchPredictionResourceUsageAssessmentConfig"],
+ getv(from_object, ["batch_prediction_resource_usage_assessment_config"]),
+ )
+
+ if getv(from_object, ["batch_prediction_validation_assessment_config"]) is not None:
+ setv(
+ to_object,
+ ["batchPredictionValidationAssessmentConfig"],
+ getv(from_object, ["batch_prediction_validation_assessment_config"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CreateMultimodalDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["metadata_schema_uri"]) is not None:
+ setv(
+ to_object, ["metadataSchemaUri"], getv(from_object, ["metadata_schema_uri"])
+ )
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(to_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _DeleteMultimodalDatasetRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetMultimodalDatasetOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["dataset_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["dataset_id"]))
+
+ if getv(from_object, ["operation_id"]) is not None:
+ setv(to_object, ["_url", "operation_id"], getv(from_object, ["operation_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetMultimodalDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _ListMultimodalDatasetsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListMultimodalDatasetsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _ListMultimodalDatasetsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _UpdateMultimodalDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(to_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+class Datasets(_api_module.BaseModule):
+
+ def _assemble_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssembleDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Assembles a multimodal dataset resource.
+ """
+
+ parameter_model = types._AssembleDatasetParameters(
+ name=name,
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AssembleDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:assemble".format_map(request_url_dict)
+ else:
+ path = "{name}:assemble"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _assess_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ tuning_resource_usage_assessment_config: Optional[
+ types.TuningResourceUsageAssessmentConfigOrDict
+ ] = None,
+ tuning_validation_assessment_config: Optional[
+ types.TuningValidationAssessmentConfigOrDict
+ ] = None,
+ batch_prediction_resource_usage_assessment_config: Optional[
+ types.BatchPredictionResourceUsageAssessmentConfigOrDict
+ ] = None,
+ batch_prediction_validation_assessment_config: Optional[
+ types.BatchPredictionValidationAssessmentConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Assesses a multimodal dataset resource.
+ """
+
+ parameter_model = types._AssessDatasetParameters(
+ name=name,
+ gemini_request_read_config=gemini_request_read_config,
+ tuning_resource_usage_assessment_config=tuning_resource_usage_assessment_config,
+ tuning_validation_assessment_config=tuning_validation_assessment_config,
+ batch_prediction_resource_usage_assessment_config=batch_prediction_resource_usage_assessment_config,
+ batch_prediction_validation_assessment_config=batch_prediction_validation_assessment_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AssessDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:assess".format_map(request_url_dict)
+ else:
+ path = "{name}:assess"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create_multimodal_dataset(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata_schema_uri: Optional[str] = None,
+ metadata: Optional[types.SchemaTablesDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Creates a dataset resource to store multimodal datasets.
+ """
+
+ parameter_model = types._CreateMultimodalDatasetParameters(
+ name=name,
+ display_name=display_name,
+ metadata_schema_uri=metadata_schema_uri,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateMultimodalDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete_multimodal_dataset(
+ self, *, name: str, config: Optional[types.VertexBaseConfigOrDict] = None
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Deletes a multimodal dataset resource.
+ """
+
+ parameter_model = types._DeleteMultimodalDatasetRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteMultimodalDatasetRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_multimodal_dataset(
+ self,
+ *,
+ name: Optional[str] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """
+ Gets a multimodal dataset resource.
+ """
+
+ parameter_model = types._GetMultimodalDatasetParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetMultimodalDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_multimodal_dataset_operation(
+ self,
+ *,
+ dataset_id: Optional[str] = None,
+ operation_id: Optional[str] = None,
+ config: Optional[types.GetMultimodalDatasetOperationConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Gets the operation from creating a multimodal dataset.
+ """
+
+ parameter_model = types._GetMultimodalDatasetOperationParameters(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetMultimodalDatasetOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/operations/{operation_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/operations/{operation_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list_multimodal_datasets(
+ self, *, config: Optional[types.ListMultimodalDatasetsConfigOrDict] = None
+ ) -> types.ListMultimodalDatasetsResponse:
+ """
+ Lists multimodal datasets.
+ """
+
+ parameter_model = types._ListMultimodalDatasetsRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListMultimodalDatasetsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListMultimodalDatasetsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _update_multimodal_dataset(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata: Optional[types.SchemaTablesDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """
+ Updates a multimodal dataset resource.
+ """
+
+ parameter_model = types._UpdateMultimodalDatasetParameters(
+ name=name,
+ display_name=display_name,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateMultimodalDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("patch", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _wait_for_operation(
+ self,
+ operation: types.MultimodalDatasetOperation,
+ timeout_seconds: int,
+ ) -> dict[str, Any]:
+ """Waits for a multimodal or assemble dataset operation to complete.
+
+ Args:
+ operation: The multimodal or assemble dataset operation to wait for.
+ timeout_seconds: The maximum time in seconds to wait for the operation
+ to complete.
+
+ Returns:
+ A dict containing the operation response.
+
+ Raises:
+ TimeoutError: If the operation does not complete within the timeout.
+ ValueError: If the operation fails.
+ """
+ response_operation_name = operation.name
+ if response_operation_name is None:
+ raise ValueError("Dataset operation name is empty.")
+ dataset_id = response_operation_name.split("/datasets/")[1].split("/")[0]
+ operation_id = response_operation_name.split("/")[-1]
+
+ start_time = time.time()
+ sleep_duration_seconds = 5
+ wait_multiplier = 2
+ max_wait_time_seconds = 60
+
+ while (time.time() - start_time) < timeout_seconds:
+ operation = self._get_multimodal_dataset_operation(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ )
+ if operation.done:
+ break
+ time.sleep(sleep_duration_seconds)
+ sleep_duration_seconds = min(
+ sleep_duration_seconds * wait_multiplier, max_wait_time_seconds
+ )
+ else:
+ raise TimeoutError(
+ "The operation did not complete within the"
+ f" specified timeout of {timeout_seconds} seconds."
+ )
+ if not operation or operation.response is None:
+ logger.error(f"Error running the operation {operation.response}.")
+ raise ValueError(f"Error running the operation {operation.response}.")
+ if hasattr(operation, "error") and operation.error is not None:
+ raise ValueError(f"Error running the operation {operation.error}")
+ return operation.response
+
+ def create_from_bigquery(
+ self,
+ *,
+ bigquery_uri: Optional[str] = None,
+ multimodal_dataset: Optional[types.MultimodalDatasetOrDict] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Creates a multimodal dataset from a BigQuery table.
+
+ Args:
+ bigquery_uri:
+ Optional. The BigQuery URI of the table to create the dataset from.
+ e.g. "bq://project.dataset.table". If both `bigquery_uri` and
+ `multimodal_dataset` are provided, and `multimodal_dataset` also
+ contains a BigQuery URI, the `bigquery_uri` parameter takes precedence.
+ multimodal_dataset:
+ Optional. A representation of a multimodal dataset. If `bigquery_uri`
+ is set, `multimodal_dataset` can still be used to set other metadata
+ fields. If both `bigquery_uri` and `multimodal_dataset` are provided,
+ and `multimodal_dataset` also contains a BigQuery URI, the
+ `bigquery_uri` parameter takes precedence.
+ config:
+ Optional. A configuration for creating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDataset object representing a multimodal dataset.
+ """
+ if not bigquery_uri and not multimodal_dataset:
+ raise ValueError(
+ "At least one of `bigquery_uri` or `multimodal_dataset` must be"
+ " provided."
+ )
+
+ if multimodal_dataset is None:
+ multimodal_dataset = types.MultimodalDataset()
+ elif isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+
+ if bigquery_uri:
+ multimodal_dataset = multimodal_dataset.model_copy(deep=True)
+ multimodal_dataset.set_bigquery_uri(bigquery_uri)
+
+ _datasets_utils.validate_multimodal_dataset_bigquery_uri(multimodal_dataset)
+
+ if isinstance(config, dict):
+ config = types.CreateMultimodalDatasetConfig(**config)
+ elif not config:
+ config = types.CreateMultimodalDatasetConfig()
+
+ display_name = (
+ multimodal_dataset.display_name
+ if multimodal_dataset.display_name is not None
+ else _datasets_utils.generate_multimodal_dataset_display_name()
+ )
+ multimodal_dataset_operation = self._create_multimodal_dataset(
+ config=config,
+ display_name=display_name,
+ metadata_schema_uri=_datasets_utils.METADATA_SCHEMA_URI,
+ metadata=multimodal_dataset.metadata,
+ )
+ response = self._wait_for_operation(
+ operation=multimodal_dataset_operation,
+ timeout_seconds=config.timeout,
+ )
+ return _datasets_utils.create_from_response(
+ types.MultimodalDataset, response, config
+ )
+
+ def create_from_pandas(
+ self,
+ *,
+ dataframe: pd.DataFrame,
+ multimodal_dataset: Optional[types.MultimodalDatasetOrDict] = None,
+ target_table_id: Optional[str] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Creates a multimodal dataset from a pandas dataframe.
+
+ Args:
+ dataframe (pandas.DataFrame):
+ The pandas dataframe to be used for the created dataset.
+ multimodal_dataset:
+ Optional. A representation of a multimodal dataset.
+ target_table_id (str):
+ Optional. The BigQuery table id where the dataframe will be
+ uploaded. The table id can be in the format of "dataset.table"
+ or "project.dataset.table". Note that the BigQuery
+ dataset must already exist and be in the same location as the
+ multimodal dataset. If not provided, a generated table id will
+ be created in the `vertex_datasets` dataset (e.g.
+ `project.vertex_datasets_us_central1.multimodal_dataset_4cbf7ffd`).
+ config:
+ Optional. A configuration for creating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ dataset (MultimodalDataset):
+ The created multimodal dataset.
+ """
+ if isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+ elif not multimodal_dataset:
+ multimodal_dataset = types.MultimodalDataset()
+
+ bigframes = _datasets_utils._try_import_bigframes()
+ project = self._api_client.project
+ location = self._api_client.location
+ credentials = self._api_client._credentials
+
+ session_options = bigframes.BigQueryOptions(
+ credentials=credentials,
+ project=project,
+ location=location,
+ )
+ with bigframes.connect(session_options) as session:
+ return self.create_from_bigframes(
+ dataframe=session.read_pandas(dataframe),
+ multimodal_dataset=multimodal_dataset,
+ target_table_id=target_table_id,
+ config=config,
+ )
+
+ def create_from_bigframes(
+ self,
+ *,
+ dataframe: "bigframes.pandas.DataFrame", # type: ignore # noqa: F821
+ multimodal_dataset: Optional[types.MultimodalDatasetOrDict] = None,
+ target_table_id: Optional[str] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Creates a multimodal dataset from a bigframes dataframe.
+
+ Args:
+ dataframe (bigframes.pandas.DataFrame):
+ The BigFrames dataframe that will be used for the created
+ dataset.
+ multimodal_dataset:
+ Optional. A representation of a multimodal dataset.
+ target_table_id (str):
+ Optional. The BigQuery table id where the dataframe will be
+ uploaded. The table id can be in the format of "dataset.table"
+ or "project.dataset.table". Note that the BigQuery
+ dataset must already exist and be in the same location as the
+ multimodal dataset. If not provided, a generated table id will
+ be created in the `vertex_datasets` dataset (e.g.
+ `project.vertex_datasets_us_central1.multimodal_dataset_4cbf7ffd`).
+ config:
+ Optional. A configuration for creating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ dataset (MultimodalDataset):
+ The created multimodal dataset.
+ """
+ if isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+ elif not multimodal_dataset:
+ multimodal_dataset = types.MultimodalDataset()
+
+ bigquery = _datasets_utils._try_import_bigquery()
+ project = self._api_client.project
+ location = self._api_client.location
+ credentials = self._api_client._credentials
+
+ if target_table_id:
+ target_table_id = _datasets_utils._normalize_and_validate_table_id(
+ table_id=target_table_id,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+ else:
+ dataset_id = _datasets_utils._create_default_bigquery_dataset_if_not_exists(
+ project=project, location=location, credentials=credentials
+ )
+ target_table_id = _datasets_utils._generate_target_table_id(dataset_id)
+
+ client = bigquery.Client(project=project, credentials=credentials)
+ _datasets_utils.save_dataframe_to_bigquery(
+ dataframe,
+ target_table_id,
+ client,
+ )
+
+ multimodal_dataset = multimodal_dataset.model_copy(deep=True)
+ multimodal_dataset.set_bigquery_uri(f"bq://{target_table_id}")
+ return self.create_from_bigquery(
+ multimodal_dataset=multimodal_dataset, config=config
+ )
+
+ def update_multimodal_dataset(
+ self,
+ *,
+ multimodal_dataset: types.MultimodalDatasetOrDict,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Updates a multimodal dataset.
+
+ Updatable fields include:
+ - display_name
+ - description
+
+ Args:
+ multimodal_dataset:
+ Required. A representation of a multimodal dataset.
+ config:
+ Optional. A configuration for updating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDataset object representing the retrieved multimodal
+ dataset.
+ """
+ if isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+ _datasets_utils.validate_multimodal_dataset_bigquery_uri(multimodal_dataset)
+
+ if isinstance(config, dict):
+ config = types.VertexBaseConfig(**config)
+ elif not config:
+ config = types.VertexBaseConfig()
+
+ return self._update_multimodal_dataset(
+ config=config,
+ name=multimodal_dataset.name,
+ display_name=multimodal_dataset.display_name,
+ description=multimodal_dataset.description,
+ metadata=multimodal_dataset.metadata,
+ )
+
+ def get_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Gets a multimodal dataset.
+
+ Args:
+ name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ config:
+ Optional. A configuration for getting the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDataset object representing the retrieved multimodal
+ dataset.
+ """
+ if isinstance(config, dict):
+ config = types.VertexBaseConfig(**config)
+ elif not config:
+ config = types.VertexBaseConfig()
+
+ name = _datasets_utils.resolve_dataset_name(
+ name, self._api_client.project, self._api_client.location
+ )
+
+ return self._get_multimodal_dataset(config=config, name=name)
+
+ def delete_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """Deletes a multimodal dataset.
+
+ Args:
+ name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ config:
+ Optional. A configuration for deleting the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDatasetOperation object representing the delete
+ multimodal dataset operation.
+ """
+ if isinstance(config, dict):
+ config = types.VertexBaseConfig(**config)
+ elif not config:
+ config = types.VertexBaseConfig()
+
+ name = _datasets_utils.resolve_dataset_name(
+ name, self._api_client.project, self._api_client.location
+ )
+
+ return self._delete_multimodal_dataset(config=config, name=name)
+
+ def assemble(
+ self,
+ *,
+ name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssembleDatasetConfigOrDict] = None,
+ ) -> str:
+ """Assemble the dataset into a BigQuery table.
+
+ Waits for the assemble operation to complete before returning.
+
+ Args:
+ name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ gemini_request_read_config:
+ Optional. The read config to use to assemble the dataset. If
+ not provided, the read config attached to the dataset will be
+ used.
+ config:
+ Optional. A configuration for assembling the dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ The URI of the bigquery table of the assembled dataset.
+ """
+ if isinstance(config, dict):
+ config = types.AssembleDatasetConfig(**config)
+ elif not config:
+ config = types.AssembleDatasetConfig()
+
+ name = _datasets_utils.resolve_dataset_name(
+ name, self._api_client.project, self._api_client.location
+ )
+
+ operation = self._assemble_multimodal_dataset(
+ name=name,
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ return response["bigqueryDestination"] # type: ignore[no-any-return]
+
+ def assess_tuning_resources(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.TuningResourceUsageAssessmentResult:
+ """Assess the tuning resources required for a given model.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the tuning resources
+ for.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the tuning resources. If not provided, the
+ read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the tuning resources. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.TuningResourceUsageAssessmentResult object representing the
+ tuning resource usage assessment result.
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = self._assess_multimodal_dataset(
+ name=dataset_name,
+ tuning_resource_usage_assessment_config=types.TuningResourceUsageAssessmentConfig(
+ model_name=model_name
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ return _datasets_utils.create_from_response(
+ types.TuningResourceUsageAssessmentResult,
+ response["tuningResourceUsageAssessmentResult"],
+ config,
+ )
+
+ def assess_tuning_validity(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ dataset_usage: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.TuningValidationAssessmentResult:
+ """Assess if the assembled dataset is valid in terms of tuning a given
+ model.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the tuning validity
+ for.
+ dataset_usage:
+ Required. The dataset usage to assess the tuning validity for.
+ Must be one of the following: SFT_TRAINING, SFT_VALIDATION.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the tuning validity. If not provided, the
+ read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the tuning validity. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A dict containing the tuning validity assessment result. The dict
+ contains the following keys:
+ - errors: A list of errors that occurred during the tuning validity
+ assessment.
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = self._assess_multimodal_dataset(
+ name=dataset_name,
+ tuning_validation_assessment_config=types.TuningValidationAssessmentConfig(
+ model_name=model_name,
+ dataset_usage=dataset_usage,
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ return _datasets_utils.create_from_response(
+ types.TuningValidationAssessmentResult,
+ response["tuningValidationAssessmentResult"],
+ config,
+ )
+
+ def assess_batch_prediction_resources(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.BatchPredictionResourceUsageAssessmentResult:
+ """Assess the batch prediction resources required for a given model.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the batch prediction
+ resources.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the batch prediction resources. If not provided,
+ the read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the batch prediction
+ resources. If not provided, the default configuration will be
+ used.
+
+ Returns:
+ A types.BatchPredictionResourceUsageAssessmentResult object
+ representing the batch prediction resource usage assessment result.
+ It contains the following keys:
+ - token_count: The number of tokens in the dataset.
+ - audio_token_count: The number of audio tokens in the dataset.
+
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = self._assess_multimodal_dataset(
+ name=dataset_name,
+ batch_prediction_resource_usage_assessment_config=types.BatchPredictionResourceUsageAssessmentConfig(
+ model_name=model_name,
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ result = response["batchPredictionResourceUsageAssessmentResult"]
+ return _datasets_utils.create_from_response(
+ types.BatchPredictionResourceUsageAssessmentResult, result, config
+ )
+
+ def assess_batch_prediction_validity(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.BatchPredictionValidationAssessmentResult:
+ """Assess if the assembled dataset is valid in terms of batch prediction
+ for a given model. Raises an error if the dataset is invalid, otherwise
+ returns None.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the batch prediction
+ validity for.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the batch prediction validity. If not provided, the
+ read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the batch prediction validity.
+ If not provided, the default configuration will be used.
+
+ Returns:
+ A types.BatchPredictionValidationAssessmentResult object representing
+ the batch prediction validity assessment result.
+ It contains the following keys:
+ - errors: A list of errors that occurred during the batch prediction
+ validity assessment.
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = self._assess_multimodal_dataset(
+ name=dataset_name,
+ batch_prediction_validation_assessment_config=types.BatchPredictionValidationAssessmentConfig(
+ model_name=model_name,
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ result = response["batchPredictionValidationAssessmentResult"]
+ return _datasets_utils.create_from_response(
+ types.BatchPredictionValidationAssessmentResult, result, config
+ )
+
+
+class AsyncDatasets(_api_module.BaseModule):
+
+ async def _assemble_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssembleDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Assembles a multimodal dataset resource.
+ """
+
+ parameter_model = types._AssembleDatasetParameters(
+ name=name,
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AssembleDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:assemble".format_map(request_url_dict)
+ else:
+ path = "{name}:assemble"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _assess_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ tuning_resource_usage_assessment_config: Optional[
+ types.TuningResourceUsageAssessmentConfigOrDict
+ ] = None,
+ tuning_validation_assessment_config: Optional[
+ types.TuningValidationAssessmentConfigOrDict
+ ] = None,
+ batch_prediction_resource_usage_assessment_config: Optional[
+ types.BatchPredictionResourceUsageAssessmentConfigOrDict
+ ] = None,
+ batch_prediction_validation_assessment_config: Optional[
+ types.BatchPredictionValidationAssessmentConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Assesses a multimodal dataset resource.
+ """
+
+ parameter_model = types._AssessDatasetParameters(
+ name=name,
+ gemini_request_read_config=gemini_request_read_config,
+ tuning_resource_usage_assessment_config=tuning_resource_usage_assessment_config,
+ tuning_validation_assessment_config=tuning_validation_assessment_config,
+ batch_prediction_resource_usage_assessment_config=batch_prediction_resource_usage_assessment_config,
+ batch_prediction_validation_assessment_config=batch_prediction_validation_assessment_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AssessDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:assess".format_map(request_url_dict)
+ else:
+ path = "{name}:assess"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create_multimodal_dataset(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata_schema_uri: Optional[str] = None,
+ metadata: Optional[types.SchemaTablesDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Creates a dataset resource to store multimodal datasets.
+ """
+
+ parameter_model = types._CreateMultimodalDatasetParameters(
+ name=name,
+ display_name=display_name,
+ metadata_schema_uri=metadata_schema_uri,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateMultimodalDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete_multimodal_dataset(
+ self, *, name: str, config: Optional[types.VertexBaseConfigOrDict] = None
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Deletes a multimodal dataset resource.
+ """
+
+ parameter_model = types._DeleteMultimodalDatasetRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteMultimodalDatasetRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_multimodal_dataset(
+ self,
+ *,
+ name: Optional[str] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """
+ Gets a multimodal dataset resource.
+ """
+
+ parameter_model = types._GetMultimodalDatasetParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetMultimodalDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_multimodal_dataset_operation(
+ self,
+ *,
+ dataset_id: Optional[str] = None,
+ operation_id: Optional[str] = None,
+ config: Optional[types.GetMultimodalDatasetOperationConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """
+ Gets the operation from creating a multimodal dataset.
+ """
+
+ parameter_model = types._GetMultimodalDatasetOperationParameters(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetMultimodalDatasetOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/operations/{operation_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/operations/{operation_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list_multimodal_datasets(
+ self, *, config: Optional[types.ListMultimodalDatasetsConfigOrDict] = None
+ ) -> types.ListMultimodalDatasetsResponse:
+ """
+ Lists multimodal datasets.
+ """
+
+ parameter_model = types._ListMultimodalDatasetsRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListMultimodalDatasetsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListMultimodalDatasetsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _update_multimodal_dataset(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata: Optional[types.SchemaTablesDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """
+ Updates a multimodal dataset resource.
+ """
+
+ parameter_model = types._UpdateMultimodalDatasetParameters(
+ name=name,
+ display_name=display_name,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateMultimodalDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "patch", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MultimodalDataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _wait_for_operation(
+ self,
+ operation: types.MultimodalDatasetOperation,
+ timeout_seconds: int,
+ ) -> dict[str, Any]:
+ """Waits for a multimodal dataset operation to complete.
+
+ Args:
+ operation: The multimodal dataset operation to wait for.
+ timeout_seconds: The maximum time in seconds to wait for the operation
+ to complete.
+
+ Returns:
+ A dict containing the operation response.
+
+ Raises:
+ TimeoutError: If the operation does not complete within the timeout.
+ ValueError: If the operation fails.
+ """
+ response_operation_name = operation.name
+ if response_operation_name is None:
+ raise ValueError("Dataset operation name is empty.")
+ dataset_id = response_operation_name.split("/datasets/")[1].split("/")[0]
+ operation_id = response_operation_name.split("/")[-1]
+
+ start_time = time.time()
+ sleep_duration_seconds = 5
+ wait_multiplier = 2
+ max_wait_time_seconds = 60
+
+ while (time.time() - start_time) < timeout_seconds:
+ operation = await self._get_multimodal_dataset_operation(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ )
+ if operation.done:
+ break
+ await asyncio.sleep(sleep_duration_seconds)
+ sleep_duration_seconds = min(
+ sleep_duration_seconds * wait_multiplier, max_wait_time_seconds
+ )
+ else:
+ raise TimeoutError(
+ "The operation did not complete within the"
+ f" specified timeout of {timeout_seconds} seconds."
+ )
+ if not operation or operation.response is None:
+ logger.error(f"Error running the operation {operation.response}.")
+ raise ValueError(f"Error running the operation {operation.response}.")
+ if hasattr(operation, "error") and operation.error is not None:
+ raise ValueError(f"Error running the operation {operation.error}")
+ return operation.response
+
+ async def create_from_bigquery(
+ self,
+ *,
+ bigquery_uri: Optional[str] = None,
+ multimodal_dataset: Optional[types.MultimodalDatasetOrDict] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Creates a multimodal dataset from a BigQuery table.
+
+ Args:
+ bigquery_uri:
+ Optional. The BigQuery URI of the table to create the dataset from.
+ e.g. "bq://project.dataset.table". If both `bigquery_uri` and
+ `multimodal_dataset` are provided, and `multimodal_dataset` also
+ contains a BigQuery URI, the `bigquery_uri` parameter takes precedence.
+ multimodal_dataset:
+ Optional. A representation of a multimodal dataset. If `bigquery_uri`
+ is set, `multimodal_dataset` can still be used to set other metadata
+ fields. If both `bigquery_uri` and `multimodal_dataset` are provided,
+ and `multimodal_dataset` also contains a BigQuery URI, the
+ `bigquery_uri` parameter takes precedence.
+ config:
+ Optional. A configuration for creating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDataset object representing a multimodal dataset.
+ """
+ if not bigquery_uri and not multimodal_dataset:
+ raise ValueError(
+ "At least one of `bigquery_uri` or `multimodal_dataset` must be"
+ " provided."
+ )
+
+ if multimodal_dataset is None:
+ multimodal_dataset = types.MultimodalDataset()
+ elif isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+
+ if bigquery_uri:
+ multimodal_dataset = multimodal_dataset.model_copy(deep=True)
+ multimodal_dataset.set_bigquery_uri(bigquery_uri)
+
+ _datasets_utils.validate_multimodal_dataset_bigquery_uri(multimodal_dataset)
+
+ if isinstance(config, dict):
+ config = types.CreateMultimodalDatasetConfig(**config)
+ elif not config:
+ config = types.CreateMultimodalDatasetConfig()
+
+ display_name = (
+ multimodal_dataset.display_name
+ if multimodal_dataset.display_name is not None
+ else _datasets_utils.generate_multimodal_dataset_display_name()
+ )
+ multimodal_dataset_operation = await self._create_multimodal_dataset(
+ config=config,
+ display_name=display_name,
+ metadata_schema_uri=_datasets_utils.METADATA_SCHEMA_URI,
+ metadata=multimodal_dataset.metadata,
+ )
+ response = await self._wait_for_operation(
+ operation=multimodal_dataset_operation,
+ timeout_seconds=config.timeout,
+ )
+ return _datasets_utils.create_from_response(
+ types.MultimodalDataset, response, config
+ )
+
+ async def create_from_pandas(
+ self,
+ *,
+ dataframe: pd.DataFrame,
+ multimodal_dataset: Optional[types.MultimodalDatasetOrDict] = None,
+ target_table_id: Optional[str] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Creates a multimodal dataset from a pandas dataframe.
+
+ Args:
+ dataframe (pandas.DataFrame):
+ The pandas dataframe to be used for the created dataset.
+ multimodal_dataset:
+ Optional. A representation of a multimodal dataset.
+ target_table_id (str):
+ Optional. The BigQuery table id where the dataframe will be
+ uploaded. The table id can be in the format of "dataset.table"
+ or "project.dataset.table". Note that the BigQuery
+ dataset must already exist and be in the same location as the
+ multimodal dataset. If not provided, a generated table id will
+ be created in the `vertex_datasets` dataset (e.g.
+ `project.vertex_datasets_us_central1.multimodal_dataset_4cbf7ffd`).
+ config:
+ Optional. A configuration for creating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ dataset (MultimodalDataset):
+ The created multimodal dataset.
+ """
+ if isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+ elif not multimodal_dataset:
+ multimodal_dataset = types.MultimodalDataset()
+
+ bigframes = _datasets_utils._try_import_bigframes()
+ project = self._api_client.project
+ location = self._api_client.location
+ credentials = self._api_client._credentials
+
+ session_options = bigframes.BigQueryOptions(
+ credentials=credentials,
+ project=project,
+ location=location,
+ )
+ with bigframes.connect(session_options) as session:
+ return await self.create_from_bigframes(
+ dataframe=session.read_pandas(dataframe),
+ multimodal_dataset=multimodal_dataset,
+ target_table_id=target_table_id,
+ config=config,
+ )
+
+ async def create_from_bigframes(
+ self,
+ *,
+ dataframe: "bigframes.pandas.DataFrame", # type: ignore # noqa: F821
+ multimodal_dataset: Optional[types.MultimodalDatasetOrDict] = None,
+ target_table_id: Optional[str] = None,
+ config: Optional[types.CreateMultimodalDatasetConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Creates a multimodal dataset from a bigframes dataframe.
+
+ Args:
+ dataframe (bigframes.pandas.DataFrame):
+ The BigFrames dataframe that will be used for the created
+ dataset.
+ multimodal_dataset:
+ Optional. A representation of a multimodal dataset.
+ target_table_id (str):
+ Optional. The BigQuery table id where the dataframe will be
+ uploaded. The table id can be in the format of "dataset.table"
+ or "project.dataset.table". Note that the BigQuery
+ dataset must already exist and be in the same location as the
+ multimodal dataset. If not provided, a generated table id will
+ be created in the `vertex_datasets` dataset (e.g.
+ `project.vertex_datasets_us_central1.multimodal_dataset_4cbf7ffd`).
+ config:
+ Optional. A configuration for creating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ dataset (MultimodalDataset):
+ The created multimodal dataset.
+ """
+ if isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+ elif not multimodal_dataset:
+ multimodal_dataset = types.MultimodalDataset()
+
+ bigquery = _datasets_utils._try_import_bigquery()
+ project = self._api_client.project
+ location = self._api_client.location
+ credentials = self._api_client._credentials
+
+ if target_table_id:
+ target_table_id = (
+ await _datasets_utils._normalize_and_validate_table_id_async(
+ table_id=target_table_id,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+ )
+ else:
+ dataset_id = await _datasets_utils._create_default_bigquery_dataset_if_not_exists_async(
+ project=project, location=location, credentials=credentials
+ )
+ target_table_id = _datasets_utils._generate_target_table_id(dataset_id)
+
+ client = bigquery.Client(project=project, credentials=credentials)
+ await _datasets_utils.save_dataframe_to_bigquery_async(
+ dataframe,
+ target_table_id,
+ client,
+ )
+
+ multimodal_dataset = multimodal_dataset.model_copy(deep=True)
+ multimodal_dataset.set_bigquery_uri(f"bq://{target_table_id}")
+ return await self.create_from_bigquery(
+ multimodal_dataset=multimodal_dataset, config=config
+ )
+
+ async def update_multimodal_dataset(
+ self,
+ *,
+ multimodal_dataset: types.MultimodalDatasetOrDict,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Updates a multimodal dataset.
+
+ Args:
+ multimodal_dataset:
+ Required. A representation of a multimodal dataset.
+ config:
+ Optional. A configuration for updating the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDataset object representing the updated multimodal
+ dataset.
+ """
+ if isinstance(multimodal_dataset, dict):
+ multimodal_dataset = types.MultimodalDataset(**multimodal_dataset)
+ _datasets_utils.validate_multimodal_dataset_bigquery_uri(multimodal_dataset)
+
+ if isinstance(config, dict):
+ config = types.VertexBaseConfig(**config)
+ elif not config:
+ config = types.VertexBaseConfig()
+
+ return await self._update_multimodal_dataset(
+ config=config,
+ name=multimodal_dataset.name,
+ display_name=multimodal_dataset.display_name,
+ description=multimodal_dataset.description,
+ metadata=multimodal_dataset.metadata,
+ )
+
+ async def get_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDataset:
+ """Gets a multimodal dataset.
+
+ Args:
+ name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ config:
+ Optional. A configuration for getting the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDataset object representing the retrieved multimodal
+ dataset.
+ """
+ if isinstance(config, dict):
+ config = types.VertexBaseConfig(**config)
+ elif not config:
+ config = types.VertexBaseConfig()
+
+ name = _datasets_utils.resolve_dataset_name(
+ name, self._api_client.project, self._api_client.location
+ )
+
+ return await self._get_multimodal_dataset(config=config, name=name)
+
+ async def delete_multimodal_dataset(
+ self,
+ *,
+ name: str,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.MultimodalDatasetOperation:
+ """Deletes a multimodal dataset.
+
+ Args:
+ name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ config:
+ Optional. A configuration for deleting the multimodal dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.MultimodalDatasetOperation object representing the delete
+ multimodal dataset operation.
+ """
+ if isinstance(config, dict):
+ config = types.VertexBaseConfig(**config)
+ elif not config:
+ config = types.VertexBaseConfig()
+
+ name = _datasets_utils.resolve_dataset_name(
+ name, self._api_client.project, self._api_client.location
+ )
+
+ return await self._delete_multimodal_dataset(config=config, name=name)
+
+ async def assemble(
+ self,
+ *,
+ name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssembleDatasetConfigOrDict] = None,
+ ) -> str:
+ """Assemble the dataset into a BigQuery table.
+
+ Waits for the assemble operation to complete before returning.
+
+ Args:
+ name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ gemini_request_read_config:
+ Optional. The read config to use to assemble the dataset. If
+ not provided, the read config attached to the dataset will be
+ used.
+ config:
+ Optional. A configuration for assembling the dataset. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ The URI of the bigquery table of the assembled dataset.
+ """
+ if isinstance(config, dict):
+ config = types.AssembleDatasetConfig(**config)
+ elif not config:
+ config = types.AssembleDatasetConfig()
+
+ name = _datasets_utils.resolve_dataset_name(
+ name, self._api_client.project, self._api_client.location
+ )
+
+ operation = await self._assemble_multimodal_dataset(
+ name=name,
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = await self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ return response["bigqueryDestination"] # type: ignore[no-any-return]
+
+ async def assess_tuning_resources(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.TuningResourceUsageAssessmentResult:
+ """Assess the tuning resources required for a given model.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the tuning resources
+ for.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the tuning resources. If not provided, the
+ read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the tuning resources. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A types.TuningResourceUsageAssessmentResult object representing the
+ tuning resource usage assessment result.
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = await self._assess_multimodal_dataset(
+ name=dataset_name,
+ tuning_resource_usage_assessment_config=types.TuningResourceUsageAssessmentConfig(
+ model_name=model_name
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = await self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ return _datasets_utils.create_from_response(
+ types.TuningResourceUsageAssessmentResult,
+ response["tuningResourceUsageAssessmentResult"],
+ config,
+ )
+
+ async def assess_tuning_validity(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ dataset_usage: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.TuningValidationAssessmentResult:
+ """Assess if the assembled dataset is valid in terms of tuning a given
+ model.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the tuning validity
+ for.
+ dataset_usage:
+ Required. The dataset usage to assess the tuning validity for.
+ Must be one of the following: SFT_TRAINING, SFT_VALIDATION.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the tuning validity. If not provided, the
+ read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the tuning validity. If not
+ provided, the default configuration will be used.
+
+ Returns:
+ A dict containing the tuning validity assessment result. The dict
+ contains the following keys:
+ - errors: A list of errors that occurred during the tuning validity
+ assessment.
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = await self._assess_multimodal_dataset(
+ name=dataset_name,
+ tuning_validation_assessment_config=types.TuningValidationAssessmentConfig(
+ model_name=model_name,
+ dataset_usage=dataset_usage,
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = await self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ return _datasets_utils.create_from_response(
+ types.TuningValidationAssessmentResult,
+ response["tuningValidationAssessmentResult"],
+ config,
+ )
+
+ async def assess_batch_prediction_resources(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.BatchPredictionResourceUsageAssessmentResult:
+ """Assess the batch prediction resources required for a given model.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the batch prediction
+ resources.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the batch prediction resources. If not provided,
+ the read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the batch prediction
+ resources. If not provided, the default configuration will be
+ used.
+
+ Returns:
+ A types.BatchPredictionResourceUsageAssessmentResult object
+ representing the batch prediction resource usage assessment result.
+ It contains the following keys:
+ - token_count: The number of tokens in the dataset.
+ - audio_token_count: The number of audio tokens in the dataset.
+
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = await self._assess_multimodal_dataset(
+ name=dataset_name,
+ batch_prediction_resource_usage_assessment_config=types.BatchPredictionResourceUsageAssessmentConfig(
+ model_name=model_name,
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = await self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ result = response["batchPredictionResourceUsageAssessmentResult"]
+ return _datasets_utils.create_from_response(
+ types.BatchPredictionResourceUsageAssessmentResult, result, config
+ )
+
+ async def assess_batch_prediction_validity(
+ self,
+ *,
+ dataset_name: str,
+ model_name: str,
+ gemini_request_read_config: Optional[
+ types.GeminiRequestReadConfigOrDict
+ ] = None,
+ config: Optional[types.AssessDatasetConfigOrDict] = None,
+ ) -> types.BatchPredictionValidationAssessmentResult:
+ """Assess if the assembled dataset is valid in terms of batch prediction
+ for a given model. Raises an error if the dataset is invalid, otherwise
+ returns None.
+
+ Args:
+ dataset_name:
+ Required. A fully-qualified resource name or ID of the dataset.
+ Example: "projects/.../locations/.../datasets/123" or "123".
+ model_name:
+ Required. The name of the model to assess the batch prediction
+ validity for.
+ gemini_request_read_config:
+ Optional. The read config used to assemble the dataset
+ before assessing the batch prediction validity. If not provided, the
+ read config attached to the dataset will be used. Required
+ if no read config is attached to the dataset.
+ config:
+ Optional. A configuration for assessing the batch prediction validity.
+ If not provided, the default configuration will be used.
+
+ Returns:
+ A types.BatchPredictionValidationAssessmentResult object representing
+ the batch prediction validity assessment result.
+ It contains the following keys:
+ - errors: A list of errors that occurred during the batch prediction
+ validity assessment.
+ """
+ if isinstance(config, dict):
+ config = types.AssessDatasetConfig(**config)
+ elif not config:
+ config = types.AssessDatasetConfig()
+
+ dataset_name = _datasets_utils.resolve_dataset_name(
+ dataset_name, self._api_client.project, self._api_client.location
+ )
+
+ operation = await self._assess_multimodal_dataset(
+ name=dataset_name,
+ batch_prediction_validation_assessment_config=types.BatchPredictionValidationAssessmentConfig(
+ model_name=model_name,
+ ),
+ gemini_request_read_config=gemini_request_read_config,
+ config=config,
+ )
+ response = await self._wait_for_operation(
+ operation=operation,
+ timeout_seconds=config.timeout,
+ )
+ result = response["batchPredictionValidationAssessmentResult"]
+ return _datasets_utils.create_from_response(
+ types.BatchPredictionValidationAssessmentResult, result, config
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/evals.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/evals.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbbabdd1d75353bf447e6076f90100709135e51a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/evals.py
@@ -0,0 +1,4940 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import json
+import logging
+from typing import Any, Callable, Optional, Union, cast
+from urllib.parse import urlencode
+import uuid
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai import types as genai_types
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+import pandas as pd
+
+from . import _evals_common
+from . import _evals_utils
+from . import _transformers as t
+from . import types
+from .types import evals as evals_types
+
+try:
+ from google.adk.agents import LlmAgent
+except ImportError:
+ LlmAgent = None
+
+
+logger = logging.getLogger("agentplatform_genai.evals")
+
+
+def _CreateEvaluationItemParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["evaluation_item_type"]) is not None:
+ setv(
+ to_object,
+ ["evaluationItemType"],
+ getv(from_object, ["evaluation_item_type"]),
+ )
+
+ if getv(from_object, ["gcs_uri"]) is not None:
+ setv(to_object, ["gcsUri"], getv(from_object, ["gcs_uri"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CreateEvaluationMetricParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["metric"]) is not None:
+ setv(
+ to_object,
+ ["metric"],
+ t.t_metric_for_registry(getv(from_object, ["metric"])),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CreateEvaluationRunParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["data_source"]) is not None:
+ setv(to_object, ["dataSource"], getv(from_object, ["data_source"]))
+
+ if getv(from_object, ["evaluation_config"]) is not None:
+ setv(
+ to_object,
+ ["evaluationConfig"],
+ _EvaluationRunConfig_to_vertex(
+ getv(from_object, ["evaluation_config"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["inference_configs"]) is not None:
+ setv(
+ to_object,
+ ["inferenceConfigs"],
+ {
+ k: _EvaluationRunInferenceConfig_to_vertex(v, to_object)
+ for k, v in getv(from_object, ["inference_configs"]).items()
+ },
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ if getv(from_object, ["analysis_configs"]) is not None:
+ setv(
+ to_object,
+ ["analysisConfigs"],
+ [item for item in getv(from_object, ["analysis_configs"])],
+ )
+
+ return to_object
+
+
+def _CreateEvaluationSetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["evaluation_items"]) is not None:
+ setv(to_object, ["evaluationItems"], getv(from_object, ["evaluation_items"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CustomCodeExecutionSpec_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["evaluationFunction"]) is not None:
+ setv(
+ to_object,
+ ["evaluation_function"],
+ getv(from_object, ["evaluationFunction"]),
+ )
+
+ if getv(from_object, ["evaluation_function"]) is not None:
+ setv(
+ to_object,
+ ["remote_custom_function"],
+ getv(from_object, ["evaluation_function"]),
+ )
+
+ return to_object
+
+
+def _CustomCodeExecutionSpec_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["evaluation_function"]) is not None:
+ setv(
+ to_object,
+ ["evaluationFunction"],
+ getv(from_object, ["evaluation_function"]),
+ )
+
+ if getv(from_object, ["remote_custom_function"]) is not None:
+ setv(
+ to_object,
+ ["evaluation_function"],
+ getv(from_object, ["remote_custom_function"]),
+ )
+
+ return to_object
+
+
+def _DeleteEvaluationMetricParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metric_resource_name"]) is not None:
+ setv(
+ to_object,
+ ["_url", "evaluation_metric"],
+ getv(from_object, ["metric_resource_name"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _EvaluateInstancesRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["bleu_input"]) is not None:
+ setv(to_object, ["bleuInput"], getv(from_object, ["bleu_input"]))
+
+ if getv(from_object, ["exact_match_input"]) is not None:
+ setv(to_object, ["exactMatchInput"], getv(from_object, ["exact_match_input"]))
+
+ if getv(from_object, ["rouge_input"]) is not None:
+ setv(to_object, ["rougeInput"], getv(from_object, ["rouge_input"]))
+
+ if getv(from_object, ["pointwise_metric_input"]) is not None:
+ setv(
+ to_object,
+ ["pointwiseMetricInput"],
+ getv(from_object, ["pointwise_metric_input"]),
+ )
+
+ if getv(from_object, ["pairwise_metric_input"]) is not None:
+ setv(
+ to_object,
+ ["pairwiseMetricInput"],
+ getv(from_object, ["pairwise_metric_input"]),
+ )
+
+ if getv(from_object, ["tool_call_valid_input"]) is not None:
+ setv(
+ to_object,
+ ["toolCallValidInput"],
+ getv(from_object, ["tool_call_valid_input"]),
+ )
+
+ if getv(from_object, ["tool_name_match_input"]) is not None:
+ setv(
+ to_object,
+ ["toolNameMatchInput"],
+ getv(from_object, ["tool_name_match_input"]),
+ )
+
+ if getv(from_object, ["tool_parameter_key_match_input"]) is not None:
+ setv(
+ to_object,
+ ["toolParameterKeyMatchInput"],
+ getv(from_object, ["tool_parameter_key_match_input"]),
+ )
+
+ if getv(from_object, ["tool_parameter_kv_match_input"]) is not None:
+ setv(
+ to_object,
+ ["toolParameterKvMatchInput"],
+ getv(from_object, ["tool_parameter_kv_match_input"]),
+ )
+
+ if getv(from_object, ["rubric_based_metric_input"]) is not None:
+ setv(
+ to_object,
+ ["rubricBasedMetricInput"],
+ _RubricBasedMetricInput_to_vertex(
+ getv(from_object, ["rubric_based_metric_input"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["autorater_config"]) is not None:
+ setv(to_object, ["autoraterConfig"], getv(from_object, ["autorater_config"]))
+
+ if getv(from_object, ["metrics"]) is not None:
+ setv(
+ to_object,
+ ["metrics"],
+ [item for item in t.t_metrics(getv(from_object, ["metrics"]))],
+ )
+
+ if getv(from_object, ["instance"]) is not None:
+ setv(
+ to_object,
+ ["instance"],
+ _EvaluationInstance_to_vertex(getv(from_object, ["instance"]), to_object),
+ )
+
+ if getv(from_object, ["metric_sources"]) is not None:
+ setv(
+ to_object,
+ ["metricSources"],
+ [
+ item
+ for item in t.t_metric_sources(getv(from_object, ["metric_sources"]))
+ ],
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _EvaluationInstance_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["prompt"]) is not None:
+ setv(to_object, ["prompt"], getv(from_object, ["prompt"]))
+
+ if getv(from_object, ["response"]) is not None:
+ setv(to_object, ["response"], getv(from_object, ["response"]))
+
+ if getv(from_object, ["reference"]) is not None:
+ setv(to_object, ["reference"], getv(from_object, ["reference"]))
+
+ if getv(from_object, ["other_data"]) is not None:
+ setv(to_object, ["otherData"], getv(from_object, ["other_data"]))
+
+ if getv(from_object, ["agent_data"]) is not None:
+ setv(to_object, ["agent_eval_data"], getv(from_object, ["agent_data"]))
+
+ if getv(from_object, ["rubric_groups"]) is not None:
+ setv(to_object, ["rubricGroups"], getv(from_object, ["rubric_groups"]))
+
+ return to_object
+
+
+def _EvaluationMetric_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["displayName"]) is not None:
+ setv(to_object, ["display_name"], getv(from_object, ["displayName"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["metric"]) is not None:
+ setv(
+ to_object,
+ ["metric"],
+ _UnifiedMetric_from_vertex(getv(from_object, ["metric"]), to_object),
+ )
+
+ return to_object
+
+
+def _EvaluationRunConfig_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metrics"]) is not None:
+ setv(
+ to_object,
+ ["metrics"],
+ [
+ _EvaluationRunMetric_from_vertex(item, to_object)
+ for item in getv(from_object, ["metrics"])
+ ],
+ )
+
+ if getv(from_object, ["outputConfig"]) is not None:
+ setv(to_object, ["output_config"], getv(from_object, ["outputConfig"]))
+
+ if getv(from_object, ["autoraterConfig"]) is not None:
+ setv(to_object, ["autorater_config"], getv(from_object, ["autoraterConfig"]))
+
+ if getv(from_object, ["promptTemplate"]) is not None:
+ setv(to_object, ["prompt_template"], getv(from_object, ["promptTemplate"]))
+
+ if getv(from_object, ["lossAnalysisConfig"]) is not None:
+ setv(
+ to_object,
+ ["loss_analysis_config"],
+ [item for item in getv(from_object, ["lossAnalysisConfig"])],
+ )
+
+ if getv(from_object, ["allowCrossRegionModel"]) is not None:
+ setv(
+ to_object,
+ ["allow_cross_region_model"],
+ getv(from_object, ["allowCrossRegionModel"]),
+ )
+
+ return to_object
+
+
+def _EvaluationRunConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metrics"]) is not None:
+ setv(
+ to_object,
+ ["metrics"],
+ [
+ _EvaluationRunMetric_to_vertex(item, to_object)
+ for item in getv(from_object, ["metrics"])
+ ],
+ )
+
+ if getv(from_object, ["output_config"]) is not None:
+ setv(to_object, ["outputConfig"], getv(from_object, ["output_config"]))
+
+ if getv(from_object, ["autorater_config"]) is not None:
+ setv(to_object, ["autoraterConfig"], getv(from_object, ["autorater_config"]))
+
+ if getv(from_object, ["prompt_template"]) is not None:
+ setv(to_object, ["promptTemplate"], getv(from_object, ["prompt_template"]))
+
+ if getv(from_object, ["loss_analysis_config"]) is not None:
+ setv(
+ to_object,
+ ["lossAnalysisConfig"],
+ [item for item in getv(from_object, ["loss_analysis_config"])],
+ )
+
+ if getv(from_object, ["allow_cross_region_model"]) is not None:
+ setv(
+ to_object,
+ ["allowCrossRegionModel"],
+ getv(from_object, ["allow_cross_region_model"]),
+ )
+
+ return to_object
+
+
+def _EvaluationRunInferenceConfig_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["agentConfig"]) is not None:
+ setv(to_object, ["agent_config"], getv(from_object, ["agentConfig"]))
+
+ if getv(from_object, ["model"]) is not None:
+ setv(to_object, ["model"], getv(from_object, ["model"]))
+
+ if getv(from_object, ["promptTemplate"]) is not None:
+ setv(to_object, ["prompt_template"], getv(from_object, ["promptTemplate"]))
+
+ if getv(from_object, ["agentRunConfig"]) is not None:
+ setv(to_object, ["agent_run_config"], getv(from_object, ["agentRunConfig"]))
+
+ if getv(from_object, ["agents"]) is not None:
+ setv(to_object, ["agent_configs"], getv(from_object, ["agents"]))
+
+ return to_object
+
+
+def _EvaluationRunInferenceConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["agent_config"]) is not None:
+ setv(to_object, ["agentConfig"], getv(from_object, ["agent_config"]))
+
+ if getv(from_object, ["model"]) is not None:
+ setv(to_object, ["model"], getv(from_object, ["model"]))
+
+ if getv(from_object, ["prompt_template"]) is not None:
+ setv(to_object, ["promptTemplate"], getv(from_object, ["prompt_template"]))
+
+ if getv(from_object, ["agent_run_config"]) is not None:
+ setv(to_object, ["agentRunConfig"], getv(from_object, ["agent_run_config"]))
+
+ if getv(from_object, ["agent_configs"]) is not None:
+ setv(to_object, ["agents"], getv(from_object, ["agent_configs"]))
+
+ return to_object
+
+
+def _EvaluationRunMetric_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metric"]) is not None:
+ setv(to_object, ["metric"], getv(from_object, ["metric"]))
+
+ if getv(from_object, ["metricResourceName"]) is not None:
+ setv(
+ to_object,
+ ["metric_resource_name"],
+ getv(from_object, ["metricResourceName"]),
+ )
+
+ if getv(from_object, ["metricConfig"]) is not None:
+ setv(
+ to_object,
+ ["metric_config"],
+ _UnifiedMetric_from_vertex(getv(from_object, ["metricConfig"]), to_object),
+ )
+
+ return to_object
+
+
+def _EvaluationRunMetric_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metric"]) is not None:
+ setv(to_object, ["metric"], getv(from_object, ["metric"]))
+
+ if getv(from_object, ["metric_resource_name"]) is not None:
+ setv(
+ to_object,
+ ["metricResourceName"],
+ getv(from_object, ["metric_resource_name"]),
+ )
+
+ if getv(from_object, ["metric_config"]) is not None:
+ setv(
+ to_object,
+ ["metricConfig"],
+ _UnifiedMetric_to_vertex(getv(from_object, ["metric_config"]), to_object),
+ )
+
+ return to_object
+
+
+def _EvaluationRun_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["displayName"]) is not None:
+ setv(to_object, ["display_name"], getv(from_object, ["displayName"]))
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["createTime"]) is not None:
+ setv(to_object, ["create_time"], getv(from_object, ["createTime"]))
+
+ if getv(from_object, ["completionTime"]) is not None:
+ setv(to_object, ["completion_time"], getv(from_object, ["completionTime"]))
+
+ if getv(from_object, ["state"]) is not None:
+ setv(to_object, ["state"], getv(from_object, ["state"]))
+
+ if getv(from_object, ["evaluationSetSnapshot"]) is not None:
+ setv(
+ to_object,
+ ["evaluation_set_snapshot"],
+ getv(from_object, ["evaluationSetSnapshot"]),
+ )
+
+ if getv(from_object, ["error"]) is not None:
+ setv(to_object, ["error"], getv(from_object, ["error"]))
+
+ if getv(from_object, ["dataSource"]) is not None:
+ setv(to_object, ["data_source"], getv(from_object, ["dataSource"]))
+
+ if getv(from_object, ["evaluationResults"]) is not None:
+ setv(
+ to_object,
+ ["evaluation_run_results"],
+ getv(from_object, ["evaluationResults"]),
+ )
+
+ if getv(from_object, ["evaluationConfig"]) is not None:
+ setv(
+ to_object,
+ ["evaluation_config"],
+ _EvaluationRunConfig_from_vertex(
+ getv(from_object, ["evaluationConfig"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["inferenceConfigs"]) is not None:
+ setv(
+ to_object,
+ ["inference_configs"],
+ {
+ k: _EvaluationRunInferenceConfig_from_vertex(v, to_object)
+ for k, v in getv(from_object, ["inferenceConfigs"]).items()
+ },
+ )
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["analysisConfigs"]) is not None:
+ setv(
+ to_object,
+ ["analysis_configs"],
+ [item for item in getv(from_object, ["analysisConfigs"])],
+ )
+
+ return to_object
+
+
+def _GenerateInstanceRubricsRequest_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["contents"]) is not None:
+ setv(to_object, ["contents"], getv(from_object, ["contents"]))
+
+ if getv(from_object, ["predefined_rubric_generation_spec"]) is not None:
+ setv(
+ to_object,
+ ["predefinedRubricGenerationSpec"],
+ getv(from_object, ["predefined_rubric_generation_spec"]),
+ )
+
+ if getv(from_object, ["rubric_generation_spec"]) is not None:
+ setv(
+ to_object,
+ ["rubricGenerationSpec"],
+ getv(from_object, ["rubric_generation_spec"]),
+ )
+
+ if getv(from_object, ["metric_resource_name"]) is not None:
+ setv(
+ to_object,
+ ["metricResourceName"],
+ getv(from_object, ["metric_resource_name"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GenerateLossClustersParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["location"]) is not None:
+ setv(to_object, ["location"], getv(from_object, ["location"]))
+
+ if getv(from_object, ["evaluation_set"]) is not None:
+ setv(to_object, ["evaluationSet"], getv(from_object, ["evaluation_set"]))
+
+ if getv(from_object, ["inline_results"]) is not None:
+ setv(
+ to_object,
+ ["inlineResults", "evaluationResults"],
+ [
+ item
+ for item in t.t_inline_results(getv(from_object, ["inline_results"]))
+ ],
+ )
+
+ if getv(from_object, ["configs"]) is not None:
+ setv(to_object, ["configs"], [item for item in getv(from_object, ["configs"])])
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GenerateUserScenariosParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["location"]) is not None:
+ setv(to_object, ["location"], getv(from_object, ["location"]))
+
+ if getv(from_object, ["agents"]) is not None:
+ setv(to_object, ["agents"], getv(from_object, ["agents"]))
+
+ if getv(from_object, ["root_agent_id"]) is not None:
+ setv(to_object, ["rootAgentId"], getv(from_object, ["root_agent_id"]))
+
+ if getv(from_object, ["user_scenario_generation_config"]) is not None:
+ setv(
+ to_object,
+ ["userScenarioGenerationConfig"],
+ t.t_user_scenario_generation_config(
+ getv(from_object, ["user_scenario_generation_config"])
+ ),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ if getv(from_object, ["allow_cross_region_model"]) is not None:
+ setv(
+ to_object,
+ ["allowCrossRegionModel"],
+ getv(from_object, ["allow_cross_region_model"]),
+ )
+
+ return to_object
+
+
+def _GetEvaluationItemParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetEvaluationMetricParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metric_resource_name"]) is not None:
+ setv(
+ to_object,
+ ["_url", "evaluation_metric"],
+ getv(from_object, ["metric_resource_name"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetEvaluationRunParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetEvaluationSetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _ListEvaluationMetricsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ if getv(from_object, ["order_by"]) is not None:
+ setv(parent_object, ["_query", "orderBy"], getv(from_object, ["order_by"]))
+
+ return to_object
+
+
+def _ListEvaluationMetricsParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _ListEvaluationMetricsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _ListEvaluationMetricsResponse_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["sdkHttpResponse"]) is not None:
+ setv(to_object, ["sdk_http_response"], getv(from_object, ["sdkHttpResponse"]))
+
+ if getv(from_object, ["nextPageToken"]) is not None:
+ setv(to_object, ["next_page_token"], getv(from_object, ["nextPageToken"]))
+
+ if getv(from_object, ["evaluationMetrics"]) is not None:
+ setv(
+ to_object,
+ ["evaluation_metrics"],
+ [
+ _EvaluationMetric_from_vertex(item, to_object)
+ for item in getv(from_object, ["evaluationMetrics"])
+ ],
+ )
+
+ return to_object
+
+
+def _RubricBasedMetricInput_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metric_spec"]) is not None:
+ setv(
+ to_object,
+ ["metricSpec"],
+ _RubricBasedMetricSpec_to_vertex(
+ getv(from_object, ["metric_spec"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["instance"]) is not None:
+ setv(to_object, ["instance"], getv(from_object, ["instance"]))
+
+ return to_object
+
+
+def _RubricBasedMetricSpec_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["metric_prompt_template"]) is not None:
+ setv(
+ to_object,
+ ["metricPromptTemplate"],
+ getv(from_object, ["metric_prompt_template"]),
+ )
+
+ if getv(from_object, ["judge_autorater_config"]) is not None:
+ setv(
+ to_object,
+ ["judgeAutoraterConfig"],
+ getv(from_object, ["judge_autorater_config"]),
+ )
+
+ if getv(from_object, ["inline_rubrics"]) is not None:
+ setv(
+ to_object,
+ ["inline_rubrics", "rubrics"],
+ getv(from_object, ["inline_rubrics"]),
+ )
+
+ if getv(from_object, ["rubric_group_key"]) is not None:
+ setv(to_object, ["rubricGroupKey"], getv(from_object, ["rubric_group_key"]))
+
+ if getv(from_object, ["rubric_generation_spec"]) is not None:
+ setv(
+ to_object,
+ ["rubricGenerationSpec"],
+ getv(from_object, ["rubric_generation_spec"]),
+ )
+
+ return to_object
+
+
+def _UnifiedMetric_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["bleuSpec"]) is not None:
+ setv(to_object, ["bleu_spec"], getv(from_object, ["bleuSpec"]))
+
+ if getv(from_object, ["rougeSpec"]) is not None:
+ setv(to_object, ["rouge_spec"], getv(from_object, ["rougeSpec"]))
+
+ if getv(from_object, ["pointwiseMetricSpec"]) is not None:
+ setv(
+ to_object,
+ ["pointwise_metric_spec"],
+ getv(from_object, ["pointwiseMetricSpec"]),
+ )
+
+ if getv(from_object, ["llmBasedMetricSpec"]) is not None:
+ setv(
+ to_object,
+ ["llm_based_metric_spec"],
+ getv(from_object, ["llmBasedMetricSpec"]),
+ )
+
+ if getv(from_object, ["customCodeExecutionSpec"]) is not None:
+ setv(
+ to_object,
+ ["custom_code_execution_spec"],
+ _CustomCodeExecutionSpec_from_vertex(
+ getv(from_object, ["customCodeExecutionSpec"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["predefinedMetricSpec"]) is not None:
+ setv(
+ to_object,
+ ["predefined_metric_spec"],
+ getv(from_object, ["predefinedMetricSpec"]),
+ )
+
+ if getv(from_object, ["computationBasedMetricSpec"]) is not None:
+ setv(
+ to_object,
+ ["computation_based_metric_spec"],
+ getv(from_object, ["computationBasedMetricSpec"]),
+ )
+
+ return to_object
+
+
+def _UnifiedMetric_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["bleu_spec"]) is not None:
+ setv(to_object, ["bleuSpec"], getv(from_object, ["bleu_spec"]))
+
+ if getv(from_object, ["rouge_spec"]) is not None:
+ setv(to_object, ["rougeSpec"], getv(from_object, ["rouge_spec"]))
+
+ if getv(from_object, ["pointwise_metric_spec"]) is not None:
+ setv(
+ to_object,
+ ["pointwiseMetricSpec"],
+ getv(from_object, ["pointwise_metric_spec"]),
+ )
+
+ if getv(from_object, ["llm_based_metric_spec"]) is not None:
+ setv(
+ to_object,
+ ["llmBasedMetricSpec"],
+ getv(from_object, ["llm_based_metric_spec"]),
+ )
+
+ if getv(from_object, ["custom_code_execution_spec"]) is not None:
+ setv(
+ to_object,
+ ["customCodeExecutionSpec"],
+ _CustomCodeExecutionSpec_to_vertex(
+ getv(from_object, ["custom_code_execution_spec"]), to_object
+ ),
+ )
+
+ if getv(from_object, ["predefined_metric_spec"]) is not None:
+ setv(
+ to_object,
+ ["predefinedMetricSpec"],
+ getv(from_object, ["predefined_metric_spec"]),
+ )
+
+ if getv(from_object, ["computation_based_metric_spec"]) is not None:
+ setv(
+ to_object,
+ ["computationBasedMetricSpec"],
+ getv(from_object, ["computation_based_metric_spec"]),
+ )
+
+ return to_object
+
+
+class Evals(_api_module.BaseModule):
+
+ def _create_evaluation_item(
+ self,
+ *,
+ evaluation_item_type: str,
+ gcs_uri: str,
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationItemConfigOrDict] = None,
+ ) -> types.EvaluationItem:
+ """
+ Creates an EvaluationItem.
+ """
+
+ parameter_model = types._CreateEvaluationItemParameters(
+ evaluation_item_type=evaluation_item_type,
+ gcs_uri=gcs_uri,
+ display_name=display_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationItemParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationItems".format_map(request_url_dict)
+ else:
+ path = "evaluationItems"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationItem._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create_evaluation_metric(
+ self,
+ *,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ metric: Optional[types.MetricOrDict] = None,
+ config: Optional[types.CreateEvaluationMetricConfigOrDict] = None,
+ ) -> types.EvaluationMetric:
+ """
+ Creates an EvaluationMetric.
+ """
+
+ parameter_model = types._CreateEvaluationMetricParameters(
+ display_name=display_name,
+ description=description,
+ metric=metric,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationMetricParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationMetrics".format_map(request_url_dict)
+ else:
+ path = "evaluationMetrics"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationMetric_from_vertex(response_dict)
+
+ return_value = types.EvaluationMetric._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create_evaluation_run(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ data_source: types.EvaluationRunDataSourceOrDict,
+ evaluation_config: types.EvaluationRunConfigOrDict,
+ labels: Optional[dict[str, str]] = None,
+ inference_configs: Optional[
+ dict[str, types.EvaluationRunInferenceConfigOrDict]
+ ] = None,
+ config: Optional[types.CreateEvaluationRunConfigOrDict] = None,
+ analysis_configs: Optional[list[types.AnalysisConfigOrDict]] = None,
+ ) -> types.EvaluationRun:
+ """
+ Creates an EvaluationRun.
+ """
+
+ parameter_model = types._CreateEvaluationRunParameters(
+ name=name,
+ display_name=display_name,
+ data_source=data_source,
+ evaluation_config=evaluation_config,
+ labels=labels,
+ inference_configs=inference_configs,
+ config=config,
+ analysis_configs=analysis_configs,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationRunParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationRuns".format_map(request_url_dict)
+ else:
+ path = "evaluationRuns"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationRun_from_vertex(response_dict)
+
+ return_value = types.EvaluationRun._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create_evaluation_set(
+ self,
+ *,
+ evaluation_items: list[str],
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationSetConfigOrDict] = None,
+ ) -> types.EvaluationSet:
+ """
+ Creates an EvaluationSet.
+ """
+
+ parameter_model = types._CreateEvaluationSetParameters(
+ evaluation_items=evaluation_items,
+ display_name=display_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationSetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationSets".format_map(request_url_dict)
+ else:
+ path = "evaluationSets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationSet._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.DeleteEvaluationMetricConfigOrDict] = None,
+ ) -> types.DeleteEvaluationMetricOperation:
+ """
+ Deletes an EvaluationMetric.
+ """
+
+ parameter_model = types._DeleteEvaluationMetricParameters(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteEvaluationMetricParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{evaluation_metric}".format_map(request_url_dict)
+ else:
+ path = "{evaluation_metric}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteEvaluationMetricOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _evaluate_instances(
+ self,
+ *,
+ bleu_input: Optional[types.BleuInputOrDict] = None,
+ exact_match_input: Optional[types.ExactMatchInputOrDict] = None,
+ rouge_input: Optional[types.RougeInputOrDict] = None,
+ pointwise_metric_input: Optional[types.PointwiseMetricInputOrDict] = None,
+ pairwise_metric_input: Optional[types.PairwiseMetricInputOrDict] = None,
+ tool_call_valid_input: Optional[types.ToolCallValidInputOrDict] = None,
+ tool_name_match_input: Optional[types.ToolNameMatchInputOrDict] = None,
+ tool_parameter_key_match_input: Optional[
+ types.ToolParameterKeyMatchInputOrDict
+ ] = None,
+ tool_parameter_kv_match_input: Optional[
+ types.ToolParameterKVMatchInputOrDict
+ ] = None,
+ rubric_based_metric_input: Optional[types.RubricBasedMetricInputOrDict] = None,
+ autorater_config: Optional[genai_types.AutoraterConfigOrDict] = None,
+ metrics: Optional[list[types.MetricOrDict]] = None,
+ instance: Optional[types.EvaluationInstanceOrDict] = None,
+ metric_sources: Optional[list[types.MetricSourceOrDict]] = None,
+ config: Optional[types.EvaluateInstancesConfigOrDict] = None,
+ ) -> types.EvaluateInstancesResponse:
+ """
+ Evaluates instances based on a given metric.
+ """
+
+ parameter_model = types._EvaluateInstancesRequestParameters(
+ bleu_input=bleu_input,
+ exact_match_input=exact_match_input,
+ rouge_input=rouge_input,
+ pointwise_metric_input=pointwise_metric_input,
+ pairwise_metric_input=pairwise_metric_input,
+ tool_call_valid_input=tool_call_valid_input,
+ tool_name_match_input=tool_name_match_input,
+ tool_parameter_key_match_input=tool_parameter_key_match_input,
+ tool_parameter_kv_match_input=tool_parameter_kv_match_input,
+ rubric_based_metric_input=rubric_based_metric_input,
+ autorater_config=autorater_config,
+ metrics=metrics,
+ instance=instance,
+ metric_sources=metric_sources,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _EvaluateInstancesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":evaluateInstances".format_map(request_url_dict)
+ else:
+ path = ":evaluateInstances"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluateInstancesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _generate_user_scenarios(
+ self,
+ *,
+ location: Optional[str] = None,
+ agents: Optional[dict[str, evals_types.AgentConfigOrDict]] = None,
+ root_agent_id: Optional[str] = None,
+ user_scenario_generation_config: Optional[
+ evals_types.UserScenarioGenerationConfigOrDict
+ ] = None,
+ config: Optional[types.GenerateUserScenariosConfigOrDict] = None,
+ allow_cross_region_model: Optional[bool] = None,
+ ) -> types.GenerateUserScenariosResponse:
+ """
+ Generates user scenarios for agent evaluation.
+ """
+
+ parameter_model = types._GenerateUserScenariosParameters(
+ location=location,
+ agents=agents,
+ root_agent_id=root_agent_id,
+ user_scenario_generation_config=user_scenario_generation_config,
+ config=config,
+ allow_cross_region_model=allow_cross_region_model,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateUserScenariosParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":generateUserScenarios".format_map(request_url_dict)
+ else:
+ path = ":generateUserScenarios"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.GenerateUserScenariosResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _generate_loss_clusters(
+ self,
+ *,
+ location: Optional[str] = None,
+ evaluation_set: Optional[str] = None,
+ inline_results: Optional[list[types.EvaluationResultOrDict]] = None,
+ configs: Optional[list[types.LossAnalysisConfigOrDict]] = None,
+ config: Optional[types.GenerateLossClustersConfigOrDict] = None,
+ ) -> types.GenerateLossClustersOperation:
+ """
+ Generates loss clusters from evaluation results.
+ """
+
+ parameter_model = types._GenerateLossClustersParameters(
+ location=location,
+ evaluation_set=evaluation_set,
+ inline_results=inline_results,
+ configs=configs,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateLossClustersParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":generateLossClusters".format_map(request_url_dict)
+ else:
+ path = ":generateLossClusters"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.GenerateLossClustersOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _generate_rubrics(
+ self,
+ *,
+ contents: list[genai_types.ContentOrDict],
+ predefined_rubric_generation_spec: Optional[
+ genai_types.PredefinedMetricSpecOrDict
+ ] = None,
+ rubric_generation_spec: Optional[genai_types.RubricGenerationSpecOrDict] = None,
+ metric_resource_name: Optional[str] = None,
+ config: Optional[types.RubricGenerationConfigOrDict] = None,
+ ) -> types.GenerateInstanceRubricsResponse:
+ """
+ Generates rubrics for a given prompt.
+ """
+
+ parameter_model = types._GenerateInstanceRubricsRequest(
+ contents=contents,
+ predefined_rubric_generation_spec=predefined_rubric_generation_spec,
+ rubric_generation_spec=rubric_generation_spec,
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateInstanceRubricsRequest_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":generateInstanceRubrics".format_map(request_url_dict)
+ else:
+ path = ":generateInstanceRubrics"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.GenerateInstanceRubricsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.GetEvaluationMetricConfigOrDict] = None,
+ ) -> types.EvaluationMetric:
+ """
+ Retrieves an EvaluationMetric from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationMetricParameters(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationMetricParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{evaluation_metric}".format_map(request_url_dict)
+ else:
+ path = "{evaluation_metric}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationMetric_from_vertex(response_dict)
+
+ return_value = types.EvaluationMetric._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_evaluation_run(
+ self, *, name: str, config: Optional[types.GetEvaluationRunConfigOrDict] = None
+ ) -> types.EvaluationRun:
+ """
+ Retrieves an EvaluationRun from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationRunParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationRunParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationRuns/{name}".format_map(request_url_dict)
+ else:
+ path = "evaluationRuns/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationRun_from_vertex(response_dict)
+
+ return_value = types.EvaluationRun._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_evaluation_set(
+ self, *, name: str, config: Optional[types.GetEvaluationSetConfigOrDict] = None
+ ) -> types.EvaluationSet:
+ """
+ Retrieves an EvaluationSet from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationSetParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationSetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationSets/{name}".format_map(request_url_dict)
+ else:
+ path = "evaluationSets/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationSet._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_evaluation_item(
+ self, *, name: str, config: Optional[types.GetEvaluationItemConfigOrDict] = None
+ ) -> types.EvaluationItem:
+ """
+ Retrieves an EvaluationItem from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationItemParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationItemParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationItems/{name}".format_map(request_url_dict)
+ else:
+ path = "evaluationItems/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationItem._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list_evaluation_metrics(
+ self, *, config: Optional[types.ListEvaluationMetricsConfigOrDict] = None
+ ) -> types.ListEvaluationMetricsResponse:
+ """
+ Lists EvaluationMetrics.
+ """
+
+ parameter_model = types._ListEvaluationMetricsParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListEvaluationMetricsParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationMetrics".format_map(request_url_dict)
+ else:
+ path = "evaluationMetrics"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _ListEvaluationMetricsResponse_from_vertex(response_dict)
+
+ return_value = types.ListEvaluationMetricsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def evaluate_instances(
+ self,
+ *,
+ metric_config: types._EvaluateInstancesRequestParameters,
+ ) -> types.EvaluateInstancesResponse:
+ """Evaluates an instance of a model."""
+
+ if isinstance(metric_config, types._EvaluateInstancesRequestParameters):
+ metric_config = metric_config.model_dump() # type: ignore[assignment]
+ else:
+ metric_config = dict(metric_config)
+
+ return self._evaluate_instances(
+ **metric_config,
+ )
+
+ def run_inference(
+ self,
+ *,
+ src: Union[str, pd.DataFrame, types.EvaluationDataset],
+ model: Optional[Union[str, Callable[[Any], Any]]] = None,
+ agent: Optional[Union[str, types.AgentEngine, LlmAgent]] = None,
+ location: Optional[str] = None,
+ config: Optional[types.EvalRunInferenceConfigOrDict] = None,
+ ) -> types.EvaluationDataset:
+ """Runs inference on a dataset for evaluation.
+
+ Args:
+ src: The source of the dataset. Can be a string (path to a local file,
+ a GCS path, or a BigQuery table), a Pandas DataFrame, or an
+ EvaluationDataset object. An EvaluationDataset may have either
+ ``eval_dataset_df`` or ``eval_cases`` populated. When
+ ``eval_cases`` with ``agent_data`` is provided, the last user
+ event in the turns is used as the current prompt and prior
+ events are replayed as session history for local ADK agents.
+ model: Optional type is experimental and may change in future versions.
+ The model to use for inference, optional for agent evaluations.
+ - For Google Gemini models, provide the model name string (e.g., "gemini-2.5-flash").
+ - For third-party models via LiteLLM, use the format "provider/model_name"
+ (e.g., "openai/gpt-4o"). Ensure the necessary API key (e.g., OPENAI_API_KEY)
+ is set as an environment variable.
+ - For custom logic, provide a callable function that accepts a prompt and
+ returns a response.
+ agent: This field is experimental and may change in future versions
+ The agent engine used or local agent to run agent, optional for non-agent evaluations.
+ - agent engine resource name in str type, with format
+ `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine_id}`,
+ run_inference will fetch the agent engine from the resource name.
+ - Or `types.AgentEngine` object.
+ - Or ADK agent in LlMAgent type.
+ location: The location to use for the inference. If not specified, the
+ location configured in the client will be used. If specified,
+ this will override the location set in `agentplatform.Client` only
+ for this API call.
+ config: The optional configuration for the inference run. Must be a dict or
+ `types.EvalRunInferenceConfig` type.
+ - dest: The destination path for storage of the inference results.
+ - prompt_template: The template string to use for constructing prompts.
+ - generate_content_config: The config for the Gemini generate content call.
+ - allow_cross_region_model: Opt-in flag to authorize cross-region routing for LLM models.
+
+ Returns:
+ The evaluation dataset.
+ """
+ if not config:
+ config = types.EvalRunInferenceConfig()
+ if isinstance(config, dict):
+ config = types.EvalRunInferenceConfig.model_validate(config)
+
+ if isinstance(src, types.EvaluationDataset):
+ if src.eval_dataset_df is not None:
+ src = src.eval_dataset_df
+ elif src.eval_cases:
+ src = _evals_common._eval_cases_to_dataframe(src.eval_cases)
+ else:
+ raise ValueError(
+ "EvaluationDataset must have eval_dataset_df or eval_cases"
+ " populated."
+ )
+
+ agent_engine_instance = None
+ agent_instance = None
+ if agent:
+ if isinstance(agent, str) or isinstance(agent, types.AgentEngine):
+ agent_engine_instance = agent
+ else:
+ agent_instance = agent
+
+ return _evals_common._execute_inference( # type: ignore[no-any-return]
+ api_client=self._api_client,
+ model=model,
+ agent_engine=agent_engine_instance,
+ agent=agent_instance,
+ src=src,
+ dest=config.dest,
+ prompt_template=config.prompt_template,
+ location=location,
+ config=config.generate_content_config,
+ user_simulator_config=getattr(config, "user_simulator_config", None),
+ allow_cross_region_model=getattr(config, "allow_cross_region_model", False),
+ )
+
+ def evaluate(
+ self,
+ *,
+ dataset: Union[
+ pd.DataFrame,
+ types.EvaluationDatasetOrDict,
+ list[types.EvaluationDatasetOrDict],
+ ],
+ metrics: Optional[list[types.MetricOrDict]] = None,
+ location: Optional[str] = None,
+ config: Optional[types.EvaluateMethodConfigOrDict] = None,
+ **kwargs: Any,
+ ) -> types.EvaluationResult:
+ """Evaluates candidate responses in the provided dataset(s) using the specified metrics.
+
+ Args:
+ dataset: The dataset(s) to evaluate. Can be a pandas DataFrame, a single
+ `types.EvaluationDataset` or a list of `types.EvaluationDataset`.
+ metrics: The list of metrics to use for evaluation.
+ location: The location to use for the evaluation service. If not specified,
+ the location configured in the client will be used. If specified,
+ this will override the location set in `agentplatform.Client` only for
+ this API call.
+ config: Optional configuration for the evaluation. Can be a dictionary or a
+ `types.EvaluateMethodConfig` object.
+ - dataset_schema: Schema to use for the dataset. If not specified, the
+ dataset schema will be inferred from the dataset automatically.
+ - dest: Destination path for storing evaluation results.
+ - evaluation_service_qps: The rate limit (queries per second) for
+ calls to the evaluation service. Defaults to 10. Increase this
+ value if your project has a higher EvaluateInstances API quota.
+ **kwargs: Extra arguments to pass to evaluation, such as `agent_info`.
+
+ Returns:
+ The evaluation result.
+ """
+ if not config:
+ config = types.EvaluateMethodConfig()
+ if isinstance(config, dict):
+ config = types.EvaluateMethodConfig.model_validate(config)
+
+ if isinstance(dataset, pd.DataFrame):
+ dataset = types.EvaluationDataset(eval_dataset_df=dataset)
+
+ if isinstance(dataset, list):
+ dataset = [
+ (
+ types.EvaluationDataset.model_validate(ds_item)
+ if isinstance(ds_item, dict)
+ else ds_item
+ )
+ for ds_item in dataset
+ ]
+ else:
+ if isinstance(dataset, dict):
+ dataset = types.EvaluationDataset.model_validate(dataset)
+ if metrics is None:
+ metrics = [types.Metric(name="general_quality_v1")]
+
+ # TODO: Replace kwargs with agent_info after the experimental phase.
+ if kwargs:
+ logger.warning(
+ "`kwargs` attribute in `evaluate` method is experimental and may change in future versions."
+ )
+
+ return _evals_common._execute_evaluation(
+ api_client=self._api_client,
+ dataset=dataset,
+ metrics=metrics,
+ dataset_schema=config.dataset_schema,
+ dest=config.dest,
+ location=location,
+ evaluation_service_qps=getattr(config, "evaluation_service_qps", None),
+ **kwargs,
+ )
+
+ def batch_evaluate(
+ self,
+ *,
+ dataset: types.EvaluationDatasetOrDict,
+ metrics: list[types.MetricOrDict],
+ dest: str,
+ config: Optional[types.EvaluateDatasetConfigOrDict] = None,
+ ) -> types.EvaluateDatasetOperation:
+ """Evaluates a dataset based on a set of given metrics."""
+
+ resolved_metrics = _evals_common._resolve_metrics(metrics, self._api_client)
+ output_config = genai_types.OutputConfig(
+ gcs_destination=genai_types.GcsDestination(output_uri_prefix=dest)
+ )
+ parameter_model = types.EvaluateDatasetRequestParameters(
+ dataset=dataset,
+ metrics=resolved_metrics,
+ output_config=output_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError("This method is only supported in the Vertex AI client.")
+ else:
+ request_dict = _evals_utils.BatchEvaluateRequestPreparer.EvaluateDatasetRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":evaluateDataset".format_map(request_url_dict)
+ else:
+ path = ":evaluateDataset"
+
+ request_dict = _evals_utils.BatchEvaluateRequestPreparer.prepare_metric_payload(
+ request_dict, resolved_metrics
+ )
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = "" if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _evals_utils.BatchEvaluateRequestPreparer.EvaluateDatasetOperation_from_vertex(
+ response_dict
+ )
+
+ return_value = types.EvaluateDatasetOperation._from_response(
+ response=response_dict, kwargs=parameter_model.model_dump()
+ )
+ self._api_client._verify_response(return_value)
+
+ return return_value
+
+ def generate_rubrics(
+ self,
+ *,
+ src: Union[str, "pd.DataFrame", types.EvaluationDataset],
+ rubric_group_name: str,
+ prompt_template: Optional[str] = None,
+ generator_model_config: Optional["genai_types.AutoraterConfigOrDict"] = None,
+ rubric_content_type: Optional["types.RubricContentType"] = None,
+ rubric_type_ontology: Optional[list[str]] = None,
+ predefined_spec_name: Optional[Union[str, "types.PrebuiltMetric"]] = None,
+ metric_spec_parameters: Optional[dict[str, Any]] = None,
+ metric: Optional[types.MetricOrDict] = None,
+ config: Optional[types.RubricGenerationConfigOrDict] = None,
+ ) -> types.EvaluationDataset:
+ """Generates rubrics for each prompt in the source and adds them as a new column
+ structured as a dictionary.
+
+ You can generate rubrics by providing either:
+ 1. A `metric` to use a pre-registered metric resource.
+ 2. A `predefined_spec_name` to use a Vertex AI backend recipe.
+ 3. A `prompt_template` along with other configuration parameters
+ (`generator_model_config`, `rubric_content_type`, `rubric_type_ontology`)
+ for custom rubric generation.
+ with `metric` taking precedence over `predefined_spec_name`,
+ and `predefined_spec_name` taking precedence over `prompt_template`
+
+ These two modes are mutually exclusive.
+
+ Args:
+ src: The source of the prompts. Can be a string (path to a local
+ file, a GCS path, or a BigQuery table), a Pandas DataFrame, or
+ an EvaluationDataset object. The loaded data must contain either
+ a 'prompt' column (for text) or a 'request' column (for text or
+ multimodal Gemini Content).
+ rubric_group_name: Name for the key within the dictionary in the new
+ column.
+ prompt_template: Optional. Template for the rubric generation prompt. Used for
+ custom rubric generation. Mutually exclusive with `predefined_spec_name`.
+ If using a 'prompt' column, use {prompt} as the placeholder. If using a
+ 'request' column, this template is passed to the service along
+ with the content.
+ generator_model_config: Optional. Configuration for the model used
+ in custom rubric generation. Only used if `prompt_template` is provided.
+ e.g., {"autorater_model": "gemini-2.5-flash"}.
+ rubric_content_type: Optional. The type of rubric content to be
+ generated. Only used if `prompt_template` is provided.
+ rubric_type_ontology: Optional. A pre-defined list of allowed types
+ for generated rubrics. Only used if `prompt_template` is provided.
+ predefined_spec_name: Optional. The name of a Predefined Metric to use
+ for rubric generation (e.g., "general_quality_v1") or a types.PrebuiltMetric object.
+ Mutually exclusive with `prompt_template` and its related parameters.
+ metric_spec_parameters: Optional. Parameters for the Predefined Metric,
+ used to customize rubric generation. Only used if `predefined_spec_name` is set.
+ Example: {"guidelines": ["The response must be in Japanese."]}
+ metric: Optional. A types.Metric object containing a metric_resource_name,
+ or a resource name string. If provided, this will take precedence over
+ predefined_spec_name and prompt_template.
+ config: Optional. Configuration for the rubric generation process.
+
+ Returns:
+ An `EvaluationDataset` with an added column named `rubric_groups` in its
+ `eval_dataset_df`. Each cell in this column contains a dictionary like:
+ {rubric_group_name: [list[Rubric]]}.
+ """
+ if isinstance(src, types.EvaluationDataset):
+ if src.eval_dataset_df is not None:
+ prompts_df = src.eval_dataset_df
+ elif src.eval_cases:
+ prompts_df = _evals_common._eval_cases_to_dataframe(src.eval_cases)
+ else:
+ raise ValueError(
+ "EvaluationDataset must have eval_dataset_df or eval_cases"
+ " populated."
+ )
+ elif isinstance(src, (str, pd.DataFrame)):
+ try:
+ prompts_df = _evals_common._load_dataframe(self._api_client, src)
+ except Exception as e:
+ raise ValueError(
+ f"Failed to load prompt dataset from source: {src}. Error: {e}"
+ )
+ else:
+ raise TypeError(
+ "Unsupported type for src. Must be str, pd.DataFrame, or types.EvaluationDataset."
+ )
+
+ if "prompt" not in prompts_df.columns and "request" not in prompts_df.columns:
+ raise ValueError("Loaded dataset must have a 'prompt' or 'request' column.")
+ if not rubric_group_name:
+ raise ValueError("rubric_group_name cannot be empty.")
+
+ input_column = "request" if "request" in prompts_df.columns else "prompt"
+ logger.info(
+ "Generating rubrics for %d prompts from column '%s', group: '%s'...",
+ len(prompts_df),
+ input_column,
+ rubric_group_name,
+ )
+ all_rubric_groups: list[dict[str, list[types.Rubric]]] = []
+
+ actual_metric_resource_name = None
+ if metric:
+ if isinstance(metric, str) and metric.startswith("projects/"):
+ actual_metric_resource_name = metric
+ else:
+ metric_obj = (
+ types.Metric.model_validate(metric)
+ if isinstance(metric, dict)
+ else metric
+ )
+ actual_metric_resource_name = getattr(
+ metric_obj, "metric_resource_name", None
+ )
+ if not actual_metric_resource_name:
+ raise ValueError(
+ "The provided Metric object must have metric_resource_name set."
+ )
+
+ rubric_gen_spec = None
+ predefined_spec = None
+
+ if actual_metric_resource_name:
+ # Precedence: Registered metric resource overrides everything else.
+ predefined_spec = None
+ rubric_gen_spec = None
+ elif predefined_spec_name:
+ if prompt_template:
+ logger.warning(
+ "prompt_template is ignored when predefined_spec_name is provided."
+ )
+ if generator_model_config:
+ logger.warning(
+ "generator_model_config is ignored when predefined_spec_name is provided."
+ )
+ if rubric_content_type:
+ logger.warning(
+ "rubric_content_type is ignored when predefined_spec_name is provided."
+ )
+ if rubric_type_ontology:
+ logger.warning(
+ "rubric_type_ontology is ignored when predefined_spec_name is provided."
+ )
+
+ if isinstance(predefined_spec_name, str):
+ actual_predefined_spec_name = predefined_spec_name
+ elif hasattr(
+ predefined_spec_name, "resolve"
+ ): # Check if it's LazyLoadedPrebuiltMetric
+ try:
+ resolved_metric = predefined_spec_name.resolve(self._api_client)
+ actual_predefined_spec_name = resolved_metric.name
+ except Exception as e:
+ raise ValueError(f"Failed to resolve PrebuiltMetric: {e}")
+ else:
+ raise TypeError(
+ "predefined_spec_name must be a string or types.PrebuiltMetric"
+ )
+
+ if not actual_predefined_spec_name:
+ raise ValueError(
+ "Could not determine metric_spec_name from predefined_spec_name"
+ )
+
+ predefined_spec = genai_types.PredefinedMetricSpec(
+ metric_spec_name=actual_predefined_spec_name,
+ metric_spec_parameters=metric_spec_parameters,
+ )
+ elif prompt_template:
+ if metric_spec_parameters:
+ logger.warning(
+ "metric_spec_parameters is ignored when prompt_template is provided."
+ )
+ spec_dict = {
+ "prompt_template": prompt_template,
+ "rubric_content_type": rubric_content_type,
+ "rubric_type_ontology": rubric_type_ontology,
+ "generator_model_config": generator_model_config,
+ }
+ spec_dict = {k: v for k, v in spec_dict.items() if v is not None}
+ rubric_gen_spec = genai_types.RubricGenerationSpec.model_validate(spec_dict)
+ else:
+ raise ValueError(
+ "Either metric, predefined_spec_name or prompt_template must be provided."
+ )
+
+ for _, row in prompts_df.iterrows():
+ input_data = row[input_column]
+ if isinstance(input_data, str):
+ contents = [
+ genai_types.Content(parts=[genai_types.Part(text=input_data)])
+ ]
+ elif isinstance(input_data, list):
+ contents = input_data
+ else:
+ logger.warning(
+ f"Skipping row: Unexpected input format in column '{input_column}'."
+ )
+ all_rubric_groups.append({rubric_group_name: []})
+ continue
+
+ try:
+ response = self._generate_rubrics(
+ contents=contents,
+ rubric_generation_spec=rubric_gen_spec,
+ predefined_rubric_generation_spec=predefined_spec,
+ metric_resource_name=actual_metric_resource_name,
+ config=config,
+ )
+ rubric_group = {rubric_group_name: response.generated_rubrics}
+ all_rubric_groups.append(rubric_group)
+ except Exception as e:
+ logger.error(
+ "Rubric generation failed for input: %s... Error: %s",
+ str(input_data)[:50],
+ e,
+ exc_info=True,
+ )
+ all_rubric_groups.append({rubric_group_name: []})
+
+ prompts_with_rubrics = prompts_df.copy()
+ prompts_with_rubrics["rubric_groups"] = all_rubric_groups
+ logger.info(
+ f"Rubric generation complete. Added column 'rubric_groups' with key '{rubric_group_name}'."
+ )
+ return types.EvaluationDataset(eval_dataset_df=prompts_with_rubrics)
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_run module is experimental, "
+ "and may change in future versions."
+ )
+ def get_evaluation_run(
+ self,
+ *,
+ name: str,
+ include_evaluation_items: bool = False,
+ config: Optional[types.GetEvaluationRunConfigOrDict] = None,
+ ) -> types.EvaluationRun:
+ """Retrieves an EvaluationRun from the resource name.
+ Args:
+ name: The resource name of the EvaluationRun. Format:
+ `projects/{project}/locations/{location}/evaluationRuns/{evaluation_run}`
+ include_evaluation_items: Whether to include the evaluation items in the
+ response.
+ config: The optional configuration for the evaluation run. Must be a dict or
+ `types.GetEvaluationRunConfigOrDict` type.
+
+ Returns:
+ The evaluation run.
+ Raises:
+ ValueError: If the name is empty or invalid.
+ """
+ if not name:
+ raise ValueError("name cannot be empty.")
+ if name.startswith("projects/"):
+ name = name.split("/")[-1]
+ result = self._get_evaluation_run(name=name, config=config)
+ if include_evaluation_items:
+ eval_result, eval_item_map = _evals_common._convert_evaluation_run_results(
+ self._api_client,
+ result.evaluation_run_results,
+ result.inference_configs,
+ )
+ result.evaluation_item_results = eval_result
+ # Bypass pydantic validation (extra='forbid') for this internal field.
+ object.__setattr__(result, "_eval_item_map", eval_item_map)
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_run module is experimental, "
+ "and may change in future versions."
+ )
+ def create_evaluation_run(
+ self,
+ *,
+ dataset: Union[types.EvaluationRunDataSource, types.EvaluationDataset],
+ dest: str,
+ metrics: list[types.EvaluationRunMetricOrDict],
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ agent_info: Optional[evals_types.AgentInfoOrDict] = None,
+ agent: Optional[str] = None,
+ user_simulator_config: Optional[evals_types.UserSimulatorConfigOrDict] = None,
+ inference_configs: Optional[
+ dict[str, types.EvaluationRunInferenceConfigOrDict]
+ ] = None,
+ labels: Optional[dict[str, str]] = None,
+ loss_analysis_metrics: Optional[list[Union[str, types.MetricOrDict]]] = None,
+ loss_analysis_configs: Optional[list[types.LossAnalysisConfigOrDict]] = None,
+ red_teaming_config: Optional[types.RedTeamingAnalysisConfigOrDict] = None,
+ config: Optional[types.CreateEvaluationRunConfigOrDict] = None,
+ ) -> types.EvaluationRun:
+ """Creates an EvaluationRun.
+
+ Args:
+ dataset: The dataset to evaluate. Either an EvaluationRunDataSource or an EvaluationDataset.
+ dest: The GCS URI prefix to write the evaluation results to.
+ metrics: The list of metrics to evaluate.
+ name: The name of the evaluation run.
+ display_name: The display name of the evaluation run.
+ agent_info: The agent info to evaluate. Mutually exclusive with
+ `inference_configs`.
+ agent: The agent engine resource name in str type, with format
+ `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine_id}`.
+ If provided, runs inference with the deployed agent to get agent responses
+ for evaluation. This is required if `agent_info` is provided.
+ user_simulator_config: The user simulator configuration for agent evaluation.
+ If `agent_info` is provided without `inference_configs`, this config is used
+ to automatically construct the inference configuration. If not specified,
+ or if `max_turn` is not set, `max_turn` defaults to 5.
+ The `model_name` inside this config can be either a full model path or a
+ short model name, e.g. `gemini-3-preview-flash`.
+ inference_configs: The candidate to inference config map for the evaluation run.
+ The key is the candidate name, and the value is the inference config.
+ If provided, `agent_info` must be None. If omitted and `agent_info` is provided,
+ this will be automatically constructed using `agent_info` and `user_simulator_config`.
+ Example:
+ {"candidate-1": types.EvaluationRunInferenceConfig(model="gemini-2.5-flash")}
+ labels: The labels to apply to the evaluation run.
+ loss_analysis_metrics: This field is experimental and may change in future
+ versions. Optional list of metrics to run loss analysis on. The
+ candidate is auto-inferred from ``inference_configs`` or
+ ``agent_info`` when there is exactly one candidate. Each metric can be
+ a string (e.g., ``"multi_turn_task_success_v1"``), a ``Metric``
+ object, or a ``RubricMetric`` enum
+ (e.g., ``types.RubricMetric.MULTI_TURN_TASK_SUCCESS``). Loss analysis
+ runs after metric calculation completes.
+ Mutually exclusive with ``loss_analysis_configs``.
+ Example::
+
+ loss_analysis_metrics=[
+ types.RubricMetric.MULTI_TURN_TASK_SUCCESS,
+ types.RubricMetric.MULTI_TURN_TOOL_USE_QUALITY,
+ ]
+ loss_analysis_configs: This field is experimental and may change in future
+ versions. Optional list of ``LossAnalysisConfig`` objects for full
+ control over loss analysis, including explicit candidate and
+ advanced options like ``predefined_taxonomy`` and
+ ``max_top_cluster_count``. Mutually exclusive with
+ ``loss_analysis_metrics``.
+ config: The configuration for the evaluation run.
+ - allow_cross_region_model: Allows the evaluation run to use cross
+ region models. When this flag is set, the service may route traffic to
+ other regions if a model is unavailable in the current region (e.g.,
+ to a `global`endpoint). If a fully-qualified model endpoint resource
+ name with a different region than the run location is provided
+ elsewhere in the runconfig, this flag must be set to true or the
+ request will fail.
+
+ Returns:
+ The created evaluation run.
+ """
+ if loss_analysis_metrics and loss_analysis_configs:
+ raise ValueError(
+ "At most one of loss_analysis_metrics or loss_analysis_configs"
+ " can be provided."
+ )
+ if agent_info and inference_configs:
+ raise ValueError(
+ "At most one of agent_info or inference_configs can be provided."
+ )
+ parsed_agent_info = (
+ evals_types.AgentInfo.model_validate(agent_info)
+ if isinstance(agent_info, dict)
+ else (agent_info or evals_types.AgentInfo())
+ )
+
+ if not config:
+ config = types.CreateEvaluationRunConfig()
+ if isinstance(config, dict):
+ config = types.CreateEvaluationRunConfig.model_validate(config)
+
+ if agent_info and not inference_configs:
+ parsed_user_simulator_config = (
+ evals_types.UserSimulatorConfig.model_validate(user_simulator_config)
+ if isinstance(user_simulator_config, dict)
+ else (user_simulator_config or evals_types.UserSimulatorConfig())
+ )
+ if getattr(parsed_user_simulator_config, "max_turn", None) is None:
+ parsed_user_simulator_config.max_turn = 5
+
+ candidate_name = parsed_agent_info.name or "candidate-1"
+ inference_configs = {
+ candidate_name: types.EvaluationRunInferenceConfig(
+ agent_configs=parsed_agent_info.agents,
+ agent_run_config=types.AgentRunConfig(
+ agent_engine=agent,
+ user_simulator_config=parsed_user_simulator_config,
+ ),
+ )
+ }
+
+ if isinstance(dataset, types.EvaluationDataset):
+ _evals_utils._validate_dataset_agent_data(dataset, inference_configs)
+ resolved_dataset = _evals_common._resolve_dataset(
+ self._api_client, dataset, dest, parsed_agent_info
+ )
+ output_config = genai_types.OutputConfig(
+ gcs_destination=genai_types.GcsDestination(output_uri_prefix=dest)
+ )
+ resolved_metrics = _evals_common._resolve_evaluation_run_metrics(
+ metrics, self._api_client
+ )
+ resolved_loss_configs = _evals_utils._resolve_eval_run_loss_configs(
+ loss_analysis_metrics=loss_analysis_metrics,
+ loss_analysis_configs=loss_analysis_configs,
+ inference_configs=inference_configs,
+ )
+ resolved_analysis_configs = _evals_utils._resolve_red_teaming_config(
+ red_teaming_config
+ )
+ evaluation_config = types.EvaluationRunConfig(
+ output_config=output_config,
+ metrics=resolved_metrics,
+ loss_analysis_config=resolved_loss_configs,
+ allow_cross_region_model=getattr(config, "allow_cross_region_model", None),
+ )
+ resolved_inference_configs = _evals_common._resolve_inference_configs(
+ self._api_client, resolved_dataset, inference_configs, parsed_agent_info
+ )
+ resolved_labels = _evals_common._add_evaluation_run_labels(labels, agent)
+ resolved_name = name or f"evaluation_run_{uuid.uuid4()}"
+ return self._create_evaluation_run(
+ name=resolved_name,
+ display_name=display_name or resolved_name,
+ data_source=resolved_dataset,
+ evaluation_config=evaluation_config,
+ inference_configs=resolved_inference_configs,
+ analysis_configs=resolved_analysis_configs,
+ labels=resolved_labels,
+ config=config,
+ )
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_set method is experimental, "
+ "and may change in future versions."
+ )
+ def get_evaluation_set(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetEvaluationSetConfigOrDict] = None,
+ ) -> types.EvaluationSet:
+ """Retrieves an EvaluationSet from the resource name.
+
+ Args:
+ name: The resource name of the EvaluationSet. Format:
+ `projects/{project}/locations/{location}/evaluationSets/{evaluation_set}`
+ config: The optional configuration for the evaluation set. Must be a dict or
+ `types.GetEvaluationSetConfigOrDict` type.
+
+ Returns:
+ The evaluation set.
+ """
+
+ if not name:
+ raise ValueError("name cannot be empty.")
+ if name.startswith("projects/"):
+ name = name.split("/")[-1]
+ return self._get_evaluation_set(name=name, config=config)
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_item method is experimental, "
+ "and may change in future versions."
+ )
+ def get_evaluation_item(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetEvaluationItemConfigOrDict] = None,
+ ) -> types.EvaluationItem:
+ """Retrieves an EvaluationItem from the resource name.
+
+ Args:
+ name: The resource name of the EvaluationItem. Format:
+ `projects/{project}/locations/{location}/evaluationItems/{evaluation_item}`
+ config: The optional configuration for the evaluation item. Must be a dict or
+ `types.GetEvaluationItemConfigOrDict` type.
+
+ Returns:
+ The evaluation item.
+ """
+ if not name:
+ raise ValueError("name cannot be empty.")
+ if name.startswith("projects/"):
+ name = name.split("/")[-1]
+ result = self._get_evaluation_item(name=name, config=config)
+ if (
+ result.gcs_uri
+ and result.evaluation_item_type == types.EvaluationItemType.RESULT
+ ):
+ result.evaluation_response = (
+ _evals_common._convert_gcs_to_evaluation_item_result(
+ self._api_client, result.gcs_uri
+ )
+ )
+ elif (
+ result.gcs_uri
+ and result.evaluation_item_type == types.EvaluationItemType.REQUEST
+ ):
+ result.evaluation_request = (
+ _evals_common._convert_gcs_to_evaluation_item_request(
+ self._api_client, result.gcs_uri
+ )
+ )
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_item module is experimental, "
+ "and may change in future versions."
+ )
+ def create_evaluation_item(
+ self,
+ *,
+ evaluation_item_type: types.EvaluationItemType,
+ gcs_uri: str,
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationItemConfigOrDict] = None,
+ ) -> types.EvaluationItem:
+ """Creates an EvaluationItem.
+
+ Args:
+ evaluation_item_type: The type of the evaluation item.
+ gcs_uri: The GCS URI of the evaluation item.
+ display_name: The display name of the evaluation item.
+ config: The optional configuration for the evaluation item. Must be a dict or
+ `types.CreateEvaluationItemConfigOrDict` type.
+
+ Returns:
+ The evaluation item.
+ """
+ return self._create_evaluation_item(
+ evaluation_item_type=evaluation_item_type,
+ gcs_uri=gcs_uri,
+ display_name=display_name,
+ config=config,
+ )
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_set module is experimental, "
+ "and may change in future versions."
+ )
+ def create_evaluation_set(
+ self,
+ *,
+ evaluation_items: list[str],
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationSetConfigOrDict] = None,
+ ) -> types.EvaluationSet:
+ """Creates an EvaluationSet.
+
+ Args:
+ evaluation_items: The list of evaluation item names. Format:
+ `projects/{project}/locations/{location}/evaluationItems/{evaluation_item}`
+ display_name: The display name of the evaluation set.
+ config: The optional configuration for the evaluation set. Must be a dict or
+ `types.CreateEvaluationSetConfigOrDict` type.
+
+ Returns:
+ The evaluation set.
+ """
+ return self._create_evaluation_set(
+ evaluation_items=evaluation_items,
+ display_name=display_name,
+ config=config,
+ )
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.generate_conversation_scenarios module is experimental, "
+ "and may change in future versions."
+ )
+ def generate_conversation_scenarios(
+ self,
+ *,
+ agent_info: evals_types.AgentInfoOrDict,
+ config: evals_types.UserScenarioGenerationConfigOrDict,
+ allow_cross_region_model: Optional[bool] = None,
+ ) -> types.EvaluationDataset:
+ """Generates an evaluation dataset with user scenarios,
+ which helps to generate conversations between a simulated user
+ and the agent under test.
+
+ Args:
+ agent_info: The agent info to generate user scenarios for.
+ config: Configuration for generating user scenarios.
+ allow_cross_region_model: Opt-in flag to authorize cross-region
+ routing for model inference.
+
+ Returns:
+ An EvaluationDataset containing the generated user scenarios.
+ """
+ parsed_agent_info = (
+ evals_types.AgentInfo.model_validate(agent_info)
+ if isinstance(agent_info, dict)
+ else agent_info
+ )
+ response = self._generate_user_scenarios(
+ agents=parsed_agent_info.agents,
+ root_agent_id=parsed_agent_info.root_agent_id,
+ user_scenario_generation_config=config,
+ allow_cross_region_model=allow_cross_region_model,
+ )
+ return _evals_utils._postprocess_user_scenarios_response(response)
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.generate_loss_clusters module is experimental, "
+ "and may change in future versions."
+ )
+ def generate_loss_clusters(
+ self,
+ *,
+ eval_result: types.EvaluationResult,
+ metric: Optional[Union[str, types.MetricOrDict]] = None,
+ candidate: Optional[str] = None,
+ config: Optional[types.LossAnalysisConfigOrDict] = None,
+ ) -> types.GenerateLossClustersResponse:
+ """Generates loss clusters from evaluation results.
+
+ Analyzes "Pass/Fail" signals from rubric-based autoraters and groups
+ them into semantic "Loss Patterns" (e.g., "Hallucination of Action").
+
+ This method calls the GenerateLossClusters LRO and polls until
+ completion, returning the results directly.
+
+ If ``metric`` or ``candidate`` are not provided, they will be
+ auto-inferred from ``eval_result`` when unambiguous (i.e., when the
+ eval result contains exactly one metric or one candidate). For
+ multi-metric or multi-candidate evaluations, provide them explicitly.
+
+ Available candidate names can be found in
+ ``eval_result.metadata.candidate_names``.
+
+ Note: This API is only available in the ``global`` region.
+
+ Args:
+ eval_result: The EvaluationResult object returned from
+ client.evals.evaluate().
+ metric: The metric to analyze. Can be a metric name string
+ (e.g., "multi_turn_task_success_v1"), a Metric object, or a
+ RubricMetric enum (e.g., types.RubricMetric.MULTI_TURN_TASK_SUCCESS).
+ If not provided and config does not specify it, auto-inferred
+ from eval_result.
+ candidate: The candidate to analyze. If not provided and config
+ does not specify it, auto-inferred from eval_result.
+ config: Optional LossAnalysisConfig with additional options
+ (predefined_taxonomy, max_top_cluster_count). Can also
+ specify metric/candidate, but explicit arguments take
+ precedence.
+
+ Returns:
+ A GenerateLossClustersResponse containing the analysis results.
+ Call .show() to visualize, or access .results for individual
+ LossAnalysisResult objects (each with their own .show()).
+ """
+ metric_name = _evals_utils._resolve_metric_name(metric)
+ parsed_config = (
+ types.LossAnalysisConfig.model_validate(config)
+ if isinstance(config, dict)
+ else config
+ )
+ resolved_config = _evals_utils._resolve_loss_analysis_config(
+ eval_result=eval_result,
+ config=parsed_config,
+ metric=metric_name,
+ candidate=candidate,
+ )
+ operation = self._generate_loss_clusters(
+ inline_results=[eval_result],
+ configs=[resolved_config],
+ )
+ completed = _evals_utils._poll_operation(
+ api_client=self._api_client,
+ operation=operation,
+ )
+ if completed.error:
+ raise RuntimeError(f"Loss analysis operation failed: {completed.error}")
+ if completed.response is None:
+ raise RuntimeError(
+ "Loss analysis operation completed but returned no response."
+ )
+ _evals_utils._enrich_loss_response_with_rubric_descriptions(
+ completed.response, eval_result
+ )
+ return completed.response
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_metric method is experimental, "
+ "and may change in future versions."
+ )
+ def create_evaluation_metric(
+ self,
+ *,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ metric: Optional[types.MetricOrDict] = None,
+ config: Optional[types.CreateEvaluationMetricConfigOrDict] = None,
+ ) -> str:
+ """Creates an EvaluationMetric."""
+ if metric and not isinstance(metric, dict):
+ # metric is now Metric | LazyLoadedPrebuiltMetric (RubricMetric)
+ # Mypy correctly narrows the type here, so cast is not needed.
+ resolved_metrics = _evals_common._resolve_metrics(
+ [metric], self._api_client
+ )
+ metric = resolved_metrics[0]
+
+ # Add fallback logic for display_name
+ if display_name is None and metric:
+ if isinstance(metric, dict):
+ display_name = metric.get("name")
+ else:
+ display_name = getattr(metric, "name", None)
+
+ result = self._create_evaluation_metric(
+ display_name=display_name,
+ description=description,
+ metric=metric,
+ config=config,
+ )
+ # result.name is Optional[str], but we know it's always returned on creation
+ return cast(str, result.name)
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_metric module is experimental, "
+ "and may change in future versions."
+ )
+ def get_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.GetEvaluationMetricConfigOrDict] = None,
+ ) -> types.EvaluationMetric:
+ """Retrieves an EvaluationMetric from the resource name."""
+ return self._get_evaluation_metric(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.list_evaluation_metrics module is experimental, "
+ "and may change in future versions."
+ )
+ def list_evaluation_metrics(
+ self,
+ *,
+ filter: Optional[str] = None,
+ order_by: Optional[str] = None,
+ config: Optional[types.ListEvaluationMetricsConfigOrDict] = None,
+ ) -> types.ListEvaluationMetricsResponse:
+ """Lists EvaluationMetrics.
+
+ Args:
+ filter: An expression for filtering the results of the request. For
+ field names both snake_case and camelCase are supported. For more
+ information about filter syntax, see
+ `AIP-160 `_.
+ Example: ``'display_name="my_metric"'``.
+ order_by: A comma-separated list of fields to order by, sorted in
+ ascending order by default. Use ``desc`` after a field name for
+ descending. Example: ``"create_time desc"``.
+ config: Optional configuration for the list operation, including
+ pagination (``page_size``, ``page_token``), ``filter``, and
+ ``order_by``. Top-level ``filter`` and ``order_by`` arguments
+ take precedence over values set in ``config``.
+
+ Returns:
+ The list evaluation metrics response.
+ """
+ if config is None:
+ config = types.ListEvaluationMetricsConfig()
+ if isinstance(config, dict):
+ config = types.ListEvaluationMetricsConfig.model_validate(config)
+ if filter is not None:
+ config.filter = filter
+ if order_by is not None:
+ config.order_by = order_by
+ return self._list_evaluation_metrics(
+ config=config,
+ )
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.delete_evaluation_metric method is experimental, "
+ "and may change in future versions."
+ )
+ def delete_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.DeleteEvaluationMetricConfigOrDict] = None,
+ ) -> None:
+ """Deletes an EvaluationMetric.
+
+ Args:
+ metric_resource_name: The resource name of the EvaluationMetric to delete.
+ Format:
+ `projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric}`
+ config: The optional configuration for the delete operation.
+ """
+ self._delete_evaluation_metric(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+
+class AsyncEvals(_api_module.BaseModule):
+
+ async def _create_evaluation_item(
+ self,
+ *,
+ evaluation_item_type: str,
+ gcs_uri: str,
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationItemConfigOrDict] = None,
+ ) -> types.EvaluationItem:
+ """
+ Creates an EvaluationItem.
+ """
+
+ parameter_model = types._CreateEvaluationItemParameters(
+ evaluation_item_type=evaluation_item_type,
+ gcs_uri=gcs_uri,
+ display_name=display_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationItemParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationItems".format_map(request_url_dict)
+ else:
+ path = "evaluationItems"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationItem._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create_evaluation_metric(
+ self,
+ *,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ metric: Optional[types.MetricOrDict] = None,
+ config: Optional[types.CreateEvaluationMetricConfigOrDict] = None,
+ ) -> types.EvaluationMetric:
+ """
+ Creates an EvaluationMetric.
+ """
+
+ parameter_model = types._CreateEvaluationMetricParameters(
+ display_name=display_name,
+ description=description,
+ metric=metric,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationMetricParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationMetrics".format_map(request_url_dict)
+ else:
+ path = "evaluationMetrics"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationMetric_from_vertex(response_dict)
+
+ return_value = types.EvaluationMetric._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create_evaluation_run(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ data_source: types.EvaluationRunDataSourceOrDict,
+ evaluation_config: types.EvaluationRunConfigOrDict,
+ labels: Optional[dict[str, str]] = None,
+ inference_configs: Optional[
+ dict[str, types.EvaluationRunInferenceConfigOrDict]
+ ] = None,
+ config: Optional[types.CreateEvaluationRunConfigOrDict] = None,
+ analysis_configs: Optional[list[types.AnalysisConfigOrDict]] = None,
+ ) -> types.EvaluationRun:
+ """
+ Creates an EvaluationRun.
+ """
+
+ parameter_model = types._CreateEvaluationRunParameters(
+ name=name,
+ display_name=display_name,
+ data_source=data_source,
+ evaluation_config=evaluation_config,
+ labels=labels,
+ inference_configs=inference_configs,
+ config=config,
+ analysis_configs=analysis_configs,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationRunParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationRuns".format_map(request_url_dict)
+ else:
+ path = "evaluationRuns"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationRun_from_vertex(response_dict)
+
+ return_value = types.EvaluationRun._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create_evaluation_set(
+ self,
+ *,
+ evaluation_items: list[str],
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationSetConfigOrDict] = None,
+ ) -> types.EvaluationSet:
+ """
+ Creates an EvaluationSet.
+ """
+
+ parameter_model = types._CreateEvaluationSetParameters(
+ evaluation_items=evaluation_items,
+ display_name=display_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateEvaluationSetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationSets".format_map(request_url_dict)
+ else:
+ path = "evaluationSets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationSet._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.DeleteEvaluationMetricConfigOrDict] = None,
+ ) -> types.DeleteEvaluationMetricOperation:
+ """
+ Deletes an EvaluationMetric.
+ """
+
+ parameter_model = types._DeleteEvaluationMetricParameters(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteEvaluationMetricParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{evaluation_metric}".format_map(request_url_dict)
+ else:
+ path = "{evaluation_metric}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteEvaluationMetricOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _evaluate_instances(
+ self,
+ *,
+ bleu_input: Optional[types.BleuInputOrDict] = None,
+ exact_match_input: Optional[types.ExactMatchInputOrDict] = None,
+ rouge_input: Optional[types.RougeInputOrDict] = None,
+ pointwise_metric_input: Optional[types.PointwiseMetricInputOrDict] = None,
+ pairwise_metric_input: Optional[types.PairwiseMetricInputOrDict] = None,
+ tool_call_valid_input: Optional[types.ToolCallValidInputOrDict] = None,
+ tool_name_match_input: Optional[types.ToolNameMatchInputOrDict] = None,
+ tool_parameter_key_match_input: Optional[
+ types.ToolParameterKeyMatchInputOrDict
+ ] = None,
+ tool_parameter_kv_match_input: Optional[
+ types.ToolParameterKVMatchInputOrDict
+ ] = None,
+ rubric_based_metric_input: Optional[types.RubricBasedMetricInputOrDict] = None,
+ autorater_config: Optional[genai_types.AutoraterConfigOrDict] = None,
+ metrics: Optional[list[types.MetricOrDict]] = None,
+ instance: Optional[types.EvaluationInstanceOrDict] = None,
+ metric_sources: Optional[list[types.MetricSourceOrDict]] = None,
+ config: Optional[types.EvaluateInstancesConfigOrDict] = None,
+ ) -> types.EvaluateInstancesResponse:
+ """
+ Evaluates instances based on a given metric.
+ """
+
+ parameter_model = types._EvaluateInstancesRequestParameters(
+ bleu_input=bleu_input,
+ exact_match_input=exact_match_input,
+ rouge_input=rouge_input,
+ pointwise_metric_input=pointwise_metric_input,
+ pairwise_metric_input=pairwise_metric_input,
+ tool_call_valid_input=tool_call_valid_input,
+ tool_name_match_input=tool_name_match_input,
+ tool_parameter_key_match_input=tool_parameter_key_match_input,
+ tool_parameter_kv_match_input=tool_parameter_kv_match_input,
+ rubric_based_metric_input=rubric_based_metric_input,
+ autorater_config=autorater_config,
+ metrics=metrics,
+ instance=instance,
+ metric_sources=metric_sources,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _EvaluateInstancesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":evaluateInstances".format_map(request_url_dict)
+ else:
+ path = ":evaluateInstances"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluateInstancesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _generate_user_scenarios(
+ self,
+ *,
+ location: Optional[str] = None,
+ agents: Optional[dict[str, evals_types.AgentConfigOrDict]] = None,
+ root_agent_id: Optional[str] = None,
+ user_scenario_generation_config: Optional[
+ evals_types.UserScenarioGenerationConfigOrDict
+ ] = None,
+ config: Optional[types.GenerateUserScenariosConfigOrDict] = None,
+ allow_cross_region_model: Optional[bool] = None,
+ ) -> types.GenerateUserScenariosResponse:
+ """
+ Generates user scenarios for agent evaluation.
+ """
+
+ parameter_model = types._GenerateUserScenariosParameters(
+ location=location,
+ agents=agents,
+ root_agent_id=root_agent_id,
+ user_scenario_generation_config=user_scenario_generation_config,
+ config=config,
+ allow_cross_region_model=allow_cross_region_model,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateUserScenariosParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":generateUserScenarios".format_map(request_url_dict)
+ else:
+ path = ":generateUserScenarios"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.GenerateUserScenariosResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _generate_loss_clusters(
+ self,
+ *,
+ location: Optional[str] = None,
+ evaluation_set: Optional[str] = None,
+ inline_results: Optional[list[types.EvaluationResultOrDict]] = None,
+ configs: Optional[list[types.LossAnalysisConfigOrDict]] = None,
+ config: Optional[types.GenerateLossClustersConfigOrDict] = None,
+ ) -> types.GenerateLossClustersOperation:
+ """
+ Generates loss clusters from evaluation results.
+ """
+
+ parameter_model = types._GenerateLossClustersParameters(
+ location=location,
+ evaluation_set=evaluation_set,
+ inline_results=inline_results,
+ configs=configs,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateLossClustersParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":generateLossClusters".format_map(request_url_dict)
+ else:
+ path = ":generateLossClusters"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.GenerateLossClustersOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _generate_rubrics(
+ self,
+ *,
+ contents: list[genai_types.ContentOrDict],
+ predefined_rubric_generation_spec: Optional[
+ genai_types.PredefinedMetricSpecOrDict
+ ] = None,
+ rubric_generation_spec: Optional[genai_types.RubricGenerationSpecOrDict] = None,
+ metric_resource_name: Optional[str] = None,
+ config: Optional[types.RubricGenerationConfigOrDict] = None,
+ ) -> types.GenerateInstanceRubricsResponse:
+ """
+ Generates rubrics for a given prompt.
+ """
+
+ parameter_model = types._GenerateInstanceRubricsRequest(
+ contents=contents,
+ predefined_rubric_generation_spec=predefined_rubric_generation_spec,
+ rubric_generation_spec=rubric_generation_spec,
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateInstanceRubricsRequest_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":generateInstanceRubrics".format_map(request_url_dict)
+ else:
+ path = ":generateInstanceRubrics"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.GenerateInstanceRubricsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.GetEvaluationMetricConfigOrDict] = None,
+ ) -> types.EvaluationMetric:
+ """
+ Retrieves an EvaluationMetric from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationMetricParameters(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationMetricParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{evaluation_metric}".format_map(request_url_dict)
+ else:
+ path = "{evaluation_metric}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationMetric_from_vertex(response_dict)
+
+ return_value = types.EvaluationMetric._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_evaluation_run(
+ self, *, name: str, config: Optional[types.GetEvaluationRunConfigOrDict] = None
+ ) -> types.EvaluationRun:
+ """
+ Retrieves an EvaluationRun from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationRunParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationRunParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationRuns/{name}".format_map(request_url_dict)
+ else:
+ path = "evaluationRuns/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _EvaluationRun_from_vertex(response_dict)
+
+ return_value = types.EvaluationRun._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_evaluation_set(
+ self, *, name: str, config: Optional[types.GetEvaluationSetConfigOrDict] = None
+ ) -> types.EvaluationSet:
+ """
+ Retrieves an EvaluationSet from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationSetParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationSetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationSets/{name}".format_map(request_url_dict)
+ else:
+ path = "evaluationSets/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationSet._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_evaluation_item(
+ self, *, name: str, config: Optional[types.GetEvaluationItemConfigOrDict] = None
+ ) -> types.EvaluationItem:
+ """
+ Retrieves an EvaluationItem from the resource name.
+ """
+
+ parameter_model = types._GetEvaluationItemParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetEvaluationItemParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationItems/{name}".format_map(request_url_dict)
+ else:
+ path = "evaluationItems/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.EvaluationItem._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list_evaluation_metrics(
+ self, *, config: Optional[types.ListEvaluationMetricsConfigOrDict] = None
+ ) -> types.ListEvaluationMetricsResponse:
+ """
+ Lists EvaluationMetrics.
+ """
+
+ parameter_model = types._ListEvaluationMetricsParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListEvaluationMetricsParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "evaluationMetrics".format_map(request_url_dict)
+ else:
+ path = "evaluationMetrics"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _ListEvaluationMetricsResponse_from_vertex(response_dict)
+
+ return_value = types.ListEvaluationMetricsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def batch_evaluate(
+ self,
+ *,
+ dataset: types.EvaluationDatasetOrDict,
+ metrics: list[types.MetricOrDict],
+ dest: str,
+ config: Optional[types.EvaluateDatasetConfigOrDict] = None,
+ ) -> types.EvaluateDatasetOperation:
+ """Evaluates a dataset based on a set of given metrics."""
+ resolved_metrics = _evals_common._resolve_metrics(metrics, self._api_client)
+ output_config = genai_types.OutputConfig(
+ gcs_destination=genai_types.GcsDestination(output_uri_prefix=dest)
+ )
+ parameter_model = types.EvaluateDatasetRequestParameters(
+ dataset=dataset,
+ metrics=resolved_metrics,
+ output_config=output_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError("This method is only supported in the Vertex AI client.")
+ else:
+ request_dict = _evals_utils.BatchEvaluateRequestPreparer.EvaluateDatasetRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = ":evaluateDataset".format_map(request_url_dict)
+ else:
+ path = ":evaluateDataset"
+
+ request_dict = _evals_utils.BatchEvaluateRequestPreparer.prepare_metric_payload(
+ request_dict, resolved_metrics
+ )
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = "" if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _evals_utils.BatchEvaluateRequestPreparer.EvaluateDatasetOperation_from_vertex(
+ response_dict
+ )
+
+ return_value = types.EvaluateDatasetOperation._from_response(
+ response=response_dict, kwargs=parameter_model.model_dump()
+ )
+ self._api_client._verify_response(return_value)
+
+ return return_value
+
+ async def evaluate_instances(
+ self,
+ *,
+ metric_config: types._EvaluateInstancesRequestParameters,
+ ) -> types.EvaluateInstancesResponse:
+ """Evaluates an instance of a model."""
+
+ if isinstance(metric_config, types._EvaluateInstancesRequestParameters):
+ metric_config = metric_config.model_dump() # type: ignore[assignment]
+ else:
+ metric_config = dict(metric_config)
+
+ result = await self._evaluate_instances(
+ **metric_config,
+ )
+
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_run module is experimental, "
+ "and may change in future versions."
+ )
+ async def get_evaluation_run(
+ self,
+ *,
+ name: str,
+ include_evaluation_items: bool = False,
+ config: Optional[types.GetEvaluationRunConfigOrDict] = None,
+ ) -> types.EvaluationRun:
+ """Retrieves the EvaluationRun from the resource name.
+ Args:
+ name: The resource name of the EvaluationRun. Format:
+ `projects/{project}/locations/{location}/evaluationRuns/{evaluation_run}`
+ include_evaluation_items: Whether to include the evaluation items in the
+ response.
+ config: The optional configuration for the evaluation run. Must be a dict or
+ `types.GetEvaluationRunConfigOrDict` type.
+
+ Returns:
+ The evaluation run.
+ Raises:
+ ValueError: If the name is empty or invalid.
+ """
+ if not name:
+ raise ValueError("name cannot be empty.")
+ if name.startswith("projects/"):
+ name = name.split("/")[-1]
+ result = await self._get_evaluation_run(name=name, config=config)
+ if include_evaluation_items:
+ eval_result, eval_item_map = (
+ await _evals_common._convert_evaluation_run_results_async(
+ self._api_client,
+ result.evaluation_run_results,
+ result.inference_configs,
+ )
+ )
+ result.evaluation_item_results = eval_result
+ # Bypass pydantic validation (extra='forbid') for this internal field.
+ object.__setattr__(result, "_eval_item_map", eval_item_map)
+
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_run module is experimental, "
+ "and may change in future versions."
+ )
+ async def create_evaluation_run(
+ self,
+ *,
+ dataset: Union[types.EvaluationRunDataSource, types.EvaluationDataset],
+ dest: str,
+ metrics: list[types.EvaluationRunMetricOrDict],
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ agent_info: Optional[evals_types.AgentInfo] = None,
+ agent: Optional[str] = None,
+ user_simulator_config: Optional[evals_types.UserSimulatorConfigOrDict] = None,
+ inference_configs: Optional[
+ dict[str, types.EvaluationRunInferenceConfigOrDict]
+ ] = None,
+ red_teaming_config: Optional[types.RedTeamingAnalysisConfigOrDict] = None,
+ labels: Optional[dict[str, str]] = None,
+ loss_analysis_metrics: Optional[list[Union[str, types.MetricOrDict]]] = None,
+ loss_analysis_configs: Optional[list[types.LossAnalysisConfigOrDict]] = None,
+ config: Optional[types.CreateEvaluationRunConfigOrDict] = None,
+ ) -> types.EvaluationRun:
+ """Creates an EvaluationRun.
+
+ Args:
+ dataset: The dataset to evaluate. Either an EvaluationRunDataSource or an EvaluationDataset.
+ dest: The GCS URI prefix to write the evaluation results to.
+ metrics: The list of metrics to evaluate.
+ name: The name of the evaluation run.
+ display_name: The display name of the evaluation run.
+ agent_info: The agent info to evaluate. Mutually exclusive with
+ `inference_configs`.
+ agent: The agent engine resource name in str type, with format
+ `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine_id}`.
+ If provided, runs inference with the deployed agent to get agent responses
+ for evaluation. This is required if `agent_info` is provided.
+ user_simulator_config: The user simulator configuration for agent evaluation.
+ If `agent_info` is provided without `inference_configs`, this config is used
+ to automatically construct the inference configuration. If not specified,
+ or if `max_turn` is not set, `max_turn` defaults to 5.
+ The `model_name` inside this config can be either a full model path or a
+ short model name, e.g. `gemini-3-preview-flash`.
+ inference_configs: The candidate to inference config map for the evaluation run.
+ The key is the candidate name, and the value is the inference config.
+ If provided, `agent_info` must be None. If omitted and `agent_info` is provided,
+ this will be automatically constructed using `agent_info` and `user_simulator_config`.
+ Example:
+ {"candidate-1": types.EvaluationRunInferenceConfig(model="gemini-2.5-flash")}
+ red_teaming_config: This field is experimental and may change in future
+ versions. Optional configuration for automated Agent Red Teaming
+ analysis. Specifies attack categories and vulnerable tools to
+ test. When provided, the server runs a red teaming pipeline
+ instead of standard evaluation metrics.
+ labels: The labels to apply to the evaluation run.
+ loss_analysis_metrics: This field is experimental and may change in future
+ versions. Optional list of metrics to run loss analysis on. The
+ candidate is auto-inferred from ``inference_configs`` or
+ ``agent_info`` when there is exactly one candidate. Each metric can be
+ a string (e.g., ``"multi_turn_task_success_v1"``), a ``Metric``
+ object, or a ``RubricMetric`` enum
+ (e.g., ``types.RubricMetric.MULTI_TURN_TASK_SUCCESS``). Loss analysis
+ runs after metric calculation completes.
+ Mutually exclusive with ``loss_analysis_configs``.
+ Example::
+
+ loss_analysis_metrics=[
+ types.RubricMetric.MULTI_TURN_TASK_SUCCESS,
+ types.RubricMetric.MULTI_TURN_TOOL_USE_QUALITY,
+ ]
+ loss_analysis_configs: This field is experimental and may change in future
+ versions. Optional list of ``LossAnalysisConfig`` objects for full
+ control over loss analysis, including explicit candidate and
+ advanced options like ``predefined_taxonomy`` and
+ ``max_top_cluster_count``. Mutually exclusive with
+ ``loss_analysis_metrics``.
+ config: The configuration for the evaluation run.
+ - allow_cross_region_model: Opt-in flag to authorize cross-region
+ routing for model inference. Applies to both scraping and evaluation.
+
+ Returns:
+ The created evaluation run.
+ """
+ if loss_analysis_metrics and loss_analysis_configs:
+ raise ValueError(
+ "At most one of loss_analysis_metrics or loss_analysis_configs"
+ " can be provided."
+ )
+ if agent_info and inference_configs:
+ raise ValueError(
+ "At most one of agent_info or inference_configs can be provided."
+ )
+ parsed_agent_info = (
+ evals_types.AgentInfo.model_validate(agent_info)
+ if isinstance(agent_info, dict)
+ else (agent_info or evals_types.AgentInfo())
+ )
+
+ if not config:
+ config = types.CreateEvaluationRunConfig()
+ if isinstance(config, dict):
+ config = types.CreateEvaluationRunConfig.model_validate(config)
+
+ if agent_info and not inference_configs:
+ parsed_user_simulator_config = (
+ evals_types.UserSimulatorConfig.model_validate(user_simulator_config)
+ if isinstance(user_simulator_config, dict)
+ else (user_simulator_config or evals_types.UserSimulatorConfig())
+ )
+ if getattr(parsed_user_simulator_config, "max_turn", None) is None:
+ parsed_user_simulator_config.max_turn = 5
+
+ candidate_name = parsed_agent_info.name or "candidate-1"
+ inference_configs = {
+ candidate_name: types.EvaluationRunInferenceConfig(
+ agent_configs=parsed_agent_info.agents,
+ agent_run_config=types.AgentRunConfig(
+ agent_engine=agent,
+ user_simulator_config=parsed_user_simulator_config,
+ ),
+ )
+ }
+
+ if isinstance(dataset, types.EvaluationDataset):
+ _evals_utils._validate_dataset_agent_data(dataset, inference_configs)
+ resolved_dataset = _evals_common._resolve_dataset(
+ self._api_client, dataset, dest, parsed_agent_info
+ )
+ output_config = genai_types.OutputConfig(
+ gcs_destination=genai_types.GcsDestination(output_uri_prefix=dest)
+ )
+ resolved_metrics = _evals_common._resolve_evaluation_run_metrics(
+ metrics, self._api_client
+ )
+ resolved_loss_configs = _evals_utils._resolve_eval_run_loss_configs(
+ loss_analysis_metrics=loss_analysis_metrics,
+ loss_analysis_configs=loss_analysis_configs,
+ inference_configs=inference_configs,
+ )
+ resolved_analysis_configs = _evals_utils._resolve_red_teaming_config(
+ red_teaming_config
+ )
+ evaluation_config = types.EvaluationRunConfig(
+ output_config=output_config,
+ metrics=resolved_metrics,
+ loss_analysis_config=resolved_loss_configs,
+ allow_cross_region_model=getattr(config, "allow_cross_region_model", None),
+ )
+ resolved_inference_configs = _evals_common._resolve_inference_configs(
+ self._api_client, resolved_dataset, inference_configs, parsed_agent_info
+ )
+ resolved_labels = _evals_common._add_evaluation_run_labels(labels, agent)
+ resolved_name = name or f"evaluation_run_{uuid.uuid4()}"
+
+ result = await self._create_evaluation_run(
+ name=resolved_name,
+ display_name=display_name or resolved_name,
+ data_source=resolved_dataset,
+ evaluation_config=evaluation_config,
+ inference_configs=resolved_inference_configs,
+ analysis_configs=resolved_analysis_configs,
+ labels=resolved_labels,
+ config=config,
+ )
+
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_set method is experimental, "
+ "and may change in future versions."
+ )
+ async def get_evaluation_set(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetEvaluationSetConfigOrDict] = None,
+ ) -> types.EvaluationSet:
+ """Retrieves an EvaluationSet from the resource name.
+
+ Args:
+ name: The resource name of the EvaluationSet. Format:
+ `projects/{project}/locations/{location}/evaluationSets/{evaluation_set}`
+ config: The optional configuration for the evaluation set. Must be a dict or
+ `types.GetEvaluationSetConfigOrDict` type.
+
+ Returns:
+ The evaluation set.
+ """
+ if not name:
+ raise ValueError("name cannot be empty.")
+ if name.startswith("projects/"):
+ name = name.split("/")[-1]
+ result = await self._get_evaluation_set(name=name, config=config)
+
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_item method is experimental, "
+ "and may change in future versions."
+ )
+ async def get_evaluation_item(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetEvaluationItemConfigOrDict] = None,
+ ) -> types.EvaluationItem:
+ """Retrieves an EvaluationItem from the resource name.
+
+ Args:
+ name: The resource name of the EvaluationItem. Format:
+ `projects/{project}/locations/{location}/evaluationItems/{evaluation_item}`
+ config: The optional configuration for the evaluation item. Must be a dict or
+ `types.GetEvaluationItemConfigOrDict` type.
+
+ Returns:
+ The evaluation item.
+ """
+ if not name:
+ raise ValueError("name cannot be empty.")
+ if name.startswith("projects/"):
+ name = name.split("/")[-1]
+ result = await self._get_evaluation_item(name=name, config=config)
+ if (
+ result.gcs_uri
+ and result.evaluation_item_type == types.EvaluationItemType.RESULT
+ ):
+ result.evaluation_response = (
+ _evals_common._convert_gcs_to_evaluation_item_result(
+ self._api_client, result.gcs_uri
+ )
+ )
+ elif (
+ result.gcs_uri
+ and result.evaluation_item_type == types.EvaluationItemType.REQUEST
+ ):
+ result.evaluation_request = (
+ _evals_common._convert_gcs_to_evaluation_item_request(
+ self._api_client, result.gcs_uri
+ )
+ )
+
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_item module is experimental, "
+ "and may change in future versions."
+ )
+ async def create_evaluation_item(
+ self,
+ *,
+ evaluation_item_type: types.EvaluationItemType,
+ gcs_uri: str,
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationItemConfigOrDict] = None,
+ ) -> types.EvaluationItem:
+ """Creates an EvaluationItem.
+
+ Args:
+ evaluation_item_type: The type of the evaluation item.
+ gcs_uri: The GCS URI of the evaluation item.
+ display_name: The display name of the evaluation item.
+ config: The optional configuration for the evaluation item. Must be a dict or
+ `types.CreateEvaluationItemConfigOrDict` type.
+
+ Returns:
+ The evaluation item.
+ """
+ result = await self._create_evaluation_item(
+ evaluation_item_type=evaluation_item_type,
+ gcs_uri=gcs_uri,
+ display_name=display_name,
+ config=config,
+ )
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_set module is experimental, "
+ "and may change in future versions."
+ )
+ async def create_evaluation_set(
+ self,
+ *,
+ evaluation_items: list[str],
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateEvaluationSetConfigOrDict] = None,
+ ) -> types.EvaluationSet:
+ """Creates an EvaluationSet.
+
+ Args:
+ evaluation_items: The list of evaluation item names. Format:
+ `projects/{project}/locations/{location}/evaluationItems/{evaluation_item}`
+ display_name: The display name of the evaluation set.
+ config: The optional configuration for the evaluation set. Must be a dict or
+ `types.CreateEvaluationSetConfigOrDict` type.
+
+ Returns:
+ The evaluation set.
+ """
+ result = await self._create_evaluation_set(
+ evaluation_items=evaluation_items,
+ display_name=display_name,
+ config=config,
+ )
+ return result
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.generate_conversation_scenarios module is experimental, "
+ "and may change in future versions."
+ )
+ async def generate_conversation_scenarios(
+ self,
+ *,
+ agent_info: evals_types.AgentInfoOrDict,
+ config: evals_types.UserScenarioGenerationConfigOrDict,
+ allow_cross_region_model: Optional[bool] = None,
+ ) -> types.EvaluationDataset:
+ """Generates an evaluation dataset with user scenarios,
+ which helps to generate conversations between a simulated user
+ and the agent under test.
+
+ Args:
+ agent_info: The agent info to generate user scenarios for.
+ config: Configuration for generating user scenarios.
+ allow_cross_region_model: Opt-in flag to authorize cross-region
+ routing for model inference.
+
+ Returns:
+ An EvaluationDataset containing the generated user scenarios.
+ """
+ parsed_agent_info = (
+ evals_types.AgentInfo.model_validate(agent_info)
+ if isinstance(agent_info, dict)
+ else agent_info
+ )
+ response = await self._generate_user_scenarios(
+ agents=parsed_agent_info.agents,
+ root_agent_id=parsed_agent_info.root_agent_id,
+ user_scenario_generation_config=config,
+ allow_cross_region_model=allow_cross_region_model,
+ )
+ return _evals_utils._postprocess_user_scenarios_response(response)
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.generate_loss_clusters module is experimental, "
+ "and may change in future versions."
+ )
+ async def generate_loss_clusters(
+ self,
+ *,
+ eval_result: types.EvaluationResult,
+ metric: Optional[Union[str, types.MetricOrDict]] = None,
+ candidate: Optional[str] = None,
+ config: Optional[types.LossAnalysisConfigOrDict] = None,
+ ) -> types.GenerateLossClustersResponse:
+ """Generates loss clusters from evaluation results.
+
+ Analyzes "Pass/Fail" signals from rubric-based autoraters and groups
+ them into semantic "Loss Patterns" (e.g., "Hallucination of Action").
+
+ This method calls the GenerateLossClusters LRO and polls until
+ completion, returning the results directly.
+
+ If ``metric`` or ``candidate`` are not provided, they will be
+ auto-inferred from ``eval_result`` when unambiguous (i.e., when the
+ eval result contains exactly one metric or one candidate). For
+ multi-metric or multi-candidate evaluations, provide them explicitly.
+
+ Available candidate names can be found in
+ ``eval_result.metadata.candidate_names``.
+
+ Note: This API is only available in the ``global`` region.
+
+ Args:
+ eval_result: The EvaluationResult object returned from
+ client.evals.evaluate().
+ metric: The metric to analyze. Can be a metric name string
+ (e.g., "multi_turn_task_success_v1"), a Metric object, or a
+ RubricMetric enum (e.g., types.RubricMetric.MULTI_TURN_TASK_SUCCESS).
+ If not provided and config does not specify it, auto-inferred
+ from eval_result.
+ candidate: The candidate to analyze. If not provided and config
+ does not specify it, auto-inferred from eval_result.
+ config: Optional LossAnalysisConfig with additional options
+ (predefined_taxonomy, max_top_cluster_count). Can also
+ specify metric/candidate, but explicit arguments take
+ precedence.
+
+ Returns:
+ A GenerateLossClustersResponse containing the analysis results.
+ Call .show() to visualize, or access .results for individual
+ LossAnalysisResult objects (each with their own .show()).
+ """
+ metric_name = _evals_utils._resolve_metric_name(metric)
+ parsed_config = (
+ types.LossAnalysisConfig.model_validate(config)
+ if isinstance(config, dict)
+ else config
+ )
+ resolved_config = _evals_utils._resolve_loss_analysis_config(
+ eval_result=eval_result,
+ config=parsed_config,
+ metric=metric_name,
+ candidate=candidate,
+ )
+ operation = await self._generate_loss_clusters(
+ inline_results=[eval_result],
+ configs=[resolved_config],
+ )
+ completed = await _evals_utils._poll_operation_async(
+ api_client=self._api_client,
+ operation=operation,
+ )
+ if completed.error:
+ raise RuntimeError(f"Loss analysis operation failed: {completed.error}")
+ if completed.response is None:
+ raise RuntimeError(
+ "Loss analysis operation completed but returned no response."
+ )
+ _evals_utils._enrich_loss_response_with_rubric_descriptions(
+ completed.response, eval_result
+ )
+ return completed.response
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.create_evaluation_metric module is experimental, "
+ "and may change in future versions."
+ )
+ async def create_evaluation_metric(
+ self,
+ *,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ metric: Optional[types.MetricOrDict] = None,
+ config: Optional[types.CreateEvaluationMetricConfigOrDict] = None,
+ ) -> str:
+ """Creates an EvaluationMetric."""
+ if metric and not isinstance(metric, dict):
+ resolved_metrics = _evals_common._resolve_metrics(
+ [metric], self._api_client
+ )
+ metric = resolved_metrics[0]
+
+ # Add fallback logic for display_name
+ if display_name is None and metric:
+ if isinstance(metric, dict):
+ display_name = metric.get("name")
+ else:
+ display_name = getattr(metric, "name", None)
+
+ result = await self._create_evaluation_metric(
+ display_name=display_name,
+ description=description,
+ metric=metric,
+ config=config,
+ )
+ return cast(str, result.name)
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.get_evaluation_metric module is experimental, "
+ "and may change in future versions."
+ )
+ async def get_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.GetEvaluationMetricConfigOrDict] = None,
+ ) -> types.EvaluationMetric:
+ """Retrieves an EvaluationMetric from the resource name."""
+ return await self._get_evaluation_metric(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.list_evaluation_metrics module is experimental, "
+ "and may change in future versions."
+ )
+ async def list_evaluation_metrics(
+ self,
+ *,
+ filter: Optional[str] = None,
+ order_by: Optional[str] = None,
+ config: Optional[types.ListEvaluationMetricsConfigOrDict] = None,
+ ) -> types.ListEvaluationMetricsResponse:
+ """Lists EvaluationMetrics.
+
+ Args:
+ filter: An expression for filtering the results of the request. For
+ field names both snake_case and camelCase are supported. For more
+ information about filter syntax, see
+ `AIP-160 `_.
+ Example: ``'display_name="my_metric"'``.
+ order_by: A comma-separated list of fields to order by, sorted in
+ ascending order by default. Use ``desc`` after a field name for
+ descending. Example: ``"create_time desc"``.
+ config: Optional configuration for the list operation, including
+ pagination (``page_size``, ``page_token``), ``filter``, and
+ ``order_by``. Top-level ``filter`` and ``order_by`` arguments
+ take precedence over values set in ``config``.
+
+ Returns:
+ The list evaluation metrics response.
+ """
+ if config is None:
+ config = types.ListEvaluationMetricsConfig()
+ if isinstance(config, dict):
+ config = types.ListEvaluationMetricsConfig.model_validate(config)
+ if filter is not None:
+ config.filter = filter
+ if order_by is not None:
+ config.order_by = order_by
+ return await self._list_evaluation_metrics(
+ config=config,
+ )
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI evals.delete_evaluation_metric method is experimental, "
+ "and may change in future versions."
+ )
+ async def delete_evaluation_metric(
+ self,
+ *,
+ metric_resource_name: str,
+ config: Optional[types.DeleteEvaluationMetricConfigOrDict] = None,
+ ) -> None:
+ """Deletes an EvaluationMetric.
+
+ Args:
+ metric_resource_name: The resource name of the EvaluationMetric to delete.
+ Format:
+ `projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric}`
+ config: The optional configuration for the delete operation.
+ """
+ await self._delete_evaluation_metric(
+ metric_resource_name=metric_resource_name,
+ config=config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/live.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/live.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a4bbbf0066a80c5dcec093dd2c50547046d7e78
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/live.py
@@ -0,0 +1,64 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""[Preview] Live API client."""
+
+import importlib
+import logging
+
+from typing import Optional, TYPE_CHECKING
+from types import ModuleType
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._api_client import BaseApiClient
+
+logger = logging.getLogger("google_genai.live")
+
+if TYPE_CHECKING:
+ from agentplatform._genai import (
+ live_agent_engines as live_agent_engines_module,
+ )
+
+
+class AsyncLive(_api_module.BaseModule):
+ """[Preview] AsyncLive."""
+
+ def __init__(self, api_client: BaseApiClient):
+ super().__init__(api_client)
+ self._agent_engines: Optional[ModuleType] = None
+
+ @property
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI agent engines module is experimental, "
+ "and may change in future versions."
+ )
+ def agent_engines(self) -> "live_agent_engines_module.AsyncLiveAgentEngines":
+ if self._agent_engines is None:
+ try:
+ # We need to lazy load the live_agent_engines module to handle
+ # the possibility of ImportError when dependencies are not
+ # installed.
+ self._agent_engines = importlib.import_module(
+ ".live_agent_engines",
+ __package__,
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines' module requires 'additional packages'. "
+ "Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._agent_engines.AsyncLiveAgentEngines(self._api_client) # type: ignore[no-any-return]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/live_agent_engines.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/live_agent_engines.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed79ed5d0c15aacc077028305c40e7eb35b5c5fa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/live_agent_engines.py
@@ -0,0 +1,179 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Live AgentEngine API client."""
+
+import contextlib
+import json
+from typing import Any, AsyncIterator, Dict, Optional
+import google.auth
+
+from google.genai import _api_module
+from .types import QueryAgentEngineConfig, QueryAgentEngineConfigOrDict
+
+
+try:
+ from websockets.asyncio.client import ClientConnection
+ from websockets.asyncio.client import connect as ws_connect
+except ModuleNotFoundError:
+ # This try/except is for TAP, mypy complains about it which is why we have the type: ignore
+ from websockets.client import ClientConnection # type: ignore
+ from websockets.client import connect as ws_connect # type: ignore
+
+
+class AsyncLiveAgentEngineSession:
+ """AsyncLiveAgentEngineSession."""
+
+ def __init__(self, websocket: ClientConnection):
+ self._ws = websocket
+
+ async def send(self, query_input: Dict[str, Any]) -> None:
+ """Send a query input to the Agent.
+
+ Args:
+ query_input: A JSON serializable Python Dict to be send to the Agent.
+ """
+
+ try:
+ json_request = json.dumps({"bidi_stream_input": query_input})
+ except Exception as exc:
+ raise ValueError(
+ "Failed to encode query input to JSON in live_agent_engines: "
+ f"{str(query_input)}"
+ ) from exc
+ await self._ws.send(json_request)
+
+ async def receive(self) -> Any:
+ """Receive one response from the Agent.
+
+ Returns:
+ A response from the Agent.
+
+ Raises:
+ websockets.exceptions.ConnectionClosed: If the connection is closed.
+ """
+
+ response = await self._ws.recv()
+ try:
+ return json.loads(response)
+ except json.decoder.JSONDecodeError as exc:
+ raise ValueError(
+ "Failed to parse response to JSON in live_agent_engines: "
+ f"{str(response)}"
+ ) from exc
+
+ async def close(self) -> None:
+ """Close the connection."""
+ await self._ws.close()
+
+
+class AsyncLiveAgentEngines(_api_module.BaseModule):
+ """AsyncLiveAgentEngines.
+
+ Example usage:
+
+ .. code-block:: python
+
+ from pathlib import Path
+
+ from google import genai
+ from google.genai import types
+
+ class MyAgentEngine(client):
+ def bidi_stream_query(self, input_queue: asyncio.Queue):
+ while True:
+ input = await input_queue.get()
+ yield {"output": f"Agent received {input}!"}
+
+ client = agentplatform.Client(project="my-project", location="us-central1")
+ agent_engine = client.agent_engines.create(agent)
+
+ async with client.aio.live.agent_engines.connect(
+ agent_engine=agent_engine.api_resource.name,
+ setup={"class_method": "bidi_stream_query"},
+ ) as session:
+ await session.send(input={"input": "Hello world"})
+
+ response = await session.receive()
+ # {"output": "Agent received Hello world!"}
+ ...
+ """
+
+ @contextlib.asynccontextmanager
+ async def connect(
+ self,
+ *,
+ agent_engine: str,
+ config: Optional[QueryAgentEngineConfigOrDict] = None,
+ ) -> AsyncIterator[AsyncLiveAgentEngineSession]:
+ """Connect to the agent deployed to Agent Engine in a live (bidirectional streaming) session.
+
+ Args:
+ agent_engine: The resource name of the Agent Engine to use for the
+ live session.
+ config: The optional configuration for starting the live Agent Engine
+ session. Custom class_method and an optional initial input could be
+ provided. If no class_method is provided, the default class_method
+ "bidi_stream_query" will be used by the Agent Engine.
+
+ Yields:
+ An AsyncLiveAgentEngineSession object.
+ """
+ if isinstance(config, dict):
+ config = QueryAgentEngineConfig(**config)
+
+ agent_engine_resource_name = agent_engine
+ if not agent_engine_resource_name.startswith("projects/"):
+ agent_engine_resource_name = f"projects/{self._api_client.project}/locations/{self._api_client.location}/reasoningEngines/{agent_engine}"
+ request_dict = {"setup": {"name": agent_engine_resource_name}}
+ if config is not None and config.class_method:
+ request_dict["setup"]["class_method"] = config.class_method
+ if config is not None and config.input:
+ request_dict["setup"]["input"] = config.input # type: ignore[assignment]
+
+ request = json.dumps(request_dict)
+
+ if not self._api_client._credentials:
+ # Get bearer token through Application Default Credentials.
+ creds, _ = google.auth.default(
+ scopes=["https://www.googleapis.com/auth/cloud-platform"]
+ )
+ else:
+ creds = self._api_client._credentials
+ # creds.valid is False, and creds.token is None
+ # Need to refresh credentials to populate those
+ if not (creds.token and creds.valid):
+ auth_req = google.auth.transport.requests.Request()
+ creds.refresh(auth_req) # type: ignore[no-untyped-call]
+ bearer_token = creds.token
+
+ original_headers = self._api_client._http_options.headers
+ headers = original_headers.copy() if original_headers is not None else {}
+ headers["Authorization"] = f"Bearer {bearer_token}"
+
+ base_url = self._api_client._websocket_base_url()
+ if isinstance(base_url, bytes):
+ base_url = base_url.decode("utf-8")
+ uri = (
+ f"{base_url}/ws/google.cloud.aiplatform."
+ f"{self._api_client._http_options.api_version}"
+ ".ReasoningEngineExecutionService/BidiQueryReasoningEngine"
+ )
+
+ async with ws_connect(
+ uri, additional_headers=headers, **self._api_client._websocket_ssl_ctx
+ ) as ws:
+ await ws.send(request)
+ yield AsyncLiveAgentEngineSession(websocket=ws)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/memories.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/memories.py
new file mode 100644
index 0000000000000000000000000000000000000000..37dda18b38b9a2442975d52d3e41fb34bcfc19dc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/memories.py
@@ -0,0 +1,3427 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import importlib
+import json
+import logging
+import typing
+from typing import Any, Iterator, List, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import _agent_engines_utils
+from . import types
+
+if typing.TYPE_CHECKING:
+ from . import memory_revisions as memory_revisions_module
+
+ _ = memory_revisions_module
+
+
+logger = logging.getLogger("agentplatform_genai.memories")
+
+logger.setLevel(logging.INFO)
+
+
+def _AgentEngineMemoryConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["ttl"]) is not None:
+ setv(parent_object, ["ttl"], getv(from_object, ["ttl"]))
+
+ if getv(from_object, ["expire_time"]) is not None:
+ setv(parent_object, ["expireTime"], getv(from_object, ["expire_time"]))
+
+ if getv(from_object, ["revision_expire_time"]) is not None:
+ setv(
+ parent_object,
+ ["revisionExpireTime"],
+ getv(from_object, ["revision_expire_time"]),
+ )
+
+ if getv(from_object, ["revision_ttl"]) is not None:
+ setv(parent_object, ["revisionTtl"], getv(from_object, ["revision_ttl"]))
+
+ if getv(from_object, ["disable_memory_revisions"]) is not None:
+ setv(
+ parent_object,
+ ["disableMemoryRevisions"],
+ getv(from_object, ["disable_memory_revisions"]),
+ )
+
+ if getv(from_object, ["topics"]) is not None:
+ setv(
+ parent_object, ["topics"], [item for item in getv(from_object, ["topics"])]
+ )
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(
+ parent_object,
+ ["metadata"],
+ {k: v for k, v in getv(from_object, ["metadata"]).items()},
+ )
+
+ if getv(from_object, ["memory_id"]) is not None:
+ setv(parent_object, ["_query", "memoryId"], getv(from_object, ["memory_id"]))
+
+ return to_object
+
+
+def _CreateAgentEngineMemoryRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["fact"]) is not None:
+ setv(to_object, ["fact"], getv(from_object, ["fact"]))
+
+ if getv(from_object, ["scope"]) is not None:
+ setv(to_object, ["scope"], getv(from_object, ["scope"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _AgentEngineMemoryConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _DeleteAgentEngineMemoryRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GenerateAgentEngineMemoriesConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["disable_consolidation"]) is not None:
+ setv(
+ parent_object,
+ ["disableConsolidation"],
+ getv(from_object, ["disable_consolidation"]),
+ )
+
+ if getv(from_object, ["revision_labels"]) is not None:
+ setv(parent_object, ["revisionLabels"], getv(from_object, ["revision_labels"]))
+
+ if getv(from_object, ["revision_expire_time"]) is not None:
+ setv(
+ parent_object,
+ ["revisionExpireTime"],
+ getv(from_object, ["revision_expire_time"]),
+ )
+
+ if getv(from_object, ["revision_ttl"]) is not None:
+ setv(parent_object, ["revisionTtl"], getv(from_object, ["revision_ttl"]))
+
+ if getv(from_object, ["disable_memory_revisions"]) is not None:
+ setv(
+ parent_object,
+ ["disableMemoryRevisions"],
+ getv(from_object, ["disable_memory_revisions"]),
+ )
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(
+ parent_object,
+ ["metadata"],
+ {k: v for k, v in getv(from_object, ["metadata"]).items()},
+ )
+
+ if getv(from_object, ["metadata_merge_strategy"]) is not None:
+ setv(
+ parent_object,
+ ["metadataMergeStrategy"],
+ getv(from_object, ["metadata_merge_strategy"]),
+ )
+
+ if getv(from_object, ["allowed_topics"]) is not None:
+ setv(
+ parent_object,
+ ["allowedTopics"],
+ [item for item in getv(from_object, ["allowed_topics"])],
+ )
+
+ return to_object
+
+
+def _GenerateAgentEngineMemoriesRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["vertex_session_source"]) is not None:
+ setv(
+ to_object,
+ ["vertexSessionSource"],
+ getv(from_object, ["vertex_session_source"]),
+ )
+
+ if getv(from_object, ["direct_contents_source"]) is not None:
+ setv(
+ to_object,
+ ["directContentsSource"],
+ getv(from_object, ["direct_contents_source"]),
+ )
+
+ if getv(from_object, ["direct_memories_source"]) is not None:
+ setv(
+ to_object,
+ ["directMemoriesSource"],
+ getv(from_object, ["direct_memories_source"]),
+ )
+
+ if getv(from_object, ["scope"]) is not None:
+ setv(to_object, ["scope"], getv(from_object, ["scope"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _GenerateAgentEngineMemoriesConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+def _GetAgentEngineGenerateMemoriesOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetAgentEngineMemoryOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetAgentEngineMemoryRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _IngestEventsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["force_flush"]) is not None:
+ setv(parent_object, ["forceFlush"], getv(from_object, ["force_flush"]))
+
+ return to_object
+
+
+def _IngestEventsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["stream_id"]) is not None:
+ setv(to_object, ["streamId"], getv(from_object, ["stream_id"]))
+
+ if getv(from_object, ["direct_contents_source"]) is not None:
+ setv(
+ to_object,
+ ["directContentsSource"],
+ getv(from_object, ["direct_contents_source"]),
+ )
+
+ if getv(from_object, ["scope"]) is not None:
+ setv(to_object, ["scope"], getv(from_object, ["scope"]))
+
+ if getv(from_object, ["generation_trigger_config"]) is not None:
+ setv(
+ to_object,
+ ["generationTriggerConfig"],
+ getv(from_object, ["generation_trigger_config"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ _IngestEventsConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _ListAgentEngineMemoryConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ if getv(from_object, ["order_by"]) is not None:
+ setv(parent_object, ["_query", "orderBy"], getv(from_object, ["order_by"]))
+
+ return to_object
+
+
+def _ListAgentEngineMemoryRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineMemoryConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _PurgeAgentEngineMemoriesRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(to_object, ["filter"], getv(from_object, ["filter"]))
+
+ if getv(from_object, ["filter_groups"]) is not None:
+ setv(
+ to_object,
+ ["filterGroups"],
+ [item for item in getv(from_object, ["filter_groups"])],
+ )
+
+ if getv(from_object, ["force"]) is not None:
+ setv(to_object, ["force"], getv(from_object, ["force"]))
+
+ return to_object
+
+
+def _RetrieveAgentEngineMemoriesConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["filter"], getv(from_object, ["filter"]))
+
+ if getv(from_object, ["filter_groups"]) is not None:
+ setv(
+ parent_object,
+ ["filterGroups"],
+ [item for item in getv(from_object, ["filter_groups"])],
+ )
+
+ if getv(from_object, ["memory_types"]) is not None:
+ setv(parent_object, ["memoryTypes"], getv(from_object, ["memory_types"]))
+
+ return to_object
+
+
+def _RetrieveAgentEngineMemoriesRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["scope"]) is not None:
+ setv(to_object, ["scope"], getv(from_object, ["scope"]))
+
+ if getv(from_object, ["similarity_search_params"]) is not None:
+ setv(
+ to_object,
+ ["similaritySearchParams"],
+ getv(from_object, ["similarity_search_params"]),
+ )
+
+ if getv(from_object, ["simple_retrieval_params"]) is not None:
+ setv(
+ to_object,
+ ["simpleRetrievalParams"],
+ getv(from_object, ["simple_retrieval_params"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ _RetrieveAgentEngineMemoriesConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+def _RetrieveMemoryProfilesRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["scope"]) is not None:
+ setv(to_object, ["scope"], getv(from_object, ["scope"]))
+
+ return to_object
+
+
+def _RollbackAgentEngineMemoryRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["target_revision_id"]) is not None:
+ setv(to_object, ["targetRevisionId"], getv(from_object, ["target_revision_id"]))
+
+ return to_object
+
+
+def _UpdateAgentEngineMemoryConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["ttl"]) is not None:
+ setv(parent_object, ["ttl"], getv(from_object, ["ttl"]))
+
+ if getv(from_object, ["expire_time"]) is not None:
+ setv(parent_object, ["expireTime"], getv(from_object, ["expire_time"]))
+
+ if getv(from_object, ["revision_expire_time"]) is not None:
+ setv(
+ parent_object,
+ ["revisionExpireTime"],
+ getv(from_object, ["revision_expire_time"]),
+ )
+
+ if getv(from_object, ["revision_ttl"]) is not None:
+ setv(parent_object, ["revisionTtl"], getv(from_object, ["revision_ttl"]))
+
+ if getv(from_object, ["disable_memory_revisions"]) is not None:
+ setv(
+ parent_object,
+ ["disableMemoryRevisions"],
+ getv(from_object, ["disable_memory_revisions"]),
+ )
+
+ if getv(from_object, ["topics"]) is not None:
+ setv(
+ parent_object, ["topics"], [item for item in getv(from_object, ["topics"])]
+ )
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(
+ parent_object,
+ ["metadata"],
+ {k: v for k, v in getv(from_object, ["metadata"]).items()},
+ )
+
+ if getv(from_object, ["memory_id"]) is not None:
+ setv(parent_object, ["_query", "memoryId"], getv(from_object, ["memory_id"]))
+
+ if getv(from_object, ["update_mask"]) is not None:
+ setv(
+ parent_object, ["_query", "updateMask"], getv(from_object, ["update_mask"])
+ )
+
+ return to_object
+
+
+def _UpdateAgentEngineMemoryRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["fact"]) is not None:
+ setv(to_object, ["fact"], getv(from_object, ["fact"]))
+
+ if getv(from_object, ["scope"]) is not None:
+ setv(to_object, ["scope"], getv(from_object, ["scope"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _UpdateAgentEngineMemoryConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class Memories(_api_module.BaseModule):
+
+ def _create(
+ self,
+ *,
+ name: str,
+ fact: str,
+ scope: dict[str, str],
+ config: Optional[types.AgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ """
+ Creates a new memory in the Agent Engine.
+ """
+
+ parameter_model = types._CreateAgentEngineMemoryRequestParameters(
+ name=name,
+ fact=fact,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories".format_map(request_url_dict)
+ else:
+ path = "{name}/memories"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineMemoryOperation:
+ """
+ Delete an Agent Engine memory.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine memory to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory}`.
+ config (DeleteAgentEngineMemoryConfig):
+ Optional. Additional configurations for deleting the Agent Engine.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineMemoryRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _generate(
+ self,
+ *,
+ name: str,
+ vertex_session_source: Optional[
+ types.GenerateMemoriesRequestVertexSessionSourceOrDict
+ ] = None,
+ direct_contents_source: Optional[
+ types.GenerateMemoriesRequestDirectContentsSourceOrDict
+ ] = None,
+ direct_memories_source: Optional[
+ types.GenerateMemoriesRequestDirectMemoriesSourceOrDict
+ ] = None,
+ scope: Optional[dict[str, str]] = None,
+ config: Optional[types.GenerateAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEngineGenerateMemoriesOperation:
+ """
+ Generates memories for an Agent Engine.
+ """
+
+ parameter_model = types._GenerateAgentEngineMemoriesRequestParameters(
+ name=name,
+ vertex_session_source=vertex_session_source,
+ direct_contents_source=direct_contents_source,
+ direct_memories_source=direct_memories_source,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateAgentEngineMemoriesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:generate".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:generate"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineGenerateMemoriesOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.Memory:
+ """
+ Gets an agent engine memory.
+
+ Args:
+ name (str): Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456/memories/789"
+ or a shortened name such as "reasoningEngines/456/memories/789".
+
+ """
+
+ parameter_model = types._GetAgentEngineMemoryRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Memory._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _ingest_events(
+ self,
+ *,
+ name: str,
+ stream_id: Optional[str] = None,
+ direct_contents_source: Optional[
+ types.IngestionDirectContentsSourceOrDict
+ ] = None,
+ scope: Optional[dict[str, str]] = None,
+ generation_trigger_config: Optional[
+ types.MemoryGenerationTriggerConfigOrDict
+ ] = None,
+ config: Optional[types.IngestEventsConfigOrDict] = None,
+ ) -> types.MemoryBankIngestEventsOperation:
+ """
+ Ingest events into a Memory Bank.
+ """
+
+ parameter_model = types._IngestEventsRequestParameters(
+ name=name,
+ stream_id=stream_id,
+ direct_contents_source=direct_contents_source,
+ scope=scope,
+ generation_trigger_config=generation_trigger_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _IngestEventsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:ingestEvents".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:ingestEvents"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MemoryBankIngestEventsOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.ListReasoningEnginesMemoriesResponse:
+ """
+ Lists Agent Engine memories.
+ """
+
+ parameter_model = types._ListAgentEngineMemoryRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories".format_map(request_url_dict)
+ else:
+ path = "{name}/memories"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListReasoningEnginesMemoriesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_memory_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ parameter_model = types._GetAgentEngineMemoryOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineMemoryOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_generate_memories_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineGenerateMemoriesOperation:
+ parameter_model = types._GetAgentEngineGenerateMemoriesOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineGenerateMemoriesOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineGenerateMemoriesOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _retrieve(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ similarity_search_params: Optional[
+ types.RetrieveMemoriesRequestSimilaritySearchParamsOrDict
+ ] = None,
+ simple_retrieval_params: Optional[
+ types.RetrieveMemoriesRequestSimpleRetrievalParamsOrDict
+ ] = None,
+ config: Optional[types.RetrieveAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.RetrieveMemoriesResponse:
+ """
+ Retrieves memories for an Agent Engine.
+ """
+
+ parameter_model = types._RetrieveAgentEngineMemoriesRequestParameters(
+ name=name,
+ scope=scope,
+ similarity_search_params=similarity_search_params,
+ simple_retrieval_params=simple_retrieval_params,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RetrieveAgentEngineMemoriesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:retrieve".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:retrieve"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RetrieveMemoriesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def retrieve_profiles(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ config: Optional[types.RetrieveMemoryProfilesConfigOrDict] = None,
+ ) -> types.RetrieveProfilesResponse:
+ """
+ Retrieves memory profiles for an Agent Engine.
+
+ For example, you can use the following code to retrieve all memory profiles
+ for scope `{'user_id': '123'}`:
+
+ ```python
+ result = client.agent_engines.memories.retrieve_profiles(
+ name="projects/123/locations/us-central1/reasoningEngines/456",
+ scope={"user_id": "123"}
+ )
+
+ for profile in result.profiles.values():
+ # Each profile is a dictionary corresponding to the relevant schema.
+ print(profile.profile)
+ ```
+
+ Args:
+ name (str): Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456".
+ scope (dict[str, str]): Required. The scope of the memories to retrieve.
+ A memory must have exactly the same scope as the scope provided here
+ to be retrieved (i.e. same keys and values). Order does not matter,
+ but it is case-sensitive.
+
+ Returns:
+ RetrieveProfilesResponse: The retrieved memory profiles.
+
+ """
+
+ parameter_model = types._RetrieveMemoryProfilesRequestParameters(
+ name=name,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RetrieveMemoryProfilesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:retrieveProfiles".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:retrieveProfiles"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RetrieveProfilesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _rollback(
+ self,
+ *,
+ name: str,
+ target_revision_id: str,
+ config: Optional[types.RollbackAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineRollbackMemoryOperation:
+ """
+ Rollback a memory to a previous revision.
+ """
+
+ parameter_model = types._RollbackAgentEngineMemoryRequestParameters(
+ name=name,
+ target_revision_id=target_revision_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RollbackAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:rollback".format_map(request_url_dict)
+ else:
+ path = "{name}:rollback"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineRollbackMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _update(
+ self,
+ *,
+ name: str,
+ fact: Optional[str] = None,
+ scope: Optional[dict[str, str]] = None,
+ config: Optional[types.UpdateAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ """
+ Updates an Agent Engine memory.
+ """
+
+ parameter_model = types._UpdateAgentEngineMemoryRequestParameters(
+ name=name,
+ fact=fact,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("patch", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _purge(
+ self,
+ *,
+ name: str,
+ filter: Optional[str] = None,
+ filter_groups: Optional[list[types.MemoryConjunctionFilterOrDict]] = None,
+ force: Optional[bool] = None,
+ config: Optional[types.PurgeAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEnginePurgeMemoriesOperation:
+ """
+ Purges memories from an Agent Engine.
+ """
+
+ parameter_model = types._PurgeAgentEngineMemoriesRequestParameters(
+ name=name,
+ filter=filter,
+ filter_groups=filter_groups,
+ force=force,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _PurgeAgentEngineMemoriesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:purge".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:purge"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEnginePurgeMemoriesOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _revisions = None
+
+ @property
+ def revisions(self) -> "memory_revisions_module.MemoryRevisions":
+ if self._revisions is None:
+ try:
+ # We need to lazy load the revisions module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._revisions = importlib.import_module(
+ ".memory_revisions", __package__
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.memories.revisions' module requires "
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._revisions.MemoryRevisions(self._api_client) # type: ignore[no-any-return]
+
+ def create(
+ self,
+ *,
+ name: str,
+ fact: str,
+ scope: dict[str, str],
+ config: Optional[types.AgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ """Creates a new memory in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the memory to create.
+ fact (str):
+ Required. The fact to be stored in the memory.
+ scope (dict[str, str]):
+ Required. The scope of the memory. For example, {"user_id": "123"}.
+ config (AgentEngineMemoryConfigOrDict):
+ Optional. The configuration for the memory.
+
+ Returns:
+ AgentEngineMemoryOperation: The operation for creating the memory.
+ """
+ if config is None:
+ config = types.AgentEngineMemoryConfig()
+ elif isinstance(config, dict):
+ config = types.AgentEngineMemoryConfig.model_validate(config)
+ operation = self._create(
+ name=name,
+ fact=fact,
+ scope=scope,
+ config=config,
+ )
+ if config.wait_for_completion:
+ if not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ # We need to make a call to get the memory because the operation
+ # response might not contain the relevant fields.
+ if operation.response:
+ operation.response = self.get(name=operation.response.name)
+ elif operation.error:
+ raise RuntimeError(f"Failed to create memory: {operation.error}")
+ else:
+ raise RuntimeError("Error creating memory.")
+ return operation
+
+ def generate(
+ self,
+ *,
+ name: str,
+ vertex_session_source: Optional[
+ types.GenerateMemoriesRequestVertexSessionSourceOrDict
+ ] = None,
+ direct_contents_source: Optional[
+ types.GenerateMemoriesRequestDirectContentsSourceOrDict
+ ] = None,
+ direct_memories_source: Optional[
+ types.GenerateMemoriesRequestDirectMemoriesSourceOrDict
+ ] = None,
+ scope: Optional[dict[str, str]] = None,
+ config: Optional[types.GenerateAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEngineGenerateMemoriesOperation:
+ """Generates memories for the agent engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to generate memories for.
+ vertex_session_source (GenerateMemoriesRequestVertexSessionSource):
+ Optional. The vertex session source to use for generating
+ memories. Only one of vertex_session_source,
+ direct_contents_source, or direct_memories_source can be
+ specified.
+ direct_contents_source(GenerateMemoriesRequestDirectContentsSource):
+ Optional. The direct contents source to use for generating
+ memories. Only one of vertex_session_source, direct_contents_source,
+ or direct_memories_source can be specified.
+ direct_memories_source (GenerateMemoriesRequestDirectMemoriesSource):
+ Optional. The direct memories source to use for generating
+ memories. Only one of vertex_session_source, direct_contents_source,
+ or direct_memories_source can be specified.
+ scope (dict[str, str]):
+ Optional. The scope of the memories to generate. This is optional
+ if vertex_session_source is used, otherwise it must be specified.
+ config (GenerateMemoriesConfig):
+ Optional. The configuration for the memories to generate.
+
+ Returns:
+ AgentEngineGenerateMemoriesOperation:
+ The operation for generating the memories.
+ """
+ if config is None:
+ config = types.GenerateAgentEngineMemoriesConfig()
+ elif isinstance(config, dict):
+ config = types.GenerateAgentEngineMemoriesConfig.model_validate(config)
+ operation = self._generate(
+ name=name,
+ vertex_session_source=vertex_session_source,
+ direct_contents_source=direct_contents_source,
+ direct_memories_source=direct_memories_source,
+ scope=scope,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_generate_memories_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to generate memory: {operation.error}")
+ return operation
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryConfigOrDict] = None,
+ ) -> Iterator[types.Memory]:
+ """Lists Agent Engine memories.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list memories for.
+ config (ListAgentEngineMemoryConfig):
+ Optional. The configuration for the memories to list.
+
+ Returns:
+ Iterable[Memory]: An iterable of memories.
+ """
+
+ return Pager(
+ "memories",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+ def retrieve(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ similarity_search_params: Optional[
+ types.RetrieveMemoriesRequestSimilaritySearchParamsOrDict
+ ] = None,
+ simple_retrieval_params: Optional[
+ types.RetrieveMemoriesRequestSimpleRetrievalParamsOrDict
+ ] = None,
+ config: Optional[types.RetrieveAgentEngineMemoriesConfigOrDict] = None,
+ ) -> Iterator[types.RetrieveMemoriesResponseRetrievedMemory]:
+ """Retrieves memories for the agent.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to retrieve memories for.
+ scope (dict[str, str]):
+ Required. The scope of the memories to retrieve. For example,
+ {"user_id": "123"}.
+ similarity_search_params (RetrieveMemoriesRequestSimilaritySearchParams):
+ Optional. The similarity search parameters to use for retrieving
+ memories.
+ simple_retrieval_params (RetrieveMemoriesRequestSimpleRetrievalParams):
+ Optional. The simple retrieval parameters to use for retrieving
+ memories.
+ config (RetrieveAgentEngineMemoriesConfig):
+ Optional. The configuration for the memories to retrieve.
+
+ Returns:
+ Iterator[RetrieveMemoriesResponseRetrievedMemory]: An iterable of
+ retrieved memories.
+ """
+ return Pager(
+ "retrieved_memories",
+ lambda config: self._retrieve(
+ name=name,
+ similarity_search_params=similarity_search_params,
+ simple_retrieval_params=simple_retrieval_params,
+ scope=scope,
+ config=config,
+ ),
+ self._retrieve(
+ name=name,
+ similarity_search_params=similarity_search_params,
+ simple_retrieval_params=simple_retrieval_params,
+ scope=scope,
+ config=config,
+ ),
+ config,
+ )
+
+ def rollback(
+ self,
+ *,
+ name: str,
+ target_revision_id: str,
+ config: Optional[types.RollbackAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineRollbackMemoryOperation:
+ """Rolls back a memory to a previous revision.
+
+ Args:
+ name (str):
+ Required. The name of the memory to rollback.
+ target_revision_id (str):
+ Required. The revision ID to roll back to
+ config (RollbackAgentEngineMemoryConfig):
+ Optional. The configuration for the rollback.
+
+ Returns:
+ AgentEngineRollbackMemoryOperation:
+ The operation for rolling back the memory.
+ """
+ if config is None:
+ config = types.RollbackAgentEngineMemoryConfig()
+ elif isinstance(config, dict):
+ config = types.RollbackAgentEngineMemoryConfig.model_validate(config)
+ operation = self._rollback(
+ name=name,
+ target_revision_id=target_revision_id,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to rollback memory: {operation.error}")
+ return operation
+
+ def purge(
+ self,
+ *,
+ name: str,
+ filter: Optional[str] = None,
+ filter_groups: Optional[List[types.MemoryConjunctionFilter]] = None,
+ force: bool = False,
+ config: Optional[types.PurgeAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEnginePurgeMemoriesOperation:
+ """Purges memories from an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to purge memories from.
+ filter (str):
+ Optional. The standard list filter to determine which memories to purge.
+ filter_groups (list[MemoryConjunctionFilter]):
+ Optional. Metadata filters that will be applied to the memories'
+ `metadata` using OR logic. Filters are defined using disjunctive
+ normal form (OR of ANDs).
+ force (bool):
+ Optional. Whether to force the purge operation. If false, the
+ operation will be staged but not executed.
+ config (PurgeAgentEngineMemoriesConfig):
+ Optional. The configuration for the purge operation.
+
+ Returns:
+ AgentEnginePurgeMemoriesOperation:
+ The operation for purging the memories.
+ """
+ if config is None:
+ config = types.PurgeAgentEngineMemoriesConfig()
+ elif isinstance(config, dict):
+ config = types.PurgeAgentEngineMemoriesConfig.model_validate(config)
+ operation = self._purge(
+ name=name,
+ filter=filter,
+ filter_groups=filter_groups,
+ force=force,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to purge memories: {operation.error}")
+ return operation
+
+ def ingest_events(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ stream_id: str = "",
+ direct_contents_source: Optional[
+ types.IngestionDirectContentsSourceOrDict
+ ] = None,
+ generation_trigger_config: Optional[
+ types.MemoryGenerationTriggerConfigOrDict
+ ] = None,
+ config: Optional[types.IngestEventsConfigOrDict] = None,
+ ) -> types.MemoryBankIngestEventsOperation:
+ """Ingests events into an Agent Engine.
+
+ Example usage:
+ ```
+ client.agent_engines.memories.ingest_events(
+ name="projects/test-project/locations/us-central1/reasoningEngines/test-agent-engine",
+ scope={"user_id": "test-user-id"},
+ direct_contents_source={
+ "events": [
+ {
+ "content": {
+ "role": "user",
+ "parts": [
+ {"text": "I am a software engineer."}
+ ],
+ }
+ }
+ ]
+ },
+ generation_trigger_config={
+ "generation_rule": {
+ "idle_duration": "60s"
+ }
+ }
+ )
+ ```
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to ingest events into.
+ scope (dict[str, str]):
+ Required. The scope of the events to ingest. For example,
+ {"user_id": "123"}.
+ stream_id (str):
+ Optional. The ID of the stream to ingest events into. If not
+ specified, the events will be ingested into the default stream.
+ direct_contents_source (IngestionDirectContentsSource):
+ The direct contents source, containing the events to ingest.
+ generation_trigger_config (MemoryGenerationTriggerConfig):
+ Optional. The configuration for the generation trigger config.
+ config (IngestEventsConfig):
+ Optional. The configuration for the ingest events operation.
+
+ Returns:
+ AgentEngineIngestEventsOperation:
+ The operation for ingesting the events.
+ """
+ if config is None:
+ config = types.IngestEventsConfig()
+ elif isinstance(config, dict):
+ config = types.IngestEventsConfig.model_validate(config)
+ operation = self._ingest_events(
+ name=name,
+ scope=scope,
+ stream_id=stream_id,
+ generation_trigger_config=generation_trigger_config,
+ direct_contents_source=direct_contents_source,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to ingest events: {operation.error}")
+ return operation
+
+
+class AsyncMemories(_api_module.BaseModule):
+
+ async def _create(
+ self,
+ *,
+ name: str,
+ fact: str,
+ scope: dict[str, str],
+ config: Optional[types.AgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ """
+ Creates a new memory in the Agent Engine.
+ """
+
+ parameter_model = types._CreateAgentEngineMemoryRequestParameters(
+ name=name,
+ fact=fact,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories".format_map(request_url_dict)
+ else:
+ path = "{name}/memories"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineMemoryOperation:
+ """
+ Delete an Agent Engine memory.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine memory to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory}`.
+ config (DeleteAgentEngineMemoryConfig):
+ Optional. Additional configurations for deleting the Agent Engine.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineMemoryRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _generate(
+ self,
+ *,
+ name: str,
+ vertex_session_source: Optional[
+ types.GenerateMemoriesRequestVertexSessionSourceOrDict
+ ] = None,
+ direct_contents_source: Optional[
+ types.GenerateMemoriesRequestDirectContentsSourceOrDict
+ ] = None,
+ direct_memories_source: Optional[
+ types.GenerateMemoriesRequestDirectMemoriesSourceOrDict
+ ] = None,
+ scope: Optional[dict[str, str]] = None,
+ config: Optional[types.GenerateAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEngineGenerateMemoriesOperation:
+ """
+ Generates memories for an Agent Engine.
+ """
+
+ parameter_model = types._GenerateAgentEngineMemoriesRequestParameters(
+ name=name,
+ vertex_session_source=vertex_session_source,
+ direct_contents_source=direct_contents_source,
+ direct_memories_source=direct_memories_source,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GenerateAgentEngineMemoriesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:generate".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:generate"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineGenerateMemoriesOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.Memory:
+ """
+ Gets an agent engine memory.
+
+ Args:
+ name (str): Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456/memories/789"
+ or a shortened name such as "reasoningEngines/456/memories/789".
+
+ """
+
+ parameter_model = types._GetAgentEngineMemoryRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Memory._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _ingest_events(
+ self,
+ *,
+ name: str,
+ stream_id: Optional[str] = None,
+ direct_contents_source: Optional[
+ types.IngestionDirectContentsSourceOrDict
+ ] = None,
+ scope: Optional[dict[str, str]] = None,
+ generation_trigger_config: Optional[
+ types.MemoryGenerationTriggerConfigOrDict
+ ] = None,
+ config: Optional[types.IngestEventsConfigOrDict] = None,
+ ) -> types.MemoryBankIngestEventsOperation:
+ """
+ Ingest events into a Memory Bank.
+ """
+
+ parameter_model = types._IngestEventsRequestParameters(
+ name=name,
+ stream_id=stream_id,
+ direct_contents_source=direct_contents_source,
+ scope=scope,
+ generation_trigger_config=generation_trigger_config,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _IngestEventsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:ingestEvents".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:ingestEvents"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MemoryBankIngestEventsOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.ListReasoningEnginesMemoriesResponse:
+ """
+ Lists Agent Engine memories.
+ """
+
+ parameter_model = types._ListAgentEngineMemoryRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories".format_map(request_url_dict)
+ else:
+ path = "{name}/memories"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListReasoningEnginesMemoriesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_memory_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ parameter_model = types._GetAgentEngineMemoryOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineMemoryOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_generate_memories_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineGenerateMemoriesOperation:
+ parameter_model = types._GetAgentEngineGenerateMemoriesOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineGenerateMemoriesOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineGenerateMemoriesOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _retrieve(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ similarity_search_params: Optional[
+ types.RetrieveMemoriesRequestSimilaritySearchParamsOrDict
+ ] = None,
+ simple_retrieval_params: Optional[
+ types.RetrieveMemoriesRequestSimpleRetrievalParamsOrDict
+ ] = None,
+ config: Optional[types.RetrieveAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.RetrieveMemoriesResponse:
+ """
+ Retrieves memories for an Agent Engine.
+ """
+
+ parameter_model = types._RetrieveAgentEngineMemoriesRequestParameters(
+ name=name,
+ scope=scope,
+ similarity_search_params=similarity_search_params,
+ simple_retrieval_params=simple_retrieval_params,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RetrieveAgentEngineMemoriesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:retrieve".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:retrieve"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RetrieveMemoriesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def retrieve_profiles(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ config: Optional[types.RetrieveMemoryProfilesConfigOrDict] = None,
+ ) -> types.RetrieveProfilesResponse:
+ """
+ Retrieves memory profiles for an Agent Engine.
+
+ For example, you can use the following code to retrieve all memory profiles
+ for scope `{'user_id': '123'}`:
+
+ ```python
+ result = client.agent_engines.memories.retrieve_profiles(
+ name="projects/123/locations/us-central1/reasoningEngines/456",
+ scope={"user_id": "123"}
+ )
+
+ for profile in result.profiles.values():
+ # Each profile is a dictionary corresponding to the relevant schema.
+ print(profile.profile)
+ ```
+
+ Args:
+ name (str): Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456".
+ scope (dict[str, str]): Required. The scope of the memories to retrieve.
+ A memory must have exactly the same scope as the scope provided here
+ to be retrieved (i.e. same keys and values). Order does not matter,
+ but it is case-sensitive.
+
+ Returns:
+ RetrieveProfilesResponse: The retrieved memory profiles.
+
+ """
+
+ parameter_model = types._RetrieveMemoryProfilesRequestParameters(
+ name=name,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RetrieveMemoryProfilesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:retrieveProfiles".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:retrieveProfiles"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RetrieveProfilesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _rollback(
+ self,
+ *,
+ name: str,
+ target_revision_id: str,
+ config: Optional[types.RollbackAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineRollbackMemoryOperation:
+ """
+ Rollback a memory to a previous revision.
+ """
+
+ parameter_model = types._RollbackAgentEngineMemoryRequestParameters(
+ name=name,
+ target_revision_id=target_revision_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RollbackAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:rollback".format_map(request_url_dict)
+ else:
+ path = "{name}:rollback"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineRollbackMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _update(
+ self,
+ *,
+ name: str,
+ fact: Optional[str] = None,
+ scope: Optional[dict[str, str]] = None,
+ config: Optional[types.UpdateAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ """
+ Updates an Agent Engine memory.
+ """
+
+ parameter_model = types._UpdateAgentEngineMemoryRequestParameters(
+ name=name,
+ fact=fact,
+ scope=scope,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateAgentEngineMemoryRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "patch", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineMemoryOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _purge(
+ self,
+ *,
+ name: str,
+ filter: Optional[str] = None,
+ filter_groups: Optional[list[types.MemoryConjunctionFilterOrDict]] = None,
+ force: Optional[bool] = None,
+ config: Optional[types.PurgeAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEnginePurgeMemoriesOperation:
+ """
+ Purges memories from an Agent Engine.
+ """
+
+ parameter_model = types._PurgeAgentEngineMemoriesRequestParameters(
+ name=name,
+ filter=filter,
+ filter_groups=filter_groups,
+ force=force,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _PurgeAgentEngineMemoriesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/memories:purge".format_map(request_url_dict)
+ else:
+ path = "{name}/memories:purge"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEnginePurgeMemoriesOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _revisions = None
+
+ @property
+ def revisions(self) -> "memory_revisions_module.AsyncMemoryRevisions":
+ if self._revisions is None:
+ try:
+ # We need to lazy load the revisions module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._revisions = importlib.import_module(
+ ".memory_revisions", __package__
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.memories.revisions' module requires "
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._revisions.AsyncMemoryRevisions(self._api_client) # type: ignore[no-any-return]
+
+ async def create(
+ self,
+ *,
+ name: str,
+ fact: str,
+ scope: dict[str, str],
+ config: Optional[types.AgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineMemoryOperation:
+ """Creates a new memory in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the memory to create.
+ fact (str):
+ Required. The fact to be stored in the memory.
+ scope (dict[str, str]):
+ Required. The scope of the memory. For example, {"user_id": "123"}.
+ config (AgentEngineMemoryConfigOrDict):
+ Optional. The configuration for the memory.
+
+ Returns:
+ AgentEngineMemoryOperation: The operation for creating the memory.
+ """
+ if config is None:
+ config = types.AgentEngineMemoryConfig()
+ elif isinstance(config, dict):
+ config = types.AgentEngineMemoryConfig.model_validate(config)
+ operation = await self._create(
+ name=name,
+ fact=fact,
+ scope=scope,
+ config=config,
+ )
+ if config.wait_for_completion:
+ if not operation.done:
+ operation = await _agent_engines_utils._await_async_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ # We need to make a call to get the memory because the operation
+ # response might not contain the relevant fields.
+ if operation.response:
+ operation.response = await self.get(name=operation.response.name)
+ elif operation.error:
+ raise RuntimeError(f"Failed to create memory: {operation.error}")
+ else:
+ raise RuntimeError("Error creating memory.")
+ return operation
+
+ async def generate(
+ self,
+ *,
+ name: str,
+ vertex_session_source: Optional[
+ types.GenerateMemoriesRequestVertexSessionSourceOrDict
+ ] = None,
+ direct_contents_source: Optional[
+ types.GenerateMemoriesRequestDirectContentsSourceOrDict
+ ] = None,
+ direct_memories_source: Optional[
+ types.GenerateMemoriesRequestDirectMemoriesSourceOrDict
+ ] = None,
+ scope: Optional[dict[str, str]] = None,
+ config: Optional[types.GenerateAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEngineGenerateMemoriesOperation:
+ """Generates memories for the agent engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to generate memories for.
+ vertex_session_source (GenerateMemoriesRequestVertexSessionSource):
+ Optional. The vertex session source to use for generating
+ memories. Only one of vertex_session_source,
+ direct_contents_source, or direct_memories_source can be
+ specified.
+ direct_contents_source(GenerateMemoriesRequestDirectContentsSource):
+ Optional. The direct contents source to use for generating
+ memories. Only one of vertex_session_source, direct_contents_source,
+ or direct_memories_source can be specified.
+ direct_memories_source (GenerateMemoriesRequestDirectMemoriesSource):
+ Optional. The direct memories source to use for generating
+ memories. Only one of vertex_session_source, direct_contents_source,
+ or direct_memories_source can be specified.
+ scope (dict[str, str]):
+ Optional. The scope of the memories to generate. This is optional
+ if vertex_session_source is used, otherwise it must be specified.
+ config (GenerateMemoriesConfig):
+ Optional. The configuration for the memories to generate.
+
+ Returns:
+ AgentEngineGenerateMemoriesOperation:
+ The operation for generating the memories.
+ """
+ if config is None:
+ config = types.GenerateAgentEngineMemoriesConfig()
+ elif isinstance(config, dict):
+ config = types.GenerateAgentEngineMemoriesConfig.model_validate(config)
+ operation = await self._generate(
+ name=name,
+ vertex_session_source=vertex_session_source,
+ direct_contents_source=direct_contents_source,
+ direct_memories_source=direct_memories_source,
+ scope=scope,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = await _agent_engines_utils._await_async_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_generate_memories_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to generate memory: {operation.error}")
+ return operation
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryConfigOrDict] = None,
+ ) -> AsyncPager[types.Memory]:
+ """Lists Agent Engine memories.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list memories for.
+ config (ListAgentEngineMemoryConfig):
+ Optional. The configuration for the memories to list.
+
+ Returns:
+ AsyncPager[Memory]: An async pager of memories.
+ """
+
+ return AsyncPager(
+ "memories",
+ functools.partial(self._list, name=name),
+ await self._list(name=name, config=config),
+ config,
+ )
+
+ async def retrieve(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ similarity_search_params: Optional[
+ types.RetrieveMemoriesRequestSimilaritySearchParamsOrDict
+ ] = None,
+ simple_retrieval_params: Optional[
+ types.RetrieveMemoriesRequestSimpleRetrievalParamsOrDict
+ ] = None,
+ config: Optional[types.RetrieveAgentEngineMemoriesConfigOrDict] = None,
+ ) -> AsyncPager[types.RetrieveMemoriesResponseRetrievedMemory]:
+ """Retrieves memories for the agent.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to retrieve memories for.
+ scope (dict[str, str]):
+ Required. The scope of the memories to retrieve. For example,
+ {"user_id": "123"}.
+ similarity_search_params (RetrieveMemoriesRequestSimilaritySearchParams):
+ Optional. The similarity search parameters to use for retrieving
+ memories.
+ simple_retrieval_params (RetrieveMemoriesRequestSimpleRetrievalParams):
+ Optional. The simple retrieval parameters to use for retrieving
+ memories.
+ config (RetrieveAgentEngineMemoriesConfig):
+ Optional. The configuration for the memories to retrieve.
+
+ Returns:
+ AsyncPager[RetrieveMemoriesResponseRetrievedMemory]: An async pager of
+ retrieved memories.
+ """
+ return AsyncPager(
+ "retrieved_memories",
+ lambda config: self._retrieve(
+ name=name,
+ similarity_search_params=similarity_search_params,
+ simple_retrieval_params=simple_retrieval_params,
+ scope=scope,
+ config=config,
+ ),
+ await self._retrieve(
+ name=name,
+ similarity_search_params=similarity_search_params,
+ simple_retrieval_params=simple_retrieval_params,
+ scope=scope,
+ config=config,
+ ),
+ config,
+ )
+
+ async def rollback(
+ self,
+ *,
+ name: str,
+ target_revision_id: str,
+ config: Optional[types.RollbackAgentEngineMemoryConfigOrDict] = None,
+ ) -> types.AgentEngineRollbackMemoryOperation:
+ """Rolls back a memory to a previous revision.
+
+ Args:
+ name (str):
+ Required. The name of the memory to rollback.
+ target_revision_id (str):
+ Required. The revision ID to roll back to
+ config (RollbackAgentEngineMemoryConfig):
+ Optional. The configuration for the rollback.
+
+ Returns:
+ AgentEngineRollbackMemoryOperation:
+ The operation for rolling back the memory.
+ """
+ if config is None:
+ config = types.RollbackAgentEngineMemoryConfig()
+ elif isinstance(config, dict):
+ config = types.RollbackAgentEngineMemoryConfig.model_validate(config)
+ operation = await self._rollback(
+ name=name,
+ target_revision_id=target_revision_id,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = await _agent_engines_utils._await_async_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to rollback memory: {operation.error}")
+ return operation
+
+ async def purge(
+ self,
+ *,
+ name: str,
+ filter: Optional[str] = None,
+ filter_groups: Optional[List[types.MemoryConjunctionFilter]] = None,
+ force: bool = False,
+ config: Optional[types.PurgeAgentEngineMemoriesConfigOrDict] = None,
+ ) -> types.AgentEnginePurgeMemoriesOperation:
+ """Purges memories from an Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to purge memories from.
+ filter (str):
+ Optional. The standard list filter to determine which memories to purge.
+ filter_groups (list[MemoryConjunctionFilter]):
+ Optional. Metadata filters that will be applied to the memories'
+ `metadata` using OR logic. Filters are defined using disjunctive
+ normal form (OR of ANDs).
+ force (bool):
+ Optional. Whether to force the purge operation. If false, the
+ operation will be staged but not executed.
+ config (PurgeAgentEngineMemoriesConfig):
+ Optional. The configuration for the purge operation.
+
+ Returns:
+ AgentEnginePurgeMemoriesOperation:
+ The operation for purging the memories.
+ """
+ if config is None:
+ config = types.PurgeAgentEngineMemoriesConfig()
+ elif isinstance(config, dict):
+ config = types.PurgeAgentEngineMemoriesConfig.model_validate(config)
+ operation = await self._purge(
+ name=name,
+ filter=filter,
+ filter_groups=filter_groups,
+ force=force,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = await _agent_engines_utils._await_async_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to purge memories: {operation.error}")
+ return operation
+
+ async def ingest_events(
+ self,
+ *,
+ name: str,
+ scope: dict[str, str],
+ stream_id: str = "",
+ direct_contents_source: Optional[
+ types.IngestionDirectContentsSourceOrDict
+ ] = None,
+ generation_trigger_config: Optional[
+ types.MemoryGenerationTriggerConfigOrDict
+ ] = None,
+ config: Optional[types.IngestEventsConfigOrDict] = None,
+ ) -> types.MemoryBankIngestEventsOperation:
+ """Ingests events into an Agent Engine.
+
+ Example usage:
+ ```
+ await client.aio.agent_engines.memories.ingest_events(
+ name="projects/test-project/locations/us-central1/reasoningEngines/test-agent-engine",
+ scope={"user_id": "test-user-id"},
+ direct_contents_source={
+ "events": [
+ {
+ "content": {
+ "role": "user",
+ "parts": [
+ {"text": "I am a software engineer."}
+ ],
+ }
+ }
+ ]
+ },
+ generation_trigger_config={
+ "generation_rule": {
+ "idle_duration": "60s"
+ }
+ }
+ )
+ ```
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine to ingest events into.
+ scope (dict[str, str]):
+ Required. The scope of the events to ingest. For example,
+ {"user_id": "123"}.
+ stream_id (str):
+ Optional. The ID of the stream to ingest events into. If not
+ specified, the events will be ingested into the default stream.
+ direct_contents_source (IngestionDirectContentsSource):
+ The direct contents source, containing the events to ingest.
+ generation_trigger_config (MemoryGenerationTriggerConfig):
+ Optional. The configuration for the generation trigger config.
+ config (IngestEventsConfig):
+ Optional. The configuration for the ingest events operation.
+
+ Returns:
+ AgentEngineIngestEventsOperation:
+ The operation for ingesting the events.
+ """
+ if config is None:
+ config = types.IngestEventsConfig()
+ elif isinstance(config, dict):
+ config = types.IngestEventsConfig.model_validate(config)
+ operation = await self._ingest_events(
+ name=name,
+ scope=scope,
+ stream_id=stream_id,
+ generation_trigger_config=generation_trigger_config,
+ direct_contents_source=direct_contents_source,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = await _agent_engines_utils._await_async_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_memory_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to ingest events: {operation.error}")
+ return operation
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/memory_revisions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/memory_revisions.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1a1e307b143717f3152dd7bfa9b233f350777a3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/memory_revisions.py
@@ -0,0 +1,475 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import json
+import logging
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.memoryrevisions")
+
+logger.setLevel(logging.INFO)
+
+
+def _GetAgentEngineMemoryRevisionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ListAgentEngineMemoryRevisionsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListAgentEngineMemoryRevisionsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineMemoryRevisionsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class MemoryRevisions(_api_module.BaseModule):
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineMemoryRevisionConfigOrDict] = None,
+ ) -> types.MemoryRevision:
+ """
+ Gets an agent engine memory revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine memory revision to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}/revisions/{revision_id}`.
+ config (GetAgentEngineMemoryRevisionConfig):
+ Optional. Additional configurations for getting the Agent Engine memory revision.
+
+ Returns:
+ AgentEngineMemoryRevision: The requested Agent Engine memory revision.
+
+ """
+
+ parameter_model = types._GetAgentEngineMemoryRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineMemoryRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MemoryRevision._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
+ ) -> types.ListAgentEngineMemoryRevisionsResponse:
+ """
+ Lists Agent Engine memory revisions.
+
+ Args:
+ name (str): Required. The name of the Agent Engine memory to list revisions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}`.
+ config (ListAgentEngineMemoryRevisionsConfig):
+ Optional. Additional configurations for listing the Agent Engine memory revisions.
+
+ Returns:
+ ListAgentEngineMemoryRevisionsResponse: The requested Agent Engine memory revisions.
+
+ """
+
+ parameter_model = types._ListAgentEngineMemoryRevisionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineMemoryRevisionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/revisions".format_map(request_url_dict)
+ else:
+ path = "{name}/revisions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineMemoryRevisionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
+ ) -> Iterator[types.MemoryRevision]:
+ """Lists Agent Engine memory revisions.
+
+ Args:
+ name (str):
+ Required. The name of the Memory to list revisions for.
+ config (ListAgentEngineMemoryRevisionsConfigOrDict):
+ Optional. The configuration for the memories to list revisions.
+
+ Returns:
+ Iterable[MemoryRevision]: An iterable of memory revisions.
+ """
+
+ return Pager(
+ "memory_revisions",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+
+class AsyncMemoryRevisions(_api_module.BaseModule):
+
+ async def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineMemoryRevisionConfigOrDict] = None,
+ ) -> types.MemoryRevision:
+ """
+ Gets an agent engine memory revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine memory revision to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}/revisions/{revision_id}`.
+ config (GetAgentEngineMemoryRevisionConfig):
+ Optional. Additional configurations for getting the Agent Engine memory revision.
+
+ Returns:
+ AgentEngineMemoryRevision: The requested Agent Engine memory revision.
+
+ """
+
+ parameter_model = types._GetAgentEngineMemoryRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineMemoryRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.MemoryRevision._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
+ ) -> types.ListAgentEngineMemoryRevisionsResponse:
+ """
+ Lists Agent Engine memory revisions.
+
+ Args:
+ name (str): Required. The name of the Agent Engine memory to list revisions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}`.
+ config (ListAgentEngineMemoryRevisionsConfig):
+ Optional. Additional configurations for listing the Agent Engine memory revisions.
+
+ Returns:
+ ListAgentEngineMemoryRevisionsResponse: The requested Agent Engine memory revisions.
+
+ """
+
+ parameter_model = types._ListAgentEngineMemoryRevisionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineMemoryRevisionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/revisions".format_map(request_url_dict)
+ else:
+ path = "{name}/revisions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineMemoryRevisionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
+ ) -> AsyncPager[types.MemoryRevision]:
+ """Lists Agent Engine memory revisions.
+
+ Args:
+ name (str):
+ Required. The name of the Memory to list revisions for.
+ config (ListAgentEngineMemoryRevisionsConfigOrDict):
+ Optional. The configuration for the memories to list revisions.
+
+ Returns:
+ AsyncPager[MemoryRevision]: An async pager of memory revisions.
+ """
+
+ return AsyncPager(
+ "memory_revisions",
+ functools.partial(self._list, name=name),
+ await self._list(name=name, config=config),
+ config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/prompt_optimizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/prompt_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..3aab5f566626a165e34bfb270a9eb773d3ae892a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/prompt_optimizer.py
@@ -0,0 +1,995 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import json
+import logging
+import time
+from typing import Any, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai import types as genai_types
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+
+from . import _logging_utils
+from . import _prompt_optimizer_utils
+from . import prompts
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.promptoptimizer")
+
+
+def _CustomJobParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["custom_job"]) is not None:
+ setv(
+ parent_object,
+ ["customJob"],
+ _CustomJob_to_vertex(getv(from_object, ["custom_job"]), to_object),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CustomJob_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(parent_object, ["displayName"]) is not None:
+ setv(to_object, ["display_name"], getv(parent_object, ["displayName"]))
+
+ if getv(parent_object, ["jobSpec"]) is not None:
+ setv(to_object, ["job_spec"], getv(parent_object, ["jobSpec"]))
+
+ if getv(parent_object, ["encryptionSpec"]) is not None:
+ setv(to_object, ["encryption_spec"], getv(parent_object, ["encryptionSpec"]))
+
+ if getv(from_object, ["state"]) is not None:
+ setv(to_object, ["state"], getv(from_object, ["state"]))
+
+ if getv(parent_object, ["error"]) is not None:
+ setv(to_object, ["error"], getv(parent_object, ["error"]))
+
+ if getv(from_object, ["createTime"]) is not None:
+ setv(to_object, ["create_time"], getv(from_object, ["createTime"]))
+
+ if getv(from_object, ["endTime"]) is not None:
+ setv(to_object, ["end_time"], getv(from_object, ["endTime"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["satisfiesPzi"]) is not None:
+ setv(to_object, ["satisfies_pzi"], getv(from_object, ["satisfiesPzi"]))
+
+ if getv(from_object, ["satisfiesPzs"]) is not None:
+ setv(to_object, ["satisfies_pzs"], getv(from_object, ["satisfiesPzs"]))
+
+ if getv(from_object, ["startTime"]) is not None:
+ setv(to_object, ["start_time"], getv(from_object, ["startTime"]))
+
+ if getv(from_object, ["updateTime"]) is not None:
+ setv(to_object, ["update_time"], getv(from_object, ["updateTime"]))
+
+ if getv(from_object, ["webAccessUris"]) is not None:
+ setv(to_object, ["web_access_uris"], getv(from_object, ["webAccessUris"]))
+
+ return to_object
+
+
+def _CustomJob_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["job_spec"]) is not None:
+ setv(parent_object, ["jobSpec"], getv(from_object, ["job_spec"]))
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(parent_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["state"]) is not None:
+ setv(to_object, ["state"], getv(from_object, ["state"]))
+
+ if getv(from_object, ["error"]) is not None:
+ setv(parent_object, ["error"], getv(from_object, ["error"]))
+
+ if getv(from_object, ["create_time"]) is not None:
+ setv(to_object, ["createTime"], getv(from_object, ["create_time"]))
+
+ if getv(from_object, ["end_time"]) is not None:
+ setv(to_object, ["endTime"], getv(from_object, ["end_time"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["satisfies_pzi"]) is not None:
+ setv(to_object, ["satisfiesPzi"], getv(from_object, ["satisfies_pzi"]))
+
+ if getv(from_object, ["satisfies_pzs"]) is not None:
+ setv(to_object, ["satisfiesPzs"], getv(from_object, ["satisfies_pzs"]))
+
+ if getv(from_object, ["start_time"]) is not None:
+ setv(to_object, ["startTime"], getv(from_object, ["start_time"]))
+
+ if getv(from_object, ["update_time"]) is not None:
+ setv(to_object, ["updateTime"], getv(from_object, ["update_time"]))
+
+ if getv(from_object, ["web_access_uris"]) is not None:
+ setv(to_object, ["webAccessUris"], getv(from_object, ["web_access_uris"]))
+
+ return to_object
+
+
+def _GetCustomJobParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _OptimizeConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["optimization_target"]) is not None:
+ setv(
+ parent_object,
+ ["optimizationTarget"],
+ getv(from_object, ["optimization_target"]),
+ )
+
+ return to_object
+
+
+def _OptimizeRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["content"]) is not None:
+ setv(to_object, ["content"], getv(from_object, ["content"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _OptimizeConfig_to_vertex(getv(from_object, ["config"]), to_object),
+ )
+
+ return to_object
+
+
+class PromptOptimizer(_api_module.BaseModule):
+ """Prompt Optimizer"""
+
+ def _optimize_prompt(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponseEndpoint:
+ """
+ Optimize a single prompt.
+ """
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create_custom_job_resource(
+ self,
+ *,
+ custom_job: types.CustomJobOrDict,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.CustomJob:
+ """
+ Creates a custom job.
+ """
+
+ parameter_model = types._CustomJobParameters(
+ custom_job=custom_job,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs".format_map(request_url_dict)
+ else:
+ path = "customJobs"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_custom_job(
+ self, *, name: str, config: Optional[types.VertexBaseConfigOrDict] = None
+ ) -> types.CustomJob:
+ """
+ Gets a custom job.
+ """
+
+ parameter_model = types._GetCustomJobParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetCustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs/{name}".format_map(request_url_dict)
+ else:
+ path = "customJobs/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ """Prompt Optimizer PO-Data."""
+
+ def _wait_for_completion(self, job_name: str) -> types.CustomJob:
+
+ JOB_COMPLETE_STATES = [
+ genai_types.JobState.JOB_STATE_SUCCEEDED,
+ genai_types.JobState.JOB_STATE_FAILED,
+ genai_types.JobState.JOB_STATE_CANCELLED,
+ genai_types.JobState.JOB_STATE_PAUSED,
+ ]
+ JOB_ERROR_STATES = [
+ genai_types.JobState.JOB_STATE_FAILED,
+ genai_types.JobState.JOB_STATE_CANCELLED,
+ ]
+
+ log_wait = 5
+ wait_multiplier = 2
+ max_wait_time = 60
+ previous_time = time.time()
+
+ job = self._get_custom_job(name=job_name)
+
+ while job.state not in JOB_COMPLETE_STATES:
+ current_time = time.time()
+ if current_time - previous_time >= log_wait:
+ logger.info(f"Waiting for job to complete. Current state: {job.state}")
+ log_wait = min(log_wait * wait_multiplier, max_wait_time)
+ previous_time = current_time
+ time.sleep(log_wait)
+ job = self._get_custom_job(name=job_name)
+
+ logger.info(f"Job state: {job.state}")
+
+ if job.state in JOB_ERROR_STATES:
+ raise RuntimeError(f"Job failed with state: {job.state}")
+ else:
+ logger.info(f"Job completed with state: {job.state}")
+ return job
+
+ @_logging_utils.show_deprecation_warning_once(
+ "The prompt_optimizer.optimize method is deprecated. Please use"
+ " prompts.launch_optimization_job instead."
+ )
+ def optimize(
+ self,
+ method: types.PromptOptimizerMethod,
+ config: types.PromptOptimizerConfigOrDict,
+ ) -> types.CustomJob:
+ """Call PO-Data optimizer.
+
+ Args:
+ method: The method for optimizing multiple prompts. Supported methods:
+ VAPO, OPTIMIZATION_TARGET_GEMINI_NANO.
+ config: PromptOptimizerConfig instance containing the
+ configuration for prompt optimization.
+ Returns:
+ The custom job that was created.
+ """
+ prompts_module = prompts.Prompts(api_client_=self._api_client)
+
+ return prompts_module.launch_optimization_job( # type: ignore[no-any-return]
+ method=method, config=config
+ )
+
+ @_logging_utils.show_deprecation_warning_once(
+ "The prompt_optimizer.optimize_prompt method is deprecated. Please use"
+ " prompts.optimize instead."
+ )
+ def optimize_prompt(
+ self,
+ *,
+ prompt: str,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Makes an API request to _optimize_prompt and returns the parsed response.
+
+ Example usage:
+ client = agentplatform.Client(project=PROJECT_NAME, location='us-central1')
+ prompt = "Generate system instructions for analyzing medical articles"
+ response = client.prompt_optimizer.optimize_prompt(prompt=prompt)
+ print(response.suggested_prompt)
+
+ Args:
+ prompt: The prompt to optimize.
+ config: Optional.The configuration for prompt optimization. To optimize
+ prompts from Android API provide
+ types.OptimizeConfig(
+ optimization_target=types.OptimizeTarget.OPTIMIZATION_TARGET_GEMINI_NANO
+ )
+ For few-shot optimization, provide:
+
+ optim_target = types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS
+ or
+ optim_target = types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
+ types.OptimizeConfig(
+ optimization_target=optim_target,
+ examples_dataframe=dataframe
+ )
+ OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS indicates that the few-shot
+ examples include specific scoring rubrics and their corresponding
+ evaluations.
+ OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE indicates that the few-shot
+ examples include a ground-truth target response.
+ Returns:
+ The parsed response from the API request.
+ """
+ prompts_module = prompts.Prompts(api_client_=self._api_client)
+
+ return prompts_module.optimize( # type: ignore[no-any-return]
+ prompt=prompt, config=config
+ )
+
+ def _custom_optimize_prompt(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Optimize a single prompt.
+
+ Sends a request to the tuningJobs:optimizePrompt streaming endpoint.
+ Then gathers the response, concatenates into one string and returns
+ the parsed response.
+ """
+ if isinstance(config, dict):
+ config.pop("examples_dataframe", None)
+ elif config and hasattr(config, "examples_dataframe"):
+ del config.examples_dataframe
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError("This method is only supported in the Vertex AI client.")
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[genai_types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_list = "" if not response.body else json.loads(response.body)
+
+ return_value = []
+
+ for response_dict in response_list:
+ response_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict, kwargs=parameter_model.model_dump()
+ )
+ self._api_client._verify_response(response_value)
+ content = response_value.content
+ if content is not None:
+ parts = content.parts
+ if parts and parts[0].text is not None:
+ return_value.append(parts[0].text)
+
+ output = "".join(return_value)
+ final_response = types.OptimizeResponse(raw_text_response=output)
+ try:
+ final_response.parsed_response = _prompt_optimizer_utils._parse(output)
+ except Exception as e:
+ logger.warning(
+ f"Failed to parse response: {e}. Returning only raw_text_response."
+ )
+ return final_response
+
+
+class AsyncPromptOptimizer(_api_module.BaseModule):
+ """Prompt Optimizer"""
+
+ async def _optimize_prompt(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponseEndpoint:
+ """
+ Optimize a single prompt.
+ """
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create_custom_job_resource(
+ self,
+ *,
+ custom_job: types.CustomJobOrDict,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.CustomJob:
+ """
+ Creates a custom job.
+ """
+
+ parameter_model = types._CustomJobParameters(
+ custom_job=custom_job,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs".format_map(request_url_dict)
+ else:
+ path = "customJobs"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_custom_job(
+ self, *, name: str, config: Optional[types.VertexBaseConfigOrDict] = None
+ ) -> types.CustomJob:
+ """
+ Gets a custom job.
+ """
+
+ parameter_model = types._GetCustomJobParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetCustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs/{name}".format_map(request_url_dict)
+ else:
+ path = "customJobs/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ # Todo: b/428953357 - Add example in the README.
+ @_logging_utils.show_deprecation_warning_once(
+ "The prompt_optimizer.optimize method is deprecated. Please use"
+ " prompts.launch_optimization_job instead."
+ )
+ async def optimize(
+ self,
+ method: types.PromptOptimizerMethod,
+ config: types.PromptOptimizerConfigOrDict,
+ ) -> types.CustomJob:
+ """Call async Vertex AI Prompt Optimizer (VAPO).
+
+
+ Note: The `wait_for_completion` parameter in the config will be
+ ignored when using the AsyncClient, as it is not supported.
+
+ Example usage:
+ client = agentplatform.Client(project=PROJECT_NAME, location='us-central1')
+ vapo_config = agentplatform.types.PromptOptimizerConfig(
+ config_path='gs://you-bucket-name/your-config.json',
+ service_account=service_account,
+ )
+ job = await client.aio.prompt_optimizer.optimize(
+ method=types.PromptOptimizerMethod.VAPO, config=vapo_config)
+
+ Args:
+ method: The method for optimizing multiple prompts. Supported methods:
+ VAPO, OPTIMIZATION_TARGET_GEMINI_NANO.
+ config: PromptOptimizerConfig instance containing the
+ configuration for prompt optimization.
+ Returns:
+ The custom job that was created.
+ """
+ prompts_module = prompts.AsyncPrompts(api_client_=self._api_client)
+
+ return await prompts_module.launch_optimization_job( # type: ignore[no-any-return]
+ method=method, config=config
+ )
+
+ async def _custom_optimize_prompt(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Optimize a single prompt."""
+ if isinstance(config, dict):
+ config.pop("examples_dataframe", None)
+ elif config and hasattr(config, "examples_dataframe"):
+ del config.examples_dataframe
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError("This method is only supported in the Vertex AI client.")
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_list = "" if not response.body else json.loads(response.body)
+
+ return_value = []
+
+ for response_dict in response_list:
+ response_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict, kwargs=parameter_model.model_dump()
+ )
+ self._api_client._verify_response(response_value)
+ content = response_value.content
+ if content is not None:
+ parts = content.parts
+ if parts and parts[0].text is not None:
+ return_value.append(parts[0].text)
+
+ output = "".join(return_value)
+ final_response = types.OptimizeResponse(raw_text_response=output)
+ try:
+ final_response.parsed_response = _prompt_optimizer_utils._parse(output)
+ except Exception as e:
+ logger.warning(
+ f"Failed to parse response: {e}. Returning only raw_text_response."
+ )
+ return final_response
+
+ @_logging_utils.show_deprecation_warning_once(
+ "The prompt_optimizer.optimize_prompt method is deprecated. Please use"
+ " prompts.optimize instead."
+ )
+ async def optimize_prompt(
+ self,
+ *,
+ prompt: str,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Makes an async request to _optimize_prompt and returns an optimized prompt.
+
+ Example usage:
+ client = agentplatform.Client(project=PROJECT_NAME, location='us-central1')
+ prompt = "Generate system instructions for analyzing medical articles"
+ response = await client.aio.prompt_optimizer.optimize_prompt(prompt=prompt)
+
+ Args:
+ prompt: The prompt to optimize.
+ config: Optional.The configuration for prompt optimization. To optimize
+ prompts from Android API provide
+ types.OptimizeConfig(
+ optimization_target=types.OptimizeTarget.OPTIMIZATION_TARGET_GEMINI_NANO
+ )
+ For few-shot optimization, provide:
+ optim_target = types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS # or types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
+ types.OptimizeConfig(
+ optimization_target=optim_target,
+ examples_dataframe=dataframe
+ )
+ OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS indicates that the few-shot
+ examples include specific scoring rubrics and their corresponding
+ evaluations.
+ OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE indicates that the few-shot
+ examples include a ground-truth target response.
+ Returns:
+ The parsed response from the API request.
+ """
+ prompts_module = prompts.AsyncPrompts(api_client_=self._api_client)
+
+ return await prompts_module.optimize( # type: ignore[no-any-return]
+ prompt=prompt, config=config
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/prompts.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/prompts.py
new file mode 100644
index 0000000000000000000000000000000000000000..4405cf34da7277b6e08d4ea496e8930fcd52e19b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/prompts.py
@@ -0,0 +1,4373 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import asyncio
+import datetime
+import json
+import logging
+import time
+from typing import Any, AsyncIterator, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai import operations
+from google.genai import types as genai_types
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+from pydantic import ValidationError
+
+from . import _prompt_management_utils
+from . import _prompt_optimizer_utils
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.prompts")
+
+
+def _CreateDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["metadata_schema_uri"]) is not None:
+ setv(
+ to_object, ["metadataSchemaUri"], getv(from_object, ["metadata_schema_uri"])
+ )
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(to_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["model_reference"]) is not None:
+ setv(to_object, ["modelReference"], getv(from_object, ["model_reference"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CreateDatasetVersionParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["dataset_name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["dataset_name"]))
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["model_reference"]) is not None:
+ setv(to_object, ["modelReference"], getv(from_object, ["model_reference"]))
+
+ if getv(from_object, ["parent"]) is not None:
+ setv(to_object, ["parent"], getv(from_object, ["parent"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CustomJobParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["custom_job"]) is not None:
+ setv(
+ parent_object,
+ ["customJob"],
+ _CustomJob_to_vertex(getv(from_object, ["custom_job"]), to_object),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _CustomJob_from_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(parent_object, ["displayName"]) is not None:
+ setv(to_object, ["display_name"], getv(parent_object, ["displayName"]))
+
+ if getv(parent_object, ["jobSpec"]) is not None:
+ setv(to_object, ["job_spec"], getv(parent_object, ["jobSpec"]))
+
+ if getv(parent_object, ["encryptionSpec"]) is not None:
+ setv(to_object, ["encryption_spec"], getv(parent_object, ["encryptionSpec"]))
+
+ if getv(from_object, ["state"]) is not None:
+ setv(to_object, ["state"], getv(from_object, ["state"]))
+
+ if getv(parent_object, ["error"]) is not None:
+ setv(to_object, ["error"], getv(parent_object, ["error"]))
+
+ if getv(from_object, ["createTime"]) is not None:
+ setv(to_object, ["create_time"], getv(from_object, ["createTime"]))
+
+ if getv(from_object, ["endTime"]) is not None:
+ setv(to_object, ["end_time"], getv(from_object, ["endTime"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["satisfiesPzi"]) is not None:
+ setv(to_object, ["satisfies_pzi"], getv(from_object, ["satisfiesPzi"]))
+
+ if getv(from_object, ["satisfiesPzs"]) is not None:
+ setv(to_object, ["satisfies_pzs"], getv(from_object, ["satisfiesPzs"]))
+
+ if getv(from_object, ["startTime"]) is not None:
+ setv(to_object, ["start_time"], getv(from_object, ["startTime"]))
+
+ if getv(from_object, ["updateTime"]) is not None:
+ setv(to_object, ["update_time"], getv(from_object, ["updateTime"]))
+
+ if getv(from_object, ["webAccessUris"]) is not None:
+ setv(to_object, ["web_access_uris"], getv(from_object, ["webAccessUris"]))
+
+ return to_object
+
+
+def _CustomJob_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["job_spec"]) is not None:
+ setv(parent_object, ["jobSpec"], getv(from_object, ["job_spec"]))
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(parent_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["state"]) is not None:
+ setv(to_object, ["state"], getv(from_object, ["state"]))
+
+ if getv(from_object, ["error"]) is not None:
+ setv(parent_object, ["error"], getv(from_object, ["error"]))
+
+ if getv(from_object, ["create_time"]) is not None:
+ setv(to_object, ["createTime"], getv(from_object, ["create_time"]))
+
+ if getv(from_object, ["end_time"]) is not None:
+ setv(to_object, ["endTime"], getv(from_object, ["end_time"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["satisfies_pzi"]) is not None:
+ setv(to_object, ["satisfiesPzi"], getv(from_object, ["satisfies_pzi"]))
+
+ if getv(from_object, ["satisfies_pzs"]) is not None:
+ setv(to_object, ["satisfiesPzs"], getv(from_object, ["satisfies_pzs"]))
+
+ if getv(from_object, ["start_time"]) is not None:
+ setv(to_object, ["startTime"], getv(from_object, ["start_time"]))
+
+ if getv(from_object, ["update_time"]) is not None:
+ setv(to_object, ["updateTime"], getv(from_object, ["update_time"]))
+
+ if getv(from_object, ["web_access_uris"]) is not None:
+ setv(to_object, ["webAccessUris"], getv(from_object, ["web_access_uris"]))
+
+ return to_object
+
+
+def _DeleteDatasetRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["prompt_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["prompt_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _DeletePromptVersionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["prompt_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["prompt_id"]))
+
+ if getv(from_object, ["version_id"]) is not None:
+ setv(to_object, ["_url", "version_id"], getv(from_object, ["version_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetCustomJobParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetDatasetOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["dataset_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["dataset_id"]))
+
+ if getv(from_object, ["operation_id"]) is not None:
+ setv(to_object, ["_url", "operation_id"], getv(from_object, ["operation_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _GetDatasetVersionParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["dataset_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["dataset_id"]))
+
+ if getv(from_object, ["dataset_version_id"]) is not None:
+ setv(
+ to_object,
+ ["_url", "dataset_version_id"],
+ getv(from_object, ["dataset_version_id"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _ListDatasetVersionsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["read_mask"]) is not None:
+ setv(to_object, ["_url", "read_mask"], getv(from_object, ["read_mask"]))
+
+ if getv(from_object, ["dataset_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["dataset_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _ListPromptsConfig_to_vertex(getv(from_object, ["config"]), to_object),
+ )
+
+ return to_object
+
+
+def _ListDatasetsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _ListPromptsConfig_to_vertex(getv(from_object, ["config"]), to_object),
+ )
+
+ return to_object
+
+
+def _ListPromptsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _OptimizeConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["optimization_target"]) is not None:
+ setv(
+ parent_object,
+ ["optimizationTarget"],
+ getv(from_object, ["optimization_target"]),
+ )
+
+ return to_object
+
+
+def _OptimizeRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["content"]) is not None:
+ setv(to_object, ["content"], getv(from_object, ["content"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _OptimizeConfig_to_vertex(getv(from_object, ["config"]), to_object),
+ )
+
+ return to_object
+
+
+def _RestoreVersionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["dataset_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["dataset_id"]))
+
+ if getv(from_object, ["version_id"]) is not None:
+ setv(to_object, ["_url", "version_id"], getv(from_object, ["version_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _UpdateDatasetParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["dataset_id"]) is not None:
+ setv(to_object, ["_url", "dataset_id"], getv(from_object, ["dataset_id"]))
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["metadata"]) is not None:
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["encryption_spec"]) is not None:
+ setv(to_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
+
+ if getv(from_object, ["model_reference"]) is not None:
+ setv(to_object, ["modelReference"], getv(from_object, ["model_reference"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+class Prompts(_api_module.BaseModule):
+
+ def _create_dataset_resource(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata_schema_uri: Optional[str] = None,
+ metadata: Optional[types.SchemaTextPromptDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ model_reference: Optional[str] = None,
+ config: Optional[types.CreateDatasetConfigOrDict] = None,
+ ) -> types.DatasetOperation:
+ """
+ Creates a dataset resource to store prompts.
+ """
+
+ parameter_model = types._CreateDatasetParameters(
+ name=name,
+ display_name=display_name,
+ metadata_schema_uri=metadata_schema_uri,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ model_reference=model_reference,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create_dataset_version_resource(
+ self,
+ *,
+ dataset_name: Optional[str] = None,
+ metadata: Optional[types.SchemaTextPromptDatasetMetadataOrDict] = None,
+ model_reference: Optional[str] = None,
+ parent: Optional[str] = None,
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateDatasetVersionConfigOrDict] = None,
+ ) -> types.DatasetOperation:
+ """
+ Creates a dataset version resource to store prompts.
+ """
+
+ parameter_model = types._CreateDatasetVersionParameters(
+ dataset_name=dataset_name,
+ metadata=metadata,
+ model_reference=model_reference,
+ parent=parent,
+ display_name=display_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateDatasetVersionParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{name}/datasetVersions".format_map(request_url_dict)
+ else:
+ path = "datasets/{name}/datasetVersions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_dataset_resource(
+ self,
+ *,
+ name: Optional[str] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.Dataset:
+ """
+ Gets a dataset resource to store prompts.
+ """
+
+ parameter_model = types._GetDatasetParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{name}".format_map(request_url_dict)
+ else:
+ path = "datasets/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Dataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_dataset_version_resource(
+ self,
+ *,
+ dataset_id: Optional[str] = None,
+ dataset_version_id: Optional[str] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.DatasetVersion:
+ """
+ Gets a dataset version resource to store prompts.
+ """
+
+ parameter_model = types._GetDatasetVersionParameters(
+ dataset_id=dataset_id,
+ dataset_version_id=dataset_version_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetDatasetVersionParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions/{dataset_version_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions/{dataset_version_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetVersion._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_dataset_operation(
+ self,
+ *,
+ dataset_id: Optional[str] = None,
+ operation_id: Optional[str] = None,
+ config: Optional[types.GetDatasetOperationConfigOrDict] = None,
+ ) -> types.DatasetOperation:
+ """
+ Gets the operation from creating a dataset.
+ """
+
+ parameter_model = types._GetDatasetOperationParameters(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetDatasetOperationParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/operations/{operation_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/operations/{operation_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list_prompts(
+ self, *, config: Optional[types.ListPromptsConfigOrDict] = None
+ ) -> types.ListDatasetsResponse:
+ """
+ Lists Agent Engines.
+ """
+
+ parameter_model = types._ListDatasetsRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListDatasetsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListDatasetsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list_versions(
+ self,
+ *,
+ read_mask: Optional[str] = None,
+ dataset_id: Optional[str] = None,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> types.ListDatasetVersionsResponse:
+ """
+ Lists Agent Engines.
+ """
+
+ parameter_model = types._ListDatasetVersionsRequestParameters(
+ read_mask=read_mask,
+ dataset_id=dataset_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListDatasetVersionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListDatasetVersionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete_dataset(
+ self, *, prompt_id: str, config: Optional[types.DeletePromptConfigOrDict] = None
+ ) -> types.DeletePromptOperation:
+ parameter_model = types._DeleteDatasetRequestParameters(
+ prompt_id=prompt_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteDatasetRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}".format_map(request_url_dict)
+ else:
+ path = "datasets/{dataset_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeletePromptOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete_dataset_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.DeletePromptConfigOrDict] = None,
+ ) -> types.DeletePromptVersionOperation:
+ parameter_model = types._DeletePromptVersionRequestParameters(
+ prompt_id=prompt_id,
+ version_id=version_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeletePromptVersionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeletePromptVersionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _restore_version(
+ self,
+ *,
+ dataset_id: str,
+ version_id: str,
+ config: Optional[types.RestoreVersionConfigOrDict] = None,
+ ) -> types.RestoreVersionOperation:
+ """
+ Restores the provided prompt version to the latest version.
+ """
+
+ parameter_model = types._RestoreVersionRequestParameters(
+ dataset_id=dataset_id,
+ version_id=version_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RestoreVersionRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}:restore".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}:restore"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RestoreVersionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _update_dataset_resource(
+ self,
+ *,
+ name: Optional[str] = None,
+ dataset_id: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata: Optional[types.SchemaTextPromptDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ model_reference: Optional[str] = None,
+ config: Optional[types.UpdatePromptConfigOrDict] = None,
+ ) -> types.Dataset:
+ """
+ Creates a dataset resource to store prompts.
+ """
+
+ parameter_model = types._UpdateDatasetParameters(
+ name=name,
+ dataset_id=dataset_id,
+ display_name=display_name,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ model_reference=model_reference,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}".format_map(request_url_dict)
+ else:
+ path = "datasets/{dataset_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("patch", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Dataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create_custom_job_resource(
+ self,
+ *,
+ custom_job: types.CustomJobOrDict,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.CustomJob:
+ """
+ Creates a custom job.
+ """
+
+ parameter_model = types._CustomJobParameters(
+ custom_job=custom_job,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs".format_map(request_url_dict)
+ else:
+ path = "customJobs"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_custom_job(
+ self, *, name: str, config: Optional[types.VertexBaseConfigOrDict] = None
+ ) -> types.CustomJob:
+ """
+ Gets a custom job.
+ """
+
+ parameter_model = types._GetCustomJobParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetCustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs/{name}".format_map(request_url_dict)
+ else:
+ path = "customJobs/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _optimize(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponseEndpoint:
+ """
+ Optimize a single prompt.
+ """
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def create(
+ self,
+ *,
+ prompt: types.PromptOrDict,
+ config: Optional[types.CreatePromptConfigOrDict] = None,
+ ) -> types.Prompt:
+ """Creates a new prompt in a Vertex Dataset resource.
+
+ This method waits for prompt creation to be complete before returning.
+
+ Note: This method does not create a versioned resource for your prompt.
+ Call create_version() to create a new prompt resource with a version.
+
+ Args:
+ prompt: The prompt to create.
+ config: Optional configuration for creating the prompt.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated
+ Dataset resources.
+ """
+ if isinstance(prompt, dict):
+ prompt = types.Prompt(**prompt)
+ if isinstance(config, dict):
+ config = types.CreatePromptConfig(**config)
+ elif not config:
+ config = types.CreatePromptConfig()
+
+ _prompt_management_utils._raise_for_invalid_prompt(prompt)
+
+ if prompt.prompt_data is None:
+ raise ValueError("Prompt data is required to create a prompt.")
+
+ prompt_metadata = _prompt_management_utils._create_dataset_metadata_from_prompt(
+ prompt,
+ variables=(
+ prompt.prompt_data.variables
+ if prompt.prompt_data and prompt.prompt_data.variables
+ else None
+ ),
+ )
+
+ # Step 1: Create the dataset resource for the prompt and wait for the operation to complete.
+ create_prompt_dataset_operation = self._create_dataset_resource(
+ display_name=(
+ config.prompt_display_name
+ if config and config.prompt_display_name
+ else f"prompt_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ name=f"projects/{self._api_client.project}/locations/{self._api_client.location}",
+ metadata_schema_uri=_prompt_management_utils.PROMPT_SCHEMA_URI,
+ metadata=prompt_metadata,
+ model_reference=prompt.prompt_data.model,
+ encryption_spec=(
+ config.encryption_spec if config and config.encryption_spec else None
+ ),
+ )
+ dataset_resource_name = self._wait_for_operation(
+ operation=create_prompt_dataset_operation,
+ timeout=config.timeout if config else 90,
+ )
+ dataset_id = dataset_resource_name.split("/")[-1]
+
+ # Step 2: Get the dataset resource
+ dataset_resource = self._get_dataset_resource(
+ name=dataset_id,
+ )
+ prompt._dataset = dataset_resource
+ return prompt
+
+ def create_version(
+ self,
+ *,
+ prompt: types.PromptOrDict,
+ config: Optional[types.CreatePromptVersionConfigOrDict] = None,
+ ) -> types.Prompt:
+ """Creates a prompt resource and an initial prompt version.
+
+ When creating new prompt and prompt version resources, this waits for
+ the create operation to complete before returning.
+
+ Note: This method is recommended instead of create() since it creates a
+ versioned resource for your prompt.
+
+ Args:
+ prompt: The prompt to create.
+ config: Optional configuration for creating the prompt and prompt version.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated
+ Dataset and Dataset Version resources.
+ """
+
+ if isinstance(prompt, dict):
+ prompt = types.Prompt(**prompt)
+ if isinstance(config, dict):
+ config = types.CreatePromptVersionConfig(**config)
+ elif not config:
+ config = types.CreatePromptVersionConfig()
+
+ _prompt_management_utils._raise_for_invalid_prompt(prompt)
+
+ if prompt.prompt_data is None:
+ raise ValueError("Prompt data is required to create a prompt.")
+
+ prompt_metadata = _prompt_management_utils._create_dataset_metadata_from_prompt(
+ prompt,
+ variables=(
+ prompt.prompt_data.variables
+ if prompt.prompt_data and prompt.prompt_data.variables
+ else None
+ ),
+ )
+
+ # Step 1: Create the dataset resource for the prompt and wait for the operation to complete.
+ create_prompt_dataset_operation = self._create_dataset_resource(
+ display_name=(
+ config.prompt_display_name
+ if config and config.prompt_display_name
+ else f"prompt_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ name=f"projects/{self._api_client.project}/locations/{self._api_client.location}",
+ metadata_schema_uri=_prompt_management_utils.PROMPT_SCHEMA_URI,
+ metadata=prompt_metadata,
+ model_reference=prompt.prompt_data.model,
+ encryption_spec=(
+ config.encryption_spec if config and config.encryption_spec else None
+ ),
+ )
+ dataset_resource_name = self._wait_for_operation(
+ operation=create_prompt_dataset_operation,
+ timeout=config.timeout if config else 90,
+ )
+ dataset_id = dataset_resource_name.split("/")[-1]
+
+ # Step 2: Get the dataset resource
+ dataset_resource = self._get_dataset_resource(
+ name=dataset_id,
+ )
+ prompt._dataset = dataset_resource
+
+ if prompt._dataset.name is None:
+ raise ValueError("Invalid dataset resource.")
+
+ # Step 3: Create the dataset version
+ create_dataset_version_operation = self._create_dataset_version_resource(
+ dataset_name=prompt._dataset.name.split("/")[-1],
+ display_name=(
+ config.version_display_name
+ if config and config.version_display_name is not None
+ else f"prompt_version_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ )
+ dataset_version_resource_name = self._wait_for_operation(
+ operation=create_dataset_version_operation,
+ timeout=config.timeout if config else 90,
+ )
+
+ # Step 4: Get the dataset version resource and return it with the prompt
+ dataset_version_resource = self._get_dataset_version_resource(
+ dataset_id=dataset_id,
+ dataset_version_id=dataset_version_resource_name.split("/")[-1],
+ )
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ dataset_version_resource
+ )
+ prompt._dataset = dataset_resource
+ prompt._dataset_version = dataset_version_resource
+ return prompt
+
+ def _wait_for_operation(
+ self,
+ operation: types.DatasetOperation,
+ timeout: int,
+ ) -> str:
+ """Waits for a dataset operation to complete.
+
+ Args:
+ operation: The dataset operation to wait for.
+ timeout: The maximum time to wait for the operation to complete.
+
+ Returns:
+ The name of the Dataset resource from the operation result.
+
+ Raises:
+ TimeoutError: If the operation does not complete within the timeout.
+ ValueError: If the operation fails.
+ """
+ done = False
+ prompt_dataset_operation: Optional[types.DatasetOperation] = None
+
+ response_operation_name = operation.name
+ if response_operation_name is None:
+ raise ValueError("Invalid operation name.")
+
+ dataset_id = response_operation_name.split("/datasets/")[1].split("/")[0]
+ operation_id = response_operation_name.split("/")[-1]
+
+ start_time = time.time()
+ sleep_duration = 5
+ wait_multiplier = 2
+ max_wait_time = 60
+ previous_time = time.time()
+
+ while not done:
+ if (time.time() - start_time) > timeout:
+ raise TimeoutError(
+ "Create prompt operation did not complete within the"
+ f" specified timeout of {timeout} seconds."
+ )
+ current_time = time.time()
+ if current_time - previous_time >= sleep_duration:
+ sleep_duration = min(sleep_duration * wait_multiplier, max_wait_time)
+ previous_time = current_time
+ time.sleep(sleep_duration)
+ prompt_dataset_operation = self._get_dataset_operation(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ )
+ done = (
+ (prompt_dataset_operation.done or False)
+ if hasattr(prompt_dataset_operation, "done")
+ else False
+ )
+ if (
+ not prompt_dataset_operation
+ or prompt_dataset_operation.response is None
+ or prompt_dataset_operation.response.get("name") is None
+ ):
+ raise ValueError("Error creating prompt version resource.")
+ if (
+ hasattr(prompt_dataset_operation, "error")
+ and prompt_dataset_operation.error is not None
+ ):
+ raise ValueError(
+ f"Error creating prompt version resource: {prompt_dataset_operation.error}"
+ )
+ return prompt_dataset_operation.response.get("name") # type: ignore[return-value]
+
+ def get(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.GetPromptConfig] = None,
+ ) -> types.Prompt:
+ """Gets a prompt resource from a Vertex Dataset.
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ config: Optional configuration for getting the prompt.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated Dataset resources.
+ """
+
+ prompt_dataset_resource = self._get_dataset_resource(name=prompt_id)
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ prompt_dataset_resource,
+ )
+ prompt._dataset = prompt_dataset_resource
+
+ return prompt
+
+ def get_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.GetPromptConfig] = None,
+ ) -> types.Prompt:
+ """Gets a prompt resource from a Vertex Dataset.
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ version_id: The id of the Vertex Dataset Version resource containing the prompt version. For example, if the prompt version resource name is "projects/123/locations/us-central1/datasets/456/datasetVersions/1", then the version_id is "1".
+ config: Optional configuration for getting the prompt.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated Dataset and Dataset Version resources.
+ """
+
+ prompt_dataset_resource = self._get_dataset_resource(name=prompt_id)
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ prompt_dataset_resource,
+ )
+ prompt._dataset = prompt_dataset_resource
+
+ prompt_version_resource = self._get_dataset_version_resource(
+ dataset_id=prompt_id,
+ dataset_version_id=version_id,
+ )
+ prompt._dataset_version = prompt_version_resource
+
+ return prompt
+
+ def _list_prompts_pager(
+ self,
+ *,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> Pager[types.Dataset]:
+ return Pager(
+ "datasets",
+ self._list_prompts,
+ self._list_prompts(config=config),
+ config,
+ )
+
+ def _list_versions_pager(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> Pager[types.DatasetVersion]:
+ return Pager(
+ "dataset_versions",
+ self._list_versions,
+ self._list_versions(config=config, dataset_id=prompt_id),
+ config,
+ )
+
+ def list(
+ self,
+ *,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> Iterator[types.PromptRef]:
+ """Lists prompt resources in a project.
+
+ This method retrieves all the prompts from the project provided in the
+ agentplatform.Client constructor and returns a list of prompt references containing the prompt_id and model for the prompt.
+
+ To get the full types.Prompt resource for a PromptRef after calling this method, use the get() method with the prompt_id as the prompt_id argument.
+ Example usage:
+
+ ```
+ # Using an iterator
+ prompt_refs = client.prompt_management.list_prompts()
+ for prompt_ref in prompt_refs:
+ client.prompt_management.get(prompt_id=prompt_ref.prompt_id)
+
+ # Using a list
+ prompts_list = list(client.prompt_management.list_prompts())
+ client.prompt_management.get(prompt_id=prompts_list[0].prompt_id)
+ ```
+
+ Args:
+ config: Optional configuration for listing prompts.
+
+ Returns:
+ An iterable of types.PromptRef objects.
+ """
+ if isinstance(config, dict):
+ config = types.ListPromptsConfig(**config)
+ elif not config:
+ config = types.ListPromptsConfig()
+ for dataset in self._list_prompts_pager(config=config):
+ if not dataset.name:
+ continue
+ prompt_ref = types.PromptRef(
+ model=dataset.model_reference, prompt_id=dataset.name.split("/")[-1]
+ )
+ yield prompt_ref
+
+ def list_versions(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> Iterator[types.PromptVersionRef]:
+ """Lists prompt version resources for a provided prompt_id.
+
+ This method retrieves all the prompt versions for a provided prompt_id.
+
+ To get the full types.Prompt resource for a PromptVersionRef after calling this method, use the get() method with the returned prompt_id and version_id.
+ Example usage:
+
+ ```
+ # Using an iterator
+ prompt_version_refs = client.prompt_management.list_versions(prompt_id="123")
+ for version_ref in prompt_version_refs:
+ client.prompt_management.get(prompt_id=version_ref.prompt_id, version_id=version_ref.version_id)
+
+ # Using a list
+ prompt_versions_list = list(client.prompt_management.list_versions(prompt_id="123"))
+ client.prompt_management.get(prompt_id=prompt_versions_list[0].prompt_id, version_id=prompt_versions_list[0].version_id)
+ ```
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ config: Optional configuration for listing prompts.
+
+ Returns:
+ An iterable of types.PromptVersionRef objects representing the prompt version resources for the provided prompt_id.
+
+ """
+ if isinstance(config, dict):
+ config = types.ListPromptsConfig(**config)
+ elif not config:
+ config = types.ListPromptsConfig()
+ for dataset_version in self._list_versions_pager(
+ config=config, prompt_id=prompt_id
+ ):
+ if (
+ not dataset_version
+ or not dataset_version.model_reference
+ or not dataset_version.name
+ ):
+ continue
+ prompt_version_ref = types.PromptVersionRef(
+ model=dataset_version.model_reference,
+ version_id=dataset_version.name.split("/")[-1],
+ prompt_id=prompt_id,
+ )
+ yield prompt_version_ref
+
+ def _wait_for_project_operation(
+ self,
+ operation: genai_types.ProjectOperation,
+ timeout: int,
+ ) -> None:
+ """Waits for a dataset deletion operation to complete.
+
+ Delete operations are project level operations and are separate from dataset resource operations, for example: projects/123/locations/us-central1/operations/789.
+
+ Args:
+ operation: The project operation to wait for.
+ timeout: The maximum time to wait for the operation to complete.
+ Raises:
+ TimeoutError: If the operation does not complete within the timeout.
+ ValueError: If the operation fails.
+ """
+ done = False
+
+ start_time = time.time()
+ sleep_duration = 5
+ wait_multiplier = 2
+ max_wait_time = 60
+ previous_time = time.time()
+ while not done:
+ if (time.time() - start_time) > timeout:
+ raise TimeoutError(
+ f"Delete operation did not complete within the"
+ f" specified timeout of {timeout} seconds."
+ )
+ current_time = time.time()
+ if current_time - previous_time >= sleep_duration:
+ sleep_duration = min(sleep_duration * wait_multiplier, max_wait_time)
+ previous_time = current_time
+ time.sleep(sleep_duration)
+ operations_module = operations.Operations(api_client_=self._api_client)
+
+ if operation.name is None:
+ raise ValueError("Invalid operation name.")
+ operation = operations_module._get(
+ operation_id=operation.name.split("/")[-1],
+ )
+ done = (operation.done or False) if hasattr(operation, "done") else False
+ if hasattr(operation, "error") and operation.error is not None:
+ raise ValueError(f"Error in delete operation: {operation.error}")
+
+ def delete(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.DeletePromptConfig] = None,
+ ) -> None:
+ """Deletes a prompt resource.
+
+ Args:
+ prompt_id: The id of the prompt resource to delete.
+
+ Raises:
+ TimeoutError: If the delete operation does not complete within the timeout.
+ ValueError: If the delete operation fails.
+ """
+
+ delete_prompt_operation = self._delete_dataset(
+ prompt_id=prompt_id,
+ config=config,
+ )
+ self._wait_for_project_operation(
+ operation=delete_prompt_operation, timeout=config.timeout if config else 90
+ )
+ logger.info(f"Deleted prompt with id: {prompt_id}")
+
+ def delete_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.DeletePromptConfig] = None,
+ ) -> None:
+ """Deletes a prompt version resource.
+
+ Args:
+ prompt_id: The id of the prompt resource to delete.
+ version_id: The id of the prompt version resource to delete.
+
+ Raises:
+ TimeoutError: If the delete operation does not complete within the timeout.
+ ValueError: If the delete operation fails.
+ """
+ delete_version_operation = self._delete_dataset_version(
+ prompt_id=prompt_id,
+ version_id=version_id,
+ config=config,
+ )
+
+ self._wait_for_project_operation(
+ operation=delete_version_operation, timeout=config.timeout if config else 90
+ )
+ logger.info(
+ f"Deleted prompt version {version_id} from prompt with id: {prompt_id}"
+ )
+
+ def restore_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.RestoreVersionConfig] = None,
+ ) -> types.Prompt:
+ """Restores the provided prompt version to the latest version.
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ version_id: The id of the Vertex Dataset Version resource to restore. For example, if the version resource name is "projects/123/locations/us-central1/datasets/456/datasetVersions/789", then the version_id is "789".
+ config: Optional configuration for restoring the prompt version.
+
+ Returns:
+ A types.Prompt object representing the prompt with the updated Dataset Version resource.
+ """
+
+ restore_prompt_operation = self._restore_version(
+ dataset_id=prompt_id,
+ version_id=version_id,
+ )
+ self._wait_for_project_operation(
+ operation=restore_prompt_operation,
+ timeout=90,
+ )
+ dataset_version_resource = self._get_dataset_version_resource(
+ dataset_id=prompt_id,
+ dataset_version_id=version_id,
+ )
+ updated_prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ dataset_version_resource,
+ )
+ updated_prompt._dataset_version = dataset_version_resource
+ return updated_prompt
+
+ def _wait_for_completion(self, job_name: str) -> types.CustomJob:
+
+ JOB_COMPLETE_STATES = [
+ genai_types.JobState.JOB_STATE_SUCCEEDED,
+ genai_types.JobState.JOB_STATE_FAILED,
+ genai_types.JobState.JOB_STATE_CANCELLED,
+ genai_types.JobState.JOB_STATE_PAUSED,
+ ]
+ JOB_ERROR_STATES = [
+ genai_types.JobState.JOB_STATE_FAILED,
+ genai_types.JobState.JOB_STATE_CANCELLED,
+ ]
+
+ log_wait = 5
+ wait_multiplier = 2
+ max_wait_time = 60
+ previous_time = time.time()
+
+ job = self._get_custom_job(name=job_name)
+
+ while job.state not in JOB_COMPLETE_STATES:
+ current_time = time.time()
+ if current_time - previous_time >= log_wait:
+ logger.info(f"Waiting for job to complete. Current state: {job.state}")
+ log_wait = min(log_wait * wait_multiplier, max_wait_time)
+ previous_time = current_time
+ time.sleep(log_wait)
+ job = self._get_custom_job(name=job_name)
+
+ logger.info(f"Job state: {job.state}")
+
+ if job.state in JOB_ERROR_STATES:
+ raise RuntimeError(f"Job failed with state: {job.state}")
+ else:
+ logger.info(f"Job completed with state: {job.state}")
+ return job
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI prompts.launch_optimization_job method is "
+ "experimental, and may change in future versions."
+ )
+ def launch_optimization_job(
+ self,
+ method: types.PromptOptimizerMethod,
+ config: types.PromptOptimizerConfigOrDict,
+ ) -> types.CustomJob:
+ """Call PO-Data optimizer.
+
+ Args:
+ method: The method for optimizing multiple prompts. Supported methods:
+ VAPO, OPTIMIZATION_TARGET_GEMINI_NANO.
+ config: PromptOptimizerConfig instance containing the
+ configuration for prompt optimization.
+ Returns:
+ The custom job that was created.
+ """
+
+ if isinstance(config, dict):
+ config = types.PromptOptimizerConfig(**config)
+
+ if not config.config_path:
+ raise ValueError("Config path is required.")
+
+ _OPTIMIZER_METHOD_TO_CONTAINER_URI = {
+ types.PromptOptimizerMethod.VAPO: "us-docker.pkg.dev/vertex-ai/cair/vaipo:preview_v1_0",
+ types.PromptOptimizerMethod.OPTIMIZATION_TARGET_GEMINI_NANO: "us-docker.pkg.dev/vertex-ai/cair/vaipo:preview_android_v1_0",
+ }
+ container_uri = _OPTIMIZER_METHOD_TO_CONTAINER_URI.get(method)
+ if not container_uri:
+ raise ValueError(
+ 'Only "VAPO" and "OPTIMIZATION_TARGET_GEMINI_NANO" '
+ "methods are currently supported."
+ )
+
+ if config.optimizer_job_display_name:
+ display_name = config.optimizer_job_display_name
+ else:
+ timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
+ display_name = f"{method.value.lower()}-optimizer-{timestamp}"
+
+ wait_for_completion = config.wait_for_completion
+ bucket = "/".join(config.config_path.split("/")[:-1])
+
+ region = self._api_client.location
+ project = self._api_client.project
+ container_args = {
+ "config": config.config_path,
+ }
+ args = ["--%s=%s" % (k, v) for k, v in container_args.items()]
+ worker_pool_specs = [
+ types.WorkerPoolSpec(
+ replica_count=1,
+ machine_spec=types.MachineSpec(machine_type="n1-standard-4"),
+ container_spec=types.ContainerSpec(
+ image_uri=container_uri,
+ args=args,
+ ),
+ )
+ ]
+
+ service_account = _prompt_optimizer_utils._get_service_account(config)
+
+ job_spec = types.CustomJobSpec(
+ worker_pool_specs=worker_pool_specs,
+ base_output_directory=genai_types.GcsDestination(output_uri_prefix=bucket),
+ service_account=service_account,
+ )
+
+ custom_job = types.CustomJob(
+ display_name=display_name,
+ job_spec=job_spec,
+ )
+
+ job = self._create_custom_job_resource(
+ custom_job=custom_job,
+ )
+
+ # Get the job resource name
+ job_resource_name = job.name
+ if not job_resource_name:
+ raise ValueError(f"Error creating job: {job}")
+ job_id = job_resource_name.split("/")[-1]
+ logger.info("Job created: %s", job.name)
+
+ # Construct the dashboard URL
+ dashboard_url = f"https://console.cloud.google.com/vertex-ai/locations/{region}/training/{job_id}/cpu?project={project}"
+ logger.info("View the job status at: %s", dashboard_url)
+
+ if wait_for_completion:
+ job = self._wait_for_completion(job_id)
+ return job
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI prompts.optimize method is "
+ "experimental, and may change in future versions."
+ )
+ def optimize(
+ self,
+ *,
+ prompt: str,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Makes an API request to optimize a prompt and returns the parsed response.
+
+ Example usage:
+ client = agentplatform.Client(project=PROJECT_NAME, location='us-central1')
+ prompt = "Generate system instructions for analyzing medical articles"
+ response = client.prompts.optimize(prompt=prompt)
+
+ Args:
+ prompt: Required. The prompt to optimize.
+ config: Optional. The configuration for prompt optimization. To optimize
+ prompts from Android API provide
+ types.OptimizeConfig(
+ optimization_target=types.OptimizeTarget.OPTIMIZATION_TARGET_GEMINI_NANO
+ )
+ For few-shot optimization, provide:
+
+ optim_target = types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS
+ or
+ optim_target = types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
+ types.OptimizeConfig(
+ optimization_target=optim_target,
+ examples_dataframe=dataframe
+ )
+ OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS indicates that the few-shot
+ examples include specific scoring rubrics and their corresponding
+ evaluations.
+ OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE indicates that the few-shot
+ examples include a ground-truth target response.
+ Returns:
+ The parsed response from the API request.
+ """
+
+ if isinstance(config, dict):
+ config = types.OptimizeConfig(**config)
+
+ optimization_target: Optional[types.OptimizeTarget] = None
+ if config is not None:
+ optimization_target = config.optimization_target
+
+ final_prompt = prompt
+ if (
+ optimization_target
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS
+ or optimization_target
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
+ ):
+ final_prompt = _prompt_optimizer_utils._get_few_shot_prompt(prompt, config)
+
+ # TODO: b/435653980 - replace the custom method with a generated method.
+ config_for_api = config.model_copy() if config else None
+ return self._custom_optimize(
+ content=genai_types.Content(
+ parts=[genai_types.Part(text=final_prompt)], role="user"
+ ),
+ config=config_for_api,
+ )
+
+ def _custom_optimize(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Internal method to call the optimizePrompt endpoint.
+
+ Sends a request to the tuningJobs:optimizePrompt streaming endpoint.
+ Then gathers the response, concatenates into one string and returns
+ the parsed response.
+ """
+ if isinstance(config, dict):
+ config.pop("examples_dataframe", None)
+ elif config and hasattr(config, "examples_dataframe"):
+ del config.examples_dataframe
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError("This method is only supported in the Vertex AI client.")
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[genai_types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_list = "" if not response.body else json.loads(response.body)
+
+ return_value = []
+
+ for response_dict in response_list:
+ response_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict, kwargs=parameter_model.model_dump()
+ )
+ self._api_client._verify_response(response_value)
+ content = response_value.content
+ if content is not None:
+ parts = content.parts
+ if parts and parts[0].text is not None:
+ return_value.append(parts[0].text)
+
+ output = "".join(return_value)
+ final_response = types.OptimizeResponse(raw_text_response=output)
+ try:
+ final_response.parsed_response = _prompt_optimizer_utils._parse(output)
+ except (ValueError, TypeError, ValidationError) as e:
+ logger.warning(
+ f"Failed to parse response: {e}. Returning only raw_text_response."
+ )
+ return final_response
+
+ def update(
+ self,
+ *,
+ prompt_id: str,
+ prompt: types.PromptOrDict,
+ config: Optional[types.UpdatePromptConfigOrDict] = None,
+ ) -> types.Prompt:
+ """Updates an existing prompt and creates a new version for the prompt associated with the provided prompt_id.
+
+ Args:
+ prompt_id: The ID of the prompt to create a new version for.
+ prompt: The updated prompt.
+ config: Optional configuration for updating the prompt.
+
+ Returns:
+ A types.Prompt object representing the updated prompt with its associated
+ Dataset and Dataset Version resources.
+ """
+
+ if isinstance(prompt, dict):
+ prompt = types.Prompt(**prompt)
+ if isinstance(config, dict):
+ config = types.UpdatePromptConfig(**config)
+ elif not config:
+ config = types.UpdatePromptConfig()
+
+ prompt_metadata = _prompt_management_utils._create_dataset_metadata_from_prompt(
+ prompt,
+ variables=(
+ prompt.prompt_data.variables
+ if prompt.prompt_data and prompt.prompt_data.variables
+ else None
+ ),
+ )
+
+ if not prompt.prompt_data:
+ raise ValueError("Prompt data is required to update a prompt.")
+
+ # Step 1: Update the dataset resource for the prompt and wait for the operation to complete.
+ updated_dataset_resource = self._update_dataset_resource(
+ name=f"projects/{self._api_client.project}/locations/{self._api_client.location}",
+ dataset_id=prompt_id,
+ display_name=(
+ config.prompt_display_name
+ if config and config.prompt_display_name
+ else None
+ ),
+ metadata=prompt_metadata,
+ model_reference=prompt.prompt_data.model,
+ encryption_spec=(
+ config.encryption_spec if config and config.encryption_spec else None
+ ),
+ config=config,
+ )
+
+ if not updated_dataset_resource.name:
+ raise ValueError("Failed to update dataset resource.")
+
+ dataset_id = updated_dataset_resource.name.split("/")[-1]
+
+ # Step 2: Create a dataset version for the prompt.
+ create_dataset_version_operation = self._create_dataset_version_resource(
+ dataset_name=dataset_id,
+ display_name=(
+ config.version_display_name
+ if config and config.version_display_name is not None
+ else f"prompt_version_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ )
+ dataset_version_resource_name = self._wait_for_operation(
+ operation=create_dataset_version_operation,
+ timeout=config.timeout if config else 90,
+ )
+ dataset_version_id = dataset_version_resource_name.split("/")[-1]
+
+ # Step 3: Get the dataset version resource and return it with the prompt.
+ dataset_version_resource = self._get_dataset_version_resource(
+ dataset_id=dataset_id,
+ dataset_version_id=dataset_version_id,
+ )
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ dataset_version_resource
+ )
+ prompt._dataset = updated_dataset_resource
+ prompt._dataset_version = dataset_version_resource
+ return prompt
+
+
+class AsyncPrompts(_api_module.BaseModule):
+
+ async def _create_dataset_resource(
+ self,
+ *,
+ name: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata_schema_uri: Optional[str] = None,
+ metadata: Optional[types.SchemaTextPromptDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ model_reference: Optional[str] = None,
+ config: Optional[types.CreateDatasetConfigOrDict] = None,
+ ) -> types.DatasetOperation:
+ """
+ Creates a dataset resource to store prompts.
+ """
+
+ parameter_model = types._CreateDatasetParameters(
+ name=name,
+ display_name=display_name,
+ metadata_schema_uri=metadata_schema_uri,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ model_reference=model_reference,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create_dataset_version_resource(
+ self,
+ *,
+ dataset_name: Optional[str] = None,
+ metadata: Optional[types.SchemaTextPromptDatasetMetadataOrDict] = None,
+ model_reference: Optional[str] = None,
+ parent: Optional[str] = None,
+ display_name: Optional[str] = None,
+ config: Optional[types.CreateDatasetVersionConfigOrDict] = None,
+ ) -> types.DatasetOperation:
+ """
+ Creates a dataset version resource to store prompts.
+ """
+
+ parameter_model = types._CreateDatasetVersionParameters(
+ dataset_name=dataset_name,
+ metadata=metadata,
+ model_reference=model_reference,
+ parent=parent,
+ display_name=display_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateDatasetVersionParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{name}/datasetVersions".format_map(request_url_dict)
+ else:
+ path = "datasets/{name}/datasetVersions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_dataset_resource(
+ self,
+ *,
+ name: Optional[str] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.Dataset:
+ """
+ Gets a dataset resource to store prompts.
+ """
+
+ parameter_model = types._GetDatasetParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{name}".format_map(request_url_dict)
+ else:
+ path = "datasets/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Dataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_dataset_version_resource(
+ self,
+ *,
+ dataset_id: Optional[str] = None,
+ dataset_version_id: Optional[str] = None,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.DatasetVersion:
+ """
+ Gets a dataset version resource to store prompts.
+ """
+
+ parameter_model = types._GetDatasetVersionParameters(
+ dataset_id=dataset_id,
+ dataset_version_id=dataset_version_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetDatasetVersionParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions/{dataset_version_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions/{dataset_version_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetVersion._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_dataset_operation(
+ self,
+ *,
+ dataset_id: Optional[str] = None,
+ operation_id: Optional[str] = None,
+ config: Optional[types.GetDatasetOperationConfigOrDict] = None,
+ ) -> types.DatasetOperation:
+ """
+ Gets the operation from creating a dataset.
+ """
+
+ parameter_model = types._GetDatasetOperationParameters(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetDatasetOperationParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/operations/{operation_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/operations/{operation_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DatasetOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list_prompts(
+ self, *, config: Optional[types.ListPromptsConfigOrDict] = None
+ ) -> types.ListDatasetsResponse:
+ """
+ Lists Agent Engines.
+ """
+
+ parameter_model = types._ListDatasetsRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListDatasetsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets".format_map(request_url_dict)
+ else:
+ path = "datasets"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListDatasetsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list_versions(
+ self,
+ *,
+ read_mask: Optional[str] = None,
+ dataset_id: Optional[str] = None,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> types.ListDatasetVersionsResponse:
+ """
+ Lists Agent Engines.
+ """
+
+ parameter_model = types._ListDatasetVersionsRequestParameters(
+ read_mask=read_mask,
+ dataset_id=dataset_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListDatasetVersionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListDatasetVersionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete_dataset(
+ self, *, prompt_id: str, config: Optional[types.DeletePromptConfigOrDict] = None
+ ) -> types.DeletePromptOperation:
+ parameter_model = types._DeleteDatasetRequestParameters(
+ prompt_id=prompt_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteDatasetRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}".format_map(request_url_dict)
+ else:
+ path = "datasets/{dataset_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeletePromptOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete_dataset_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.DeletePromptConfigOrDict] = None,
+ ) -> types.DeletePromptVersionOperation:
+ parameter_model = types._DeletePromptVersionRequestParameters(
+ prompt_id=prompt_id,
+ version_id=version_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeletePromptVersionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeletePromptVersionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _restore_version(
+ self,
+ *,
+ dataset_id: str,
+ version_id: str,
+ config: Optional[types.RestoreVersionConfigOrDict] = None,
+ ) -> types.RestoreVersionOperation:
+ """
+ Restores the provided prompt version to the latest version.
+ """
+
+ parameter_model = types._RestoreVersionRequestParameters(
+ dataset_id=dataset_id,
+ version_id=version_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RestoreVersionRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}:restore".format_map(
+ request_url_dict
+ )
+ else:
+ path = "datasets/{dataset_id}/datasetVersions/{version_id}:restore"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RestoreVersionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _update_dataset_resource(
+ self,
+ *,
+ name: Optional[str] = None,
+ dataset_id: Optional[str] = None,
+ display_name: Optional[str] = None,
+ metadata: Optional[types.SchemaTextPromptDatasetMetadataOrDict] = None,
+ description: Optional[str] = None,
+ encryption_spec: Optional[genai_types.EncryptionSpecOrDict] = None,
+ model_reference: Optional[str] = None,
+ config: Optional[types.UpdatePromptConfigOrDict] = None,
+ ) -> types.Dataset:
+ """
+ Creates a dataset resource to store prompts.
+ """
+
+ parameter_model = types._UpdateDatasetParameters(
+ name=name,
+ dataset_id=dataset_id,
+ display_name=display_name,
+ metadata=metadata,
+ description=description,
+ encryption_spec=encryption_spec,
+ model_reference=model_reference,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateDatasetParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "datasets/{dataset_id}".format_map(request_url_dict)
+ else:
+ path = "datasets/{dataset_id}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "patch", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Dataset._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create_custom_job_resource(
+ self,
+ *,
+ custom_job: types.CustomJobOrDict,
+ config: Optional[types.VertexBaseConfigOrDict] = None,
+ ) -> types.CustomJob:
+ """
+ Creates a custom job.
+ """
+
+ parameter_model = types._CustomJobParameters(
+ custom_job=custom_job,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs".format_map(request_url_dict)
+ else:
+ path = "customJobs"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_custom_job(
+ self, *, name: str, config: Optional[types.VertexBaseConfigOrDict] = None
+ ) -> types.CustomJob:
+ """
+ Gets a custom job.
+ """
+
+ parameter_model = types._GetCustomJobParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetCustomJobParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "customJobs/{name}".format_map(request_url_dict)
+ else:
+ path = "customJobs/{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ if self._api_client.vertexai:
+ response_dict = _CustomJob_from_vertex(response_dict)
+
+ return_value = types.CustomJob._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _optimize(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponseEndpoint:
+ """
+ Optimize a single prompt.
+ """
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def create(
+ self,
+ *,
+ prompt: types.PromptOrDict,
+ config: Optional[types.CreatePromptConfigOrDict] = None,
+ ) -> types.Prompt:
+ """Creates a new prompt in a Vertex Dataset resource.
+
+ This method waits for prompt creation to be complete before returning.
+
+ Note: This method does not create a versioned resource for your prompt.
+ Call create_version() to create a new prompt resource with a version.
+
+ Args:
+ prompt: The prompt to create.
+ config: Optional configuration for creating the prompt.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated
+ Dataset resources.
+ """
+ if isinstance(prompt, dict):
+ prompt = types.Prompt(**prompt)
+ if isinstance(config, dict):
+ config = types.CreatePromptConfig(**config)
+ elif not config:
+ config = types.CreatePromptConfig()
+
+ _prompt_management_utils._raise_for_invalid_prompt(prompt)
+
+ if prompt.prompt_data is None:
+ raise ValueError("Prompt data is required to create a prompt.")
+
+ prompt_metadata = _prompt_management_utils._create_dataset_metadata_from_prompt(
+ prompt,
+ variables=(
+ prompt.prompt_data.variables
+ if prompt.prompt_data and prompt.prompt_data.variables
+ else None
+ ),
+ )
+
+ # Step 1: Create the dataset resource for the prompt and wait for the operation to complete.
+ create_prompt_dataset_operation = await self._create_dataset_resource(
+ display_name=(
+ config.prompt_display_name
+ if config and config.prompt_display_name
+ else f"prompt_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ name=f"projects/{self._api_client.project}/locations/{self._api_client.location}",
+ metadata_schema_uri=_prompt_management_utils.PROMPT_SCHEMA_URI,
+ metadata=prompt_metadata,
+ model_reference=prompt.prompt_data.model,
+ encryption_spec=(
+ config.encryption_spec if config and config.encryption_spec else None
+ ),
+ )
+ dataset_resource_name = await self._wait_for_operation(
+ operation=create_prompt_dataset_operation,
+ timeout=config.timeout if config else 90,
+ )
+ dataset_id = dataset_resource_name.split("/")[-1]
+
+ # Step 2: Get the dataset resource
+ dataset_resource = await self._get_dataset_resource(
+ name=dataset_id,
+ )
+ prompt._dataset = dataset_resource
+ return prompt
+
+ async def create_version(
+ self,
+ *,
+ prompt: types.PromptOrDict,
+ config: Optional[types.CreatePromptVersionConfigOrDict] = None,
+ ) -> types.Prompt:
+ """Creates a prompt resource and an initial prompt version.
+
+ When creating new prompt and prompt version resources, this waits for
+ the create operation to complete before returning.
+
+ Note: This method is recommended instead of create() since it creates a
+ versioned resource for your prompt.
+
+ Args:
+ prompt: The prompt to create.
+ config: Optional configuration for creating the prompt and prompt version.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated
+ Dataset and Dataset Version resources.
+ """
+ if isinstance(prompt, dict):
+ prompt = types.Prompt(**prompt)
+ if isinstance(config, dict):
+ config = types.CreatePromptVersionConfig(**config)
+ elif not config:
+ config = types.CreatePromptVersionConfig()
+
+ _prompt_management_utils._raise_for_invalid_prompt(prompt)
+
+ if prompt.prompt_data is None:
+ raise ValueError("Prompt data is required to create a prompt.")
+
+ prompt_metadata = _prompt_management_utils._create_dataset_metadata_from_prompt(
+ prompt,
+ variables=(
+ prompt.prompt_data.variables
+ if prompt.prompt_data and prompt.prompt_data.variables
+ else None
+ ),
+ )
+
+ # Step 1: Create the dataset resource for the prompt and wait for the operation to complete.
+ create_prompt_dataset_operation = await self._create_dataset_resource(
+ display_name=(
+ config.prompt_display_name
+ if config and config.prompt_display_name
+ else f"prompt_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ name=f"projects/{self._api_client.project}/locations/{self._api_client.location}",
+ metadata_schema_uri=_prompt_management_utils.PROMPT_SCHEMA_URI,
+ metadata=prompt_metadata,
+ model_reference=prompt.prompt_data.model,
+ encryption_spec=(
+ config.encryption_spec if config and config.encryption_spec else None
+ ),
+ )
+ dataset_resource_name = await self._wait_for_operation(
+ operation=create_prompt_dataset_operation,
+ timeout=config.timeout if config else 90,
+ )
+ dataset_id = dataset_resource_name.split("/")[-1]
+
+ # Step 2: Get the dataset resource
+ dataset_resource = await self._get_dataset_resource(
+ name=dataset_id,
+ )
+ prompt._dataset = dataset_resource
+
+ if prompt._dataset.name is None:
+ raise ValueError("Invalid dataset resource.")
+
+ # Step 3: Create the dataset version
+ create_dataset_version_operation = await self._create_dataset_version_resource(
+ dataset_name=prompt._dataset.name.split("/")[-1],
+ display_name=(
+ config.version_display_name
+ if config and config.version_display_name is not None
+ else f"prompt_version_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ )
+ dataset_version_resource_name = await self._wait_for_operation(
+ operation=create_dataset_version_operation,
+ timeout=config.timeout if config else 90,
+ )
+
+ # Step 4: Get the dataset version resource and return it with the prompt
+ dataset_version_resource = await self._get_dataset_version_resource(
+ dataset_id=dataset_id,
+ dataset_version_id=dataset_version_resource_name.split("/")[-1],
+ )
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ dataset_version_resource
+ )
+ prompt._dataset = dataset_resource
+ prompt._dataset_version = dataset_version_resource
+ return prompt
+
+ async def update(
+ self,
+ *,
+ prompt_id: str,
+ prompt: types.PromptOrDict,
+ config: Optional[types.UpdatePromptConfigOrDict] = None,
+ ) -> types.Prompt:
+ """Updates an existing prompt and creates a new version for the prompt
+ associated with the provided prompt_id.
+
+ Args:
+ prompt_id: The ID of the prompt to create a new version for.
+ prompt: The updated prompt.
+ config: Optional configuration for updating the prompt.
+
+ Returns:
+ A types.Prompt object representing the updated prompt with its associated
+ Dataset and Dataset Version resources.
+ """
+
+ if isinstance(prompt, dict):
+ prompt = types.Prompt(**prompt)
+ if isinstance(config, dict):
+ config = types.UpdatePromptConfig(**config)
+ elif not config:
+ config = types.UpdatePromptConfig()
+
+ prompt_metadata = _prompt_management_utils._create_dataset_metadata_from_prompt(
+ prompt,
+ variables=(
+ prompt.prompt_data.variables
+ if prompt.prompt_data and prompt.prompt_data.variables
+ else None
+ ),
+ )
+
+ if not prompt.prompt_data:
+ raise ValueError("Prompt data is required to update a prompt.")
+
+ # Step 1: Update the dataset resource for the prompt and wait for the operation to complete.
+ updated_dataset_resource = await self._update_dataset_resource(
+ name=f"projects/{self._api_client.project}/locations/{self._api_client.location}",
+ dataset_id=prompt_id,
+ display_name=(
+ config.prompt_display_name
+ if config and config.prompt_display_name
+ else None
+ ),
+ metadata=prompt_metadata,
+ model_reference=prompt.prompt_data.model,
+ encryption_spec=(
+ config.encryption_spec if config and config.encryption_spec else None
+ ),
+ config=config,
+ )
+
+ if not updated_dataset_resource.name:
+ raise ValueError("Failed to update dataset resource.")
+
+ dataset_id = updated_dataset_resource.name.split("/")[-1]
+
+ # Step 2: Create a dataset version for the prompt.
+ create_dataset_version_operation = await self._create_dataset_version_resource(
+ dataset_name=dataset_id,
+ display_name=(
+ config.version_display_name
+ if config and config.version_display_name is not None
+ else f"prompt_version_{time.strftime('%Y%m%d-%H%M%S')}"
+ ),
+ )
+ dataset_version_resource_name = await self._wait_for_operation(
+ operation=create_dataset_version_operation,
+ timeout=config.timeout if config else 90,
+ )
+ dataset_version_id = dataset_version_resource_name.split("/")[-1]
+
+ # Step 3: Get the dataset version resource and return it with the prompt.
+ dataset_version_resource = await self._get_dataset_version_resource(
+ dataset_id=dataset_id,
+ dataset_version_id=dataset_version_id,
+ )
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ dataset_version_resource
+ )
+ prompt._dataset = updated_dataset_resource
+ prompt._dataset_version = dataset_version_resource
+ return prompt
+
+ async def _wait_for_operation(
+ self,
+ operation: types.DatasetOperation,
+ timeout: int,
+ ) -> str:
+ """Waits for a dataset operation to complete.
+
+ Args:
+ operation: The dataset operation to wait for.
+ timeout: The maximum time to wait for the operation to complete.
+
+ Returns:
+ The name of the Dataset resource from the operation result.
+
+ Raises:
+ TimeoutError: If the operation does not complete within the timeout.
+ ValueError: If the operation fails.
+ """
+ done = False
+ prompt_dataset_operation: Optional[types.DatasetOperation] = None
+
+ response_operation_name = operation.name
+ if response_operation_name is None:
+ raise ValueError("Invalid operation name.")
+
+ dataset_id = response_operation_name.split("/datasets/")[1].split("/")[0]
+ operation_id = response_operation_name.split("/")[-1]
+
+ start_time = time.time()
+ sleep_duration = 5
+ wait_multiplier = 2
+ max_wait_time = 60
+ previous_time = time.time()
+
+ while not done:
+ if (time.time() - start_time) > timeout:
+ raise TimeoutError(
+ "Create prompt operation did not complete within the"
+ f" specified timeout of {timeout} seconds."
+ )
+ current_time = time.time()
+ if current_time - previous_time >= sleep_duration:
+ sleep_duration = min(sleep_duration * wait_multiplier, max_wait_time)
+ previous_time = current_time
+ await asyncio.sleep(sleep_duration)
+ prompt_dataset_operation = await self._get_dataset_operation(
+ dataset_id=dataset_id,
+ operation_id=operation_id,
+ )
+ done = (
+ (prompt_dataset_operation.done or False)
+ if hasattr(prompt_dataset_operation, "done")
+ else False
+ )
+ if (
+ not prompt_dataset_operation
+ or prompt_dataset_operation.response is None
+ or prompt_dataset_operation.response.get("name") is None
+ ):
+ raise ValueError("Error creating prompt version resource.")
+ if (
+ hasattr(prompt_dataset_operation, "error")
+ and prompt_dataset_operation.error is not None
+ ):
+ raise ValueError(
+ f"Error creating prompt version resource: {prompt_dataset_operation.error}"
+ )
+ return prompt_dataset_operation.response.get("name") # type: ignore[return-value]
+
+ async def get(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.GetPromptConfig] = None,
+ ) -> types.Prompt:
+ """Gets a prompt resource from a Vertex Dataset.
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ config: Optional configuration for getting the prompt.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated Dataset and Dataset Version resources.
+ """
+
+ prompt_dataset_resource = await self._get_dataset_resource(name=prompt_id)
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ prompt_dataset_resource,
+ )
+ prompt._dataset = prompt_dataset_resource
+
+ return prompt
+
+ async def get_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.GetPromptConfig] = None,
+ ) -> types.Prompt:
+ """Gets a prompt resource from a Vertex Dataset.
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ version_id: The id of the Vertex Dataset Version resource containing the prompt version. For example, if the prompt version resource name is "projects/123/locations/us-central1/datasets/456/datasetVersions/1", then the version_id is "1".
+ config: Optional configuration for getting the prompt.
+
+ Returns:
+ A types.Prompt object representing the prompt with its associated Dataset and Dataset Version resources.
+ """
+
+ prompt_dataset_resource = await self._get_dataset_resource(name=prompt_id)
+ prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ prompt_dataset_resource,
+ )
+ prompt._dataset = prompt_dataset_resource
+
+ prompt_version_resource = await self._get_dataset_version_resource(
+ dataset_id=prompt_id,
+ dataset_version_id=version_id,
+ )
+ prompt._dataset_version = prompt_version_resource
+
+ return prompt
+
+ async def _wait_for_project_operation(
+ self,
+ operation: genai_types.ProjectOperation,
+ timeout: int,
+ ) -> None:
+ """Waits for a dataset deletion operation to complete.
+
+ Delete operations are project level operations and are separate from dataset resource operations, for example: projects/123/locations/us-central1/operations/789.
+
+ Args:
+ operation: The project operation to wait for.
+ timeout: The maximum time to wait for the operation to complete.
+ Raises:
+ TimeoutError: If the operation does not complete within the timeout.
+ ValueError: If the operation fails.
+ """
+ done = False
+
+ start_time = time.time()
+ sleep_duration = 5
+ wait_multiplier = 2
+ max_wait_time = 60
+ previous_time = time.time()
+ while not done:
+ if (time.time() - start_time) > timeout:
+ raise TimeoutError(
+ f"Delete operation did not complete within the"
+ f" specified timeout of {timeout} seconds."
+ )
+ current_time = time.time()
+ if current_time - previous_time >= sleep_duration:
+ sleep_duration = min(sleep_duration * wait_multiplier, max_wait_time)
+ previous_time = current_time
+ await asyncio.sleep(sleep_duration)
+ operations_module = operations.AsyncOperations(api_client_=self._api_client)
+
+ if operation.name is None:
+ raise ValueError("Invalid operation name.")
+ operation = await operations_module._get(
+ operation_id=operation.name.split("/")[-1],
+ )
+ done = (operation.done or False) if hasattr(operation, "done") else False
+ if hasattr(operation, "error") and operation.error is not None:
+ raise ValueError(f"Error in delete operation: {operation.error}")
+
+ async def delete(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.DeletePromptConfig] = None,
+ ) -> None:
+ """Deletes a prompt resource.
+
+ Args:
+ prompt_id: The id of the prompt resource to delete.
+
+ Raises:
+ TimeoutError: If the delete operation does not complete within the timeout.
+ ValueError: If the delete operation fails.
+ """
+
+ delete_prompt_operation = await self._delete_dataset(
+ prompt_id=prompt_id,
+ config=config,
+ )
+ await self._wait_for_project_operation(
+ operation=delete_prompt_operation, timeout=config.timeout if config else 90
+ )
+ logger.info(f"Deleted prompt with id: {prompt_id}")
+
+ async def delete_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.DeletePromptConfig] = None,
+ ) -> None:
+ """Deletes a prompt version resource.
+
+ Args:
+ prompt_id: The id of the prompt resource to delete.
+ version_id: The id of the prompt version resource to delete.
+
+ Raises:
+ TimeoutError: If the delete operation does not complete within the timeout.
+ ValueError: If the delete operation fails.
+ """
+ delete_version_operation = await self._delete_dataset_version(
+ prompt_id=prompt_id,
+ version_id=version_id,
+ config=config,
+ )
+
+ await self._wait_for_project_operation(
+ operation=delete_version_operation, timeout=config.timeout if config else 90
+ )
+ logger.info(
+ f"Deleted prompt version {version_id} from prompt with id: {prompt_id}"
+ )
+
+ async def _list_prompts_pager(
+ self,
+ *,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> AsyncPager[types.Dataset]:
+ return AsyncPager(
+ "datasets",
+ self._list_prompts,
+ await self._list_prompts(config=config),
+ config,
+ )
+
+ async def _list_versions_pager(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> AsyncPager[types.DatasetVersion]:
+ return AsyncPager(
+ "dataset_versions",
+ self._list_versions,
+ await self._list_versions(config=config, dataset_id=prompt_id),
+ config,
+ )
+
+ async def list(
+ self,
+ *,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> AsyncIterator[types.PromptRef]:
+ """Lists prompt resources in a project.
+
+ This method retrieves all the prompts from the project provided in the
+ agentplatform.Client constructor and returns a list of prompt references containing the prompt_id and model for the prompt.
+
+ To get the full types.Prompt resource for a PromptRef after calling this method, use the get() method with the prompt_id as the prompt_id argument.
+ Example usage:
+
+ ```
+ prompt_refs = client.aio.prompt_management.list_prompts()
+ async for prompt_ref in prompt_refs:
+ await client.prompt_management.get(prompt_id=prompt_ref.prompt_id)
+ ```
+
+ Args:
+ config: Optional configuration for listing prompts.
+
+ Returns:
+ An async iterator of types.PromptRef objects.
+ """
+ if isinstance(config, dict):
+ config = types.ListPromptsConfig(**config)
+ elif not config:
+ config = types.ListPromptsConfig()
+ async for dataset in await self._list_prompts_pager(config=config):
+ if not dataset or not dataset.model_reference or not dataset.name:
+ continue
+ prompt_ref = types.PromptRef(
+ model=dataset.model_reference, prompt_id=dataset.name.split("/")[-1]
+ )
+ yield prompt_ref
+
+ async def list_versions(
+ self,
+ *,
+ prompt_id: str,
+ config: Optional[types.ListPromptsConfigOrDict] = None,
+ ) -> AsyncIterator[types.PromptVersionRef]:
+ """Lists prompt version resources for a provided prompt_id.
+
+ This method retrieves all the prompt versions for a provided prompt_id.
+
+ To get the full types.Prompt resource for a PromptVersionRef after calling this method, use the get() method with the returned prompt_id and version_id.
+ Example usage:
+
+ ```
+ prompt_version_refs = await client.prompt_management.list_versions(prompt_id="123")
+ async for version_ref in prompt_version_refs:
+ await client.aio.prompt_management.get(prompt_id=version_ref.prompt_id, version_id=version_ref.version_id)
+ ```
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ config: Optional configuration for listing prompts.
+
+ Returns:
+ An async iterator of types.PromptVersionRef objects representing the prompt version resources for the provided prompt_id.
+
+ """
+ if isinstance(config, dict):
+ config = types.ListPromptsConfig(**config)
+ elif not config:
+ config = types.ListPromptsConfig()
+ async for dataset_version in await self._list_versions_pager(
+ config=config, prompt_id=prompt_id
+ ):
+ if (
+ not dataset_version
+ or not dataset_version.model_reference
+ or not dataset_version.name
+ ):
+ continue
+ prompt_version_ref = types.PromptVersionRef(
+ model=dataset_version.model_reference,
+ version_id=dataset_version.name.split("/")[-1],
+ prompt_id=prompt_id,
+ )
+ yield prompt_version_ref
+
+ async def restore_version(
+ self,
+ *,
+ prompt_id: str,
+ version_id: str,
+ config: Optional[types.RestoreVersionConfig] = None,
+ ) -> types.Prompt:
+ """Restores the provided prompt version to the latest version.
+
+ Args:
+ prompt_id: The id of the Vertex Dataset resource containing the prompt. For example, if the prompt resource name is "projects/123/locations/us-central1/datasets/456", then the prompt_id is "456".
+ version_id: The id of the Vertex Dataset Version resource to restore. For example, if the version resource name is "projects/123/locations/us-central1/datasets/456/datasetVersions/789", then the version_id is "789".
+ config: Optional configuration for restoring the prompt version.
+
+ Returns:
+ A types.Prompt object representing the prompt with the updated Dataset Version resource.
+ """
+
+ restore_prompt_operation = await self._restore_version(
+ dataset_id=prompt_id,
+ version_id=version_id,
+ )
+ await self._wait_for_project_operation(
+ operation=restore_prompt_operation,
+ timeout=90,
+ )
+ dataset_version_resource = await self._get_dataset_version_resource(
+ dataset_id=prompt_id,
+ dataset_version_id=version_id,
+ )
+ updated_prompt = _prompt_management_utils._create_prompt_from_dataset_metadata(
+ dataset_version_resource,
+ )
+ updated_prompt._dataset_version = dataset_version_resource
+ return updated_prompt
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI prompts.launch_optimization_job method is "
+ "experimental, and may change in future versions."
+ )
+ async def launch_optimization_job(
+ self,
+ method: types.PromptOptimizerMethod,
+ config: types.PromptOptimizerConfigOrDict,
+ ) -> types.CustomJob:
+ """Call async Vertex AI Prompt Optimizer (VAPO).
+
+
+ Note: The `wait_for_completion` parameter in the config will be
+ ignored when using the AsyncClient, as it is not supported.
+
+ Example usage:
+ client = agentplatform.Client(project=PROJECT_NAME, location='us-central1')
+ vapo_config = agentplatform.types.PromptOptimizerConfig(
+ config_path='gs://you-bucket-name/your-config.json',
+ service_account=service_account,
+ )
+ job = await client.aio.prompts.launch_optimization_job(
+ method=types.PromptOptimizerMethod.VAPO, config=vapo_config)
+
+ Args:
+ method: The method for optimizing multiple prompts. Supported methods:
+ VAPO, OPTIMIZATION_TARGET_GEMINI_NANO.
+ config: PromptOptimizerConfig instance containing the
+ configuration for prompt optimization.
+ Returns:
+ The custom job that was created.
+ """
+ if isinstance(config, dict):
+ config = types.PromptOptimizerConfig(**config)
+
+ if not config.config_path:
+ raise ValueError("Config path is required.")
+
+ _OPTIMIZER_METHOD_TO_CONTAINER_URI = {
+ types.PromptOptimizerMethod.VAPO: "us-docker.pkg.dev/vertex-ai/cair/vaipo:preview_v1_0",
+ types.PromptOptimizerMethod.OPTIMIZATION_TARGET_GEMINI_NANO: "us-docker.pkg.dev/vertex-ai/cair/vaipo:preview_android_v1_0",
+ }
+ container_uri = _OPTIMIZER_METHOD_TO_CONTAINER_URI.get(method)
+ if not container_uri:
+ raise ValueError(
+ 'Only "VAPO" and "OPTIMIZATION_TARGET_GEMINI_NANO" '
+ "methods are currently supported."
+ )
+
+ if config.wait_for_completion:
+ logger.info(
+ "Ignoring wait_for_completion=True since the AsyncClient does not support it."
+ )
+
+ if config.optimizer_job_display_name:
+ display_name = config.optimizer_job_display_name
+ else:
+ timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
+ display_name = f"{method.value.lower()}-optimizer-{timestamp}"
+
+ if not config.config_path:
+ raise ValueError("Config path is required.")
+ bucket = "/".join(config.config_path.split("/")[:-1])
+
+ region = self._api_client.location
+ project = self._api_client.project
+ container_args = {
+ "config": config.config_path,
+ }
+ args = ["--%s=%s" % (k, v) for k, v in container_args.items()]
+ worker_pool_specs = [
+ types.WorkerPoolSpec(
+ replica_count=1,
+ machine_spec=types.MachineSpec(machine_type="n1-standard-4"),
+ container_spec=types.ContainerSpec(
+ image_uri=container_uri,
+ args=args,
+ ),
+ )
+ ]
+
+ service_account = _prompt_optimizer_utils._get_service_account(config)
+
+ job_spec = types.CustomJobSpec(
+ worker_pool_specs=worker_pool_specs,
+ base_output_directory=genai_types.GcsDestination(output_uri_prefix=bucket),
+ service_account=service_account,
+ )
+
+ custom_job = types.CustomJob(
+ display_name=display_name,
+ job_spec=job_spec,
+ )
+
+ job = await self._create_custom_job_resource(
+ custom_job=custom_job,
+ )
+
+ # Get the job id for the dashboard url and display to the user.
+ job_resource_name = job.name
+ if not job_resource_name:
+ raise ValueError(f"Error creating job: {job}")
+ job_id = job_resource_name.split("/")[-1]
+ logger.info("Job created: %s", job.name)
+
+ # Construct the dashboard URL to show to the user.
+ dashboard_url = f"https://console.cloud.google.com/vertex-ai/locations/{region}/training/{job_id}/cpu?project={project}"
+ logger.info("View the job status at: %s", dashboard_url)
+
+ return job
+
+ async def _custom_optimize(
+ self,
+ *,
+ content: Optional[genai_types.ContentOrDict] = None,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Optimize a single prompt."""
+ if isinstance(config, dict):
+ config.pop("examples_dataframe", None)
+ elif config and hasattr(config, "examples_dataframe"):
+ del config.examples_dataframe
+
+ parameter_model = types._OptimizeRequestParameters(
+ content=content,
+ config=config,
+ )
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError("This method is only supported in the Vertex AI client.")
+ else:
+ request_dict = _OptimizeRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "tuningJobs:optimizePrompt".format_map(request_url_dict)
+ else:
+ path = "tuningJobs:optimizePrompt"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_list = "" if not response.body else json.loads(response.body)
+
+ return_value = []
+
+ for response_dict in response_list:
+ response_value = types.OptimizeResponseEndpoint._from_response(
+ response=response_dict, kwargs=parameter_model.model_dump()
+ )
+ self._api_client._verify_response(response_value)
+ content = response_value.content
+ if content is not None:
+ parts = content.parts
+ if parts and parts[0].text is not None:
+ return_value.append(parts[0].text)
+
+ output = "".join(return_value)
+ final_response = types.OptimizeResponse(raw_text_response=output)
+ try:
+ final_response.parsed_response = _prompt_optimizer_utils._parse(output)
+ except Exception as e:
+ logger.warning(
+ f"Failed to parse response: {e}. Returning only raw_text_response."
+ )
+ return final_response
+
+ @_common.experimental_warning(
+ "The Vertex SDK GenAI prompts.optimize method is "
+ "experimental, and may change in future versions."
+ )
+ async def optimize(
+ self,
+ *,
+ prompt: str,
+ config: Optional[types.OptimizeConfigOrDict] = None,
+ ) -> types.OptimizeResponse:
+ """Makes an async request to the optimizePrompt endpoint and returns an optimized prompt.
+
+ Example usage:
+ client = agentplatform.Client(project=PROJECT_NAME, location='us-central1')
+ prompt = "Generate system instructions for analyzing medical articles"
+ response = await client.aio.prompts.optimize(prompt=prompt)
+
+ Args:
+ prompt: Required. The prompt to optimize.
+ config: Optional.The configuration for prompt optimization. To optimize
+ prompts from Android API provide
+ types.OptimizeConfig(
+ optimization_target=types.OptimizeTarget.OPTIMIZATION_TARGET_GEMINI_NANO
+ )
+ For few-shot optimization, provide:
+ optim_target = types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS # or types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
+ types.OptimizeConfig(
+ optimization_target=optim_target,
+ examples_dataframe=dataframe
+ )
+ OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS indicates that the few-shot
+ examples include specific scoring rubrics and their corresponding
+ evaluations.
+ OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE indicates that the few-shot
+ examples include a ground-truth target response.
+ Returns:
+ The parsed response from the API request.
+ """
+ if isinstance(config, dict):
+ config = types.OptimizeConfig(**config)
+
+ optimization_target: Optional[types.OptimizeTarget] = None
+ if config is not None:
+ optimization_target = config.optimization_target
+
+ final_prompt = prompt
+ if (
+ optimization_target
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS
+ or optimization_target
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
+ ):
+ final_prompt = _prompt_optimizer_utils._get_few_shot_prompt(prompt, config)
+
+ # TODO: b/435653980 - replace the custom method with a generated method.
+ config_for_api = config.model_copy() if config else None
+ return await self._custom_optimize(
+ content=genai_types.Content(
+ parts=[genai_types.Part(text=final_prompt)], role="user"
+ ),
+ config=config_for_api,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/runtime_revisions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/runtime_revisions.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4a8d49fd19a5f3809739fe5b869480013b6f72d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/runtime_revisions.py
@@ -0,0 +1,1257 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import json
+import logging
+from typing import Any, AsyncIterator, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import _agent_engines_utils
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.runtimerevisions")
+
+logger.setLevel(logging.INFO)
+
+
+def _DeleteAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GetAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GetDeleteAgentEngineRuntimeRevisionOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _ListAgentEngineRuntimeRevisionsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListAgentEngineRuntimeRevisionsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineRuntimeRevisionsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+def _QueryAgentEngineRuntimeRevisionConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["class_method"]) is not None:
+ setv(parent_object, ["classMethod"], getv(from_object, ["class_method"]))
+
+ if getv(from_object, ["input"]) is not None:
+ setv(parent_object, ["input"], getv(from_object, ["input"]))
+
+ if getv(from_object, ["include_all_fields"]) is not None:
+ setv(to_object, ["includeAllFields"], getv(from_object, ["include_all_fields"]))
+
+ return to_object
+
+
+def _QueryAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _QueryAgentEngineRuntimeRevisionConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class RuntimeRevisions(_api_module.BaseModule):
+
+ def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.ReasoningEngineRuntimeRevision:
+ """
+ Get an agent engine runtime revision instance.
+ """
+
+ parameter_model = types._GetAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ReasoningEngineRuntimeRevision._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineRuntimeRevisionsConfigOrDict] = None,
+ ) -> types.ListReasoningEnginesRuntimeRevisionsResponse:
+ """
+ Lists reasoning engine runtime revisions.
+
+ Args:
+ name (str): Required. The name of the reasoning engine to list runtime revisions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineRuntimeRevisionsConfig):
+ Optional. Additional configurations for listing the reasoning engine runtime revisions.
+
+ Returns:
+ ListReasoningEnginesRuntimeRevisionsResponse: The requested reasoning engine runtime revisions.
+
+ """
+
+ parameter_model = types._ListAgentEngineRuntimeRevisionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineRuntimeRevisionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/runtimeRevisions".format_map(request_url_dict)
+ else:
+ path = "{name}/runtimeRevisions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = (
+ types.ListReasoningEnginesRuntimeRevisionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineRuntimeRevisionOperation:
+ """
+ Delete an Agent Engine runtime revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine runtime revision to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/runtimeRevisions/{runtime_revision_id}`.
+ config (DeleteAgentEngineRuntimeRevisionConfig):
+ Optional. Additional configurations for deleting the Agent Engine runtime revision.
+
+ Returns:
+ DeleteAgentEngineRuntimeRevisionOperation: The operation for deleting the Agent Engine runtime revision.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineRuntimeRevisionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_delete_runtime_revision_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[
+ types.GetDeleteAgentEngineRuntimeRevisionOperationConfigOrDict
+ ] = None,
+ ) -> types.DeleteAgentEngineRuntimeRevisionOperation:
+ parameter_model = types._GetDeleteAgentEngineRuntimeRevisionOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = (
+ _GetDeleteAgentEngineRuntimeRevisionOperationParameters_to_vertex(
+ parameter_model
+ )
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineRuntimeRevisionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _query(
+ self,
+ *,
+ name: str,
+ config: Optional[types.QueryAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.QueryReasoningEngineResponse:
+ """
+ Query an Agent Engine runtime revision.
+ """
+
+ parameter_model = types._QueryAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _QueryAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:query".format_map(request_url_dict)
+ else:
+ path = "{name}:query"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.QueryReasoningEngineResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.AgentEngineRuntimeRevision:
+ """Gets an agent engine runtime revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine runtime revision to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/runtimeRevisions/{runtime_revision_id}`.
+ config (GetAgentEngineRuntimeRevisionConfigOrDict):
+ Optional. Additional configurations for getting the Agent Engine runtime revision.
+
+ Returns:
+ AgentEngineRuntimeRevision: The requested Agent Engine runtime revision instance.
+ """
+ api_resource = self._get(name=name, config=config)
+ agent_engine_runtime_revision = types.AgentEngineRuntimeRevision(
+ api_client=self,
+ api_async_client=AsyncRuntimeRevisions(api_client_=self._api_client),
+ api_resource=api_resource,
+ )
+ if api_resource.spec:
+ self._register_api_methods(
+ agent_engine_runtime_revision=agent_engine_runtime_revision
+ )
+ return agent_engine_runtime_revision
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineRuntimeRevisionsConfigOrDict] = None,
+ ) -> Iterator[types.AgentEngineRuntimeRevision]:
+ """Lists all reasoning engine runtime revision instances matching the given query.
+
+ Args:
+ name (str): Required. The name of the reasoning engine to list runtime revisions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineRuntimeRevisionsConfig):
+ Optional. Additional configurations for listing the reasoning engine runtime revisions.
+
+ Returns:
+ Iterable[AgentEngineRuntimeRevision]: An iterable of runtime revisions.
+ """
+ list_pager: Pager[types.ReasoningEngineRuntimeRevision] = Pager(
+ "reasoning_engine_runtime_revisions",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+ return (
+ types.AgentEngineRuntimeRevision(
+ api_client=self,
+ api_async_client=AsyncRuntimeRevisions(api_client_=self._api_client),
+ api_resource=runtime_revision,
+ )
+ for runtime_revision in list_pager
+ )
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineRuntimeRevisionOperation:
+ """Delete an Agent Engine runtime revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine runtime revision to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/runtimeRevisions/{runtime_revision_id}`.
+ config (DeleteAgentEngineRuntimeRevisionConfig):
+ Optional. Additional configurations for deleting the Agent Engine runtime revision.
+
+ Returns:
+ DeleteAgentEngineRuntimeRevisionOperation: The operation for deleting the Agent Engine runtime revision.
+ """
+ if config is None:
+ config = types.DeleteAgentEngineRuntimeRevisionConfig()
+ elif isinstance(config, dict):
+ config = types.DeleteAgentEngineRuntimeRevisionConfig.model_validate(config)
+ operation = self._delete(
+ name=name,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_delete_runtime_revision_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(
+ f"Failed to delete runtime revision: {operation.error}"
+ )
+ return operation
+
+ def _register_api_methods(
+ self,
+ *,
+ agent_engine_runtime_revision: types.AgentEngineRuntimeRevision,
+ ) -> types.AgentEngineRuntimeRevision:
+ """Registers the API methods for the agent engine runtime revision."""
+ try:
+ _agent_engines_utils._register_api_methods_or_raise(
+ agent_engine=agent_engine_runtime_revision,
+ wrap_operation_fn={
+ "": _agent_engines_utils._wrap_query_operation, # type: ignore[dict-item]
+ "async": _agent_engines_utils._wrap_async_query_operation, # type: ignore[dict-item]
+ "stream": _agent_engines_utils._wrap_stream_query_operation, # type: ignore[dict-item]
+ "async_stream": _agent_engines_utils._wrap_async_stream_query_operation, # type: ignore[dict-item]
+ "a2a_extension": _agent_engines_utils._wrap_a2a_operation,
+ },
+ )
+ except Exception as e:
+ logger.warning(
+ _agent_engines_utils._FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e
+ )
+ return agent_engine_runtime_revision
+
+ def _stream_query(
+ self,
+ *,
+ name: str,
+ config: Optional[types.QueryAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> Iterator[Any]:
+ """Streams the response of the agent engine."""
+ parameter_model = types._QueryAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+ request_dict = _QueryAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:streamQuery?alt=sse".format_map(request_url_dict)
+ else:
+ path = "{name}:streamQuery?alt=sse"
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+ http_options = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+ for response in self._api_client.request_streamed(
+ "post", path, request_dict, http_options
+ ):
+ yield response
+
+ async def _async_stream_query(
+ self,
+ *,
+ name: str,
+ config: Optional[types.QueryAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> AsyncIterator[Any]:
+ """Streams the response of the agent engine."""
+ parameter_model = types._QueryAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+ request_dict = _QueryAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:streamQuery?alt=sse".format_map(request_url_dict)
+ else:
+ path = "{name}:streamQuery?alt=sse"
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+ http_options = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+ async_iterator = await self._api_client.async_request_streamed(
+ "post", path, request_dict, http_options
+ )
+ async for response in async_iterator:
+ yield response
+
+
+class AsyncRuntimeRevisions(_api_module.BaseModule):
+
+ async def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.ReasoningEngineRuntimeRevision:
+ """
+ Get an agent engine runtime revision instance.
+ """
+
+ parameter_model = types._GetAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ReasoningEngineRuntimeRevision._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineRuntimeRevisionsConfigOrDict] = None,
+ ) -> types.ListReasoningEnginesRuntimeRevisionsResponse:
+ """
+ Lists reasoning engine runtime revisions.
+
+ Args:
+ name (str): Required. The name of the reasoning engine to list runtime revisions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineRuntimeRevisionsConfig):
+ Optional. Additional configurations for listing the reasoning engine runtime revisions.
+
+ Returns:
+ ListReasoningEnginesRuntimeRevisionsResponse: The requested reasoning engine runtime revisions.
+
+ """
+
+ parameter_model = types._ListAgentEngineRuntimeRevisionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineRuntimeRevisionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/runtimeRevisions".format_map(request_url_dict)
+ else:
+ path = "{name}/runtimeRevisions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = (
+ types.ListReasoningEnginesRuntimeRevisionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineRuntimeRevisionOperation:
+ """
+ Delete an Agent Engine runtime revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine runtime revision to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/runtimeRevisions/{runtime_revision_id}`.
+ config (DeleteAgentEngineRuntimeRevisionConfig):
+ Optional. Additional configurations for deleting the Agent Engine runtime revision.
+
+ Returns:
+ DeleteAgentEngineRuntimeRevisionOperation: The operation for deleting the Agent Engine runtime revision.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineRuntimeRevisionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_delete_runtime_revision_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[
+ types.GetDeleteAgentEngineRuntimeRevisionOperationConfigOrDict
+ ] = None,
+ ) -> types.DeleteAgentEngineRuntimeRevisionOperation:
+ parameter_model = types._GetDeleteAgentEngineRuntimeRevisionOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = (
+ _GetDeleteAgentEngineRuntimeRevisionOperationParameters_to_vertex(
+ parameter_model
+ )
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineRuntimeRevisionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _query(
+ self,
+ *,
+ name: str,
+ config: Optional[types.QueryAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.QueryReasoningEngineResponse:
+ """
+ Query an Agent Engine runtime revision.
+ """
+
+ parameter_model = types._QueryAgentEngineRuntimeRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _QueryAgentEngineRuntimeRevisionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:query".format_map(request_url_dict)
+ else:
+ path = "{name}:query"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.QueryReasoningEngineResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.AgentEngineRuntimeRevision:
+ """Gets an agent engine runtime revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine runtime revision to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/runtimeRevisions/{runtime_revision_id}`.
+ config (GetAgentEngineRuntimeRevisionConfigOrDict):
+ Optional. Additional configurations for getting the Agent Engine runtime revision.
+
+ Returns:
+ AgentEngineRuntimeRevision: The requested Agent Engine runtime revision instance.
+ """
+ api_resource = await self._get(name=name, config=config)
+ agent_engine_runtime_revision = types.AgentEngineRuntimeRevision(
+ api_client=self,
+ api_async_client=AsyncRuntimeRevisions(api_client_=self._api_client),
+ api_resource=api_resource,
+ )
+ if api_resource.spec:
+ self._register_api_methods(
+ agent_engine_runtime_revision=agent_engine_runtime_revision
+ )
+ return agent_engine_runtime_revision
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineRuntimeRevisionsConfigOrDict] = None,
+ ) -> AsyncIterator[types.AgentEngineRuntimeRevision]:
+ """Lists reasoning engine runtime revisions.
+
+ Args:
+ name (str): Required. The name of the reasoning engine to list runtime revisions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineRuntimeRevisionsConfig):
+ Optional. Additional configurations for listing the reasoning engine runtime revisions.
+
+ Returns:
+ AsyncIterator[AgentEngineRuntimeRevision]: An async iterator of runtime revisions.
+ """
+ list_pager: AsyncPager[types.ReasoningEngineRuntimeRevision] = AsyncPager(
+ "reasoning_engine_runtime_revisions",
+ functools.partial(self._list, name=name),
+ await self._list(name=name, config=config),
+ config,
+ )
+
+ async for runtime_revision in list_pager:
+ yield types.AgentEngineRuntimeRevision(
+ api_client=self,
+ api_async_client=AsyncRuntimeRevisions(api_client_=self._api_client),
+ api_resource=runtime_revision,
+ )
+
+ async def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineRuntimeRevisionOperation:
+ """Delete an Agent Engine runtime revision.
+
+ Args:
+ name (str): Required. The name of the Agent Engine runtime revision to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/runtimeRevisions/{runtime_revision_id}`.
+ config (DeleteAgentEngineRuntimeRevisionConfig):
+ Optional. Additional configurations for deleting the Agent Engine runtime revision.
+
+ Returns:
+ DeleteAgentEngineRuntimeRevisionOperation: The operation for deleting the Agent Engine runtime revision.
+ """
+ if config is None:
+ config = types.DeleteAgentEngineRuntimeRevisionConfig()
+ elif isinstance(config, dict):
+ config = types.DeleteAgentEngineRuntimeRevisionConfig.model_validate(config)
+ operation = await self._delete(
+ name=name,
+ config=config,
+ )
+ if config.wait_for_completion and not operation.done:
+ operation = await _agent_engines_utils._await_async_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_delete_runtime_revision_operation,
+ poll_interval_seconds=0.5,
+ )
+ if operation.error:
+ raise RuntimeError(
+ f"Failed to delete runtime revision: {operation.error}"
+ )
+ return operation
+
+ def _register_api_methods(
+ self,
+ *,
+ agent_engine_runtime_revision: types.AgentEngineRuntimeRevision,
+ ) -> types.AgentEngineRuntimeRevision:
+ """Registers the API methods for the agent engine runtime revision."""
+ try:
+ _agent_engines_utils._register_api_methods_or_raise(
+ agent_engine=agent_engine_runtime_revision,
+ wrap_operation_fn={
+ "": _agent_engines_utils._wrap_query_operation, # type: ignore[dict-item]
+ "async": _agent_engines_utils._wrap_async_query_operation, # type: ignore[dict-item]
+ "stream": _agent_engines_utils._wrap_stream_query_operation, # type: ignore[dict-item]
+ "async_stream": _agent_engines_utils._wrap_async_stream_query_operation, # type: ignore[dict-item]
+ "a2a_extension": _agent_engines_utils._wrap_a2a_operation,
+ },
+ )
+ except Exception as e:
+ logger.warning(
+ _agent_engines_utils._FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e
+ )
+ return agent_engine_runtime_revision
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/runtimes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/runtimes.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f41816bf5216de25fb6464792c6085aa76108f4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/runtimes.py
@@ -0,0 +1,78 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Handwritten placeholder code for the runtimes.py file.
+# Should be replaced by the generated file.
+
+import importlib
+import logging
+import typing
+
+from google.genai import _api_module
+
+
+if typing.TYPE_CHECKING:
+ from . import runtime_revisions as runtime_revisions_module
+
+ _ = runtime_revisions_module
+
+
+logger = logging.getLogger("agentplatform_genai.runtimes")
+
+logger.setLevel(logging.INFO)
+
+
+class Runtimes(_api_module.BaseModule):
+
+ _revisions = None
+
+ @property
+ def revisions(self) -> "runtime_revisions_module.RuntimeRevisions":
+ if self._revisions is None:
+ try:
+ # We need to lazy load the revisions module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._revisions = importlib.import_module(
+ ".runtime_revisions", __package__
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.runtimes.revisions' module requires "
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._revisions.RuntimeRevisions(self._api_client) # type: ignore[no-any-return]
+
+
+class AsyncRuntimes(_api_module.BaseModule):
+
+ _revisions = None
+
+ @property
+ def revisions(self) -> "runtime_revisions_module.AsyncRuntimeRevisions":
+ if self._revisions is None:
+ try:
+ # We need to lazy load the revisions module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._revisions = importlib.import_module(
+ ".runtime_revisions", __package__
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.runtimes.revisions' module requires "
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._revisions.AsyncRuntimeRevisions(self._api_client) # type: ignore[no-any-return]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandbox_snapshots.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandbox_snapshots.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffa7663a47494d704a8c3ca4fa126cb0689822af
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandbox_snapshots.py
@@ -0,0 +1,1019 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import json
+import logging
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import Pager
+
+from . import _agent_engines_utils
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.sandboxsnapshots")
+
+logger.setLevel(logging.INFO)
+
+
+def _CreateAgentEngineSandboxSnapshotConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["owner"]) is not None:
+ setv(parent_object, ["owner"], getv(from_object, ["owner"]))
+
+ if getv(from_object, ["ttl"]) is not None:
+ setv(parent_object, ["ttl"], getv(from_object, ["ttl"]))
+
+ return to_object
+
+
+def _CreateSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["source_sandbox_environment_name"]) is not None:
+ setv(
+ to_object,
+ ["_url", "name"],
+ getv(from_object, ["source_sandbox_environment_name"]),
+ )
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _CreateAgentEngineSandboxSnapshotConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+def _DeleteSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GetAgentEngineSandboxSnapshotOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ListSandboxEnvironmentSnapshotsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListSandboxEnvironmentSnapshotsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListSandboxEnvironmentSnapshotsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class SandboxSnapshots(_api_module.BaseModule):
+ """Sandbox environment snapshot commands."""
+
+ def _create(
+ self,
+ *,
+ source_sandbox_environment_name: str,
+ config: Optional[types.CreateAgentEngineSandboxSnapshotConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxSnapshotOperation:
+ """
+ Snapshots an existing sandbox environment.
+
+ Args:
+ source_sandbox_environment_name (str):
+ Required. The name of the sandbox environment to snapshot.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox_environment_id}
+ config (CreateAgentEngineSandboxSnapshotConfig):
+ Optional. The configuration for the sandbox snapshot.
+
+ """
+
+ parameter_model = types._CreateSandboxEnvironmentSnapshotRequestParameters(
+ source_sandbox_environment_name=source_sandbox_environment_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:snapshot".format_map(request_url_dict)
+ else:
+ path = "{name}:snapshot"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxSnapshotOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSandboxEnvironmentSnapshotConfigOrDict] = None,
+ ) -> types.DeleteSandboxEnvironmentSnapshotOperation:
+ """
+ Deletes a sandbox environment snapshot.
+
+ """
+
+ parameter_model = types._DeleteSandboxEnvironmentSnapshotRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteSandboxEnvironmentSnapshotOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetSandboxEnvironmentSnapshotConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentSnapshot:
+ """
+ Gets a sandbox environment snapshot.
+
+ """
+
+ parameter_model = types._GetSandboxEnvironmentSnapshotRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentSnapshot._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSandboxEnvironmentSnapshotsConfigOrDict] = None,
+ ) -> types.ListSandboxEnvironmentSnapshotsResponse:
+ """
+ Lists sandbox environment snapshots.
+
+ """
+
+ parameter_model = types._ListSandboxEnvironmentSnapshotsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSandboxEnvironmentSnapshotsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironmentSnapshots".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironmentSnapshots"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSandboxEnvironmentSnapshotsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def get_sandbox_snapshot_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxSnapshotOperation:
+ parameter_model = types._GetAgentEngineSandboxSnapshotOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSandboxSnapshotOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxSnapshotOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def create(
+ self,
+ *,
+ source_sandbox_environment_name: str,
+ config: Optional[types.CreateAgentEngineSandboxSnapshotConfigOrDict] = None,
+ poll_interval_seconds: float = 0.1,
+ ) -> types.AgentEngineSandboxSnapshotOperation:
+ """Snapshots an existing sandbox environment.
+
+ Args:
+ source_sandbox_environment_name (str):
+ Required. The name of the sandbox environment to snapshot.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox_environment_id}
+ config (CreateAgentEngineSandboxSnapshotConfig):
+ Optional. The configuration for the sandbox snapshot.
+ poll_interval_seconds (int):
+ Optional. Seconds to wait between polling for operation status. Defaults to 0.1.
+
+ Returns:
+ AgentEngineSandboxSnapshotOperation: The operation for creating the sandbox snapshot.
+ """
+ operation = self._create(
+ source_sandbox_environment_name=source_sandbox_environment_name,
+ config=config,
+ )
+ if config is None:
+ config = types.CreateAgentEngineSandboxSnapshotConfig()
+ elif isinstance(config, dict):
+ config = types.CreateAgentEngineSandboxSnapshotConfig.model_validate(config)
+ if config.wait_for_completion:
+ if not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self.get_sandbox_snapshot_operation,
+ poll_interval_seconds=poll_interval_seconds,
+ )
+ # We need to make a call to get the sandbox snapshot because the operation
+ # response might not contain the relevant fields.
+ if not operation.response:
+ raise ValueError("Error retrieving sandbox snapshot.")
+ operation.response = self.get(name=operation.response.name)
+ return operation
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSandboxEnvironmentSnapshotsConfigOrDict] = None,
+ ) -> Iterator[types.SandboxEnvironmentSnapshot]:
+ """Lists Agent Engine sandbox snapshots.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list sandbox snapshots for.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentSnapshots/{sandbox_snapshot_id}
+ config (ListSandboxEnvironmentSnapshotsConfig):
+ Optional. The configuration for the sandbox snapshots to list.
+
+ Returns:
+ Iterable[SandboxEnvironmentSnapshot]: An iterable of agent engine sandbox snapshots.
+ """
+ return Pager(
+ "sandbox_environment_snapshots",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetSandboxEnvironmentSnapshotConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentSnapshot:
+ """Gets a sandbox snapshot in the Agent Engine.
+ Args:
+ name (str):
+ Required. A fully-qualified resource name or ID such as
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentSnapshots/{snapshot_id}
+ or a shortened name such as "reasoningEngines/{resource_id}/sandboxEnvironmentSnapshots/{snapshot_id}".
+ config (GetSandboxEnvironmentSnapshotConfigOrDict):
+ Optional. The configuration for the sandbox snapshot to get.
+ """
+ return self._get(name=name, config=config)
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSandboxEnvironmentSnapshotConfigOrDict] = None,
+ ) -> types.DeleteSandboxEnvironmentSnapshotOperation:
+ """Deletes a sandbox snapshot in the Agent Engine.
+ Args:
+ name (str):
+ Required. The name of the sandbox snapshot to delete.
+ Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentSnapshots/{snapshot_id}
+ config (DeleteSandboxEnvironmentSnapshotConfigOrDict):
+ Optional. Configuration for the delete operation.
+ """
+ return self._delete(name=name, config=config)
+
+
+class AsyncSandboxSnapshots(_api_module.BaseModule):
+ """Sandbox environment snapshot commands."""
+
+ async def _create(
+ self,
+ *,
+ source_sandbox_environment_name: str,
+ config: Optional[types.CreateAgentEngineSandboxSnapshotConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxSnapshotOperation:
+ """
+ Snapshots an existing sandbox environment.
+
+ Args:
+ source_sandbox_environment_name (str):
+ Required. The name of the sandbox environment to snapshot.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox_environment_id}
+ config (CreateAgentEngineSandboxSnapshotConfig):
+ Optional. The configuration for the sandbox snapshot.
+
+ """
+
+ parameter_model = types._CreateSandboxEnvironmentSnapshotRequestParameters(
+ source_sandbox_environment_name=source_sandbox_environment_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:snapshot".format_map(request_url_dict)
+ else:
+ path = "{name}:snapshot"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxSnapshotOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSandboxEnvironmentSnapshotConfigOrDict] = None,
+ ) -> types.DeleteSandboxEnvironmentSnapshotOperation:
+ """
+ Deletes a sandbox environment snapshot.
+
+ """
+
+ parameter_model = types._DeleteSandboxEnvironmentSnapshotRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteSandboxEnvironmentSnapshotOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetSandboxEnvironmentSnapshotConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentSnapshot:
+ """
+ Gets a sandbox environment snapshot.
+
+ """
+
+ parameter_model = types._GetSandboxEnvironmentSnapshotRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSandboxEnvironmentSnapshotRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentSnapshot._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSandboxEnvironmentSnapshotsConfigOrDict] = None,
+ ) -> types.ListSandboxEnvironmentSnapshotsResponse:
+ """
+ Lists sandbox environment snapshots.
+
+ """
+
+ parameter_model = types._ListSandboxEnvironmentSnapshotsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSandboxEnvironmentSnapshotsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironmentSnapshots".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironmentSnapshots"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSandboxEnvironmentSnapshotsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def get_sandbox_snapshot_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxSnapshotOperation:
+ parameter_model = types._GetAgentEngineSandboxSnapshotOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSandboxSnapshotOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxSnapshotOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandbox_templates.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandbox_templates.py
new file mode 100644
index 0000000000000000000000000000000000000000..60038948385e3efa489b97e243e57cc5c3657137
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandbox_templates.py
@@ -0,0 +1,1088 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import json
+import logging
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import Pager
+
+from . import _agent_engines_utils
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.sandboxtemplates")
+
+logger.setLevel(logging.INFO)
+
+
+def _CreateSandboxEnvironmentTemplateConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["custom_container_environment"]) is not None:
+ setv(
+ parent_object,
+ ["customContainerEnvironment"],
+ getv(from_object, ["custom_container_environment"]),
+ )
+
+ if getv(from_object, ["default_container_environment"]) is not None:
+ setv(
+ parent_object,
+ ["defaultContainerEnvironment"],
+ getv(from_object, ["default_container_environment"]),
+ )
+
+ if getv(from_object, ["egress_control_config"]) is not None:
+ setv(
+ parent_object,
+ ["egressControlConfig"],
+ getv(from_object, ["egress_control_config"]),
+ )
+
+ return to_object
+
+
+def _CreateSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _CreateSandboxEnvironmentTemplateConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ return to_object
+
+
+def _DeleteSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GetSandboxEnvironmentTemplateOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ListSandboxEnvironmentTemplatesConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListSandboxEnvironmentTemplatesRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListSandboxEnvironmentTemplatesConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class SandboxTemplates(_api_module.BaseModule):
+ """Sandbox environment templates commands."""
+
+ def _create(
+ self,
+ *,
+ name: str,
+ config: Optional[types.CreateSandboxEnvironmentTemplateConfigOrDict] = None,
+ display_name: str,
+ ) -> types.SandboxEnvironmentTemplateOperation:
+ """
+ Creates a new sandbox template in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to create the template under.
+ Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}
+ display_name (str):
+ Required. The display name of the sandbox template.
+ config (CreateSandboxEnvironmentTemplateConfig):
+ Optional. The configuration for the sandbox template.
+
+ """
+
+ parameter_model = types._CreateSandboxEnvironmentTemplateRequestParameters(
+ name=name,
+ config=config,
+ display_name=display_name,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironmentTemplates".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironmentTemplates"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentTemplateOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSandboxEnvironmentTemplateConfigOrDict] = None,
+ ) -> types.DeleteSandboxEnvironmentTemplateOperation:
+ """
+ Delete an Agent Engine sandbox template.
+
+ Args:
+ name (str):
+ Required. The name of the sandbox template to delete.
+ Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxTemplates/{sandbox_template}
+ config (DeleteSandboxEnvironmentTemplateConfig):
+ Optional. Configuration for the delete operation.
+
+ """
+
+ parameter_model = types._DeleteSandboxEnvironmentTemplateRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteSandboxEnvironmentTemplateOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetSandboxEnvironmentTemplateConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentTemplate:
+ """
+ Gets an agent engine sandbox template.
+
+ Args:
+ name (str): The resource name of the SandboxEnvironmentTemplate.
+ Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentTemplates/{sandbox_environment_template}`
+ config (GetSandboxEnvironmentTemplateConfig): Configuration for the
+ request.
+
+ Returns:
+ shared.SandboxEnvironmentTemplate: The retrieved sandbox environment
+ template.
+
+ """
+
+ parameter_model = types._GetSandboxEnvironmentTemplateRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentTemplate._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSandboxEnvironmentTemplatesConfigOrDict] = None,
+ ) -> types.ListSandboxEnvironmentTemplatesResponse:
+ """
+ Lists Agent Engine sandbox templates.
+
+ Args:
+ name (str): Name of the agent engine. Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}
+ config (ListSandboxEnvironmentTemplatesConfig): Configuration for listing sandbox templates.
+
+ Returns:
+ ListSandboxEnvironmentTemplatesResponse: A list of sandbox templates.
+
+ """
+
+ parameter_model = types._ListSandboxEnvironmentTemplatesRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSandboxEnvironmentTemplatesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironmentTemplates".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironmentTemplates"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSandboxEnvironmentTemplatesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def get_sandbox_environment_template_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentTemplateOperation:
+ parameter_model = types._GetSandboxEnvironmentTemplateOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSandboxEnvironmentTemplateOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentTemplateOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def create(
+ self,
+ *,
+ name: str,
+ display_name: str,
+ config: Optional[types.CreateSandboxEnvironmentTemplateConfigOrDict] = None,
+ poll_interval_seconds: float = 0.1,
+ ) -> types.SandboxEnvironmentTemplateOperation:
+ """Creates a new sandbox template in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to create sandbox template for.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}
+ display_name (str):
+ Required. The display name of the sandbox template.
+ config (CreateSandboxEnvironmentTemplateConfig):
+ Optional. The configuration for the sandbox template.
+ polling_interval (int):
+ Optional. Seconds to wait between polling for operation status. Defaults to 5.
+
+ Returns:
+ SandboxEnvironmentTemplateOperation: The operation for creating the sandbox template.
+ """
+ operation = self._create(
+ name=name,
+ display_name=display_name,
+ config=config,
+ )
+ if config is None:
+ config = types.CreateSandboxEnvironmentTemplateConfig()
+ elif isinstance(config, dict):
+ config = types.CreateSandboxEnvironmentTemplateConfig.model_validate(config)
+ if config.wait_for_completion:
+ if not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self.get_sandbox_environment_template_operation,
+ poll_interval_seconds=poll_interval_seconds,
+ )
+ # We need to make a call to get the sandbox template because the operation
+ # response might not contain the relevant fields.
+ if not operation.response:
+ raise ValueError("Error retrieving sandbox template.")
+ operation.response = self.get(name=operation.response.name)
+ return operation
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSandboxEnvironmentTemplatesConfigOrDict] = None,
+ ) -> Iterator[types.SandboxEnvironmentTemplate]:
+ """Lists Agent Engine sandbox templates.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list sandbox templates for.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentTemplates/{sandbox_template_id}
+ config (ListSandboxEnvironmentTemplatesConfig):
+ Optional. The configuration for the sandbox templates to list.
+
+ Returns:
+ Iterable[SandboxEnvironmentTemplate]: An iterable of agent engine sandbox templates.
+ """
+ return Pager(
+ "sandbox_environment_templates",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetSandboxEnvironmentTemplateConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentTemplate:
+ """Gets a sandbox template in the Agent Engine.
+ Args:
+ name (str):
+ Required. A fully-qualified resource name or ID such as
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentTemplates/{sandbox_template_id}
+ or a shortened name such as "reasoningEngines/{resource_id}/sandboxEnvironmentTemplates/{sandbox_template_id}".
+ config (GetSandboxEnvironmentTemplateConfigOrDict):
+ Optional. The configuration for the sandbox template to get.
+ """
+ return self._get(name=name, config=config)
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSandboxEnvironmentTemplateConfigOrDict] = None,
+ ) -> types.DeleteSandboxEnvironmentTemplateOperation:
+ """Deletes a sandbox template in the Agent Engine.
+ Args:
+ name (str):
+ Required. The name of the sandbox template to delete.
+ Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentTemplates/{sandbox_template_id}
+ config (DeleteSandboxEnvironmentTemplateConfig):
+ Optional. Configuration for the delete operation.
+ """
+ return self._delete(name=name, config=config)
+
+
+class AsyncSandboxTemplates(_api_module.BaseModule):
+ """Sandbox environment templates commands."""
+
+ async def _create(
+ self,
+ *,
+ name: str,
+ config: Optional[types.CreateSandboxEnvironmentTemplateConfigOrDict] = None,
+ display_name: str,
+ ) -> types.SandboxEnvironmentTemplateOperation:
+ """
+ Creates a new sandbox template in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to create the template under.
+ Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}
+ display_name (str):
+ Required. The display name of the sandbox template.
+ config (CreateSandboxEnvironmentTemplateConfig):
+ Optional. The configuration for the sandbox template.
+
+ """
+
+ parameter_model = types._CreateSandboxEnvironmentTemplateRequestParameters(
+ name=name,
+ config=config,
+ display_name=display_name,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironmentTemplates".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironmentTemplates"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentTemplateOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSandboxEnvironmentTemplateConfigOrDict] = None,
+ ) -> types.DeleteSandboxEnvironmentTemplateOperation:
+ """
+ Delete an Agent Engine sandbox template.
+
+ Args:
+ name (str):
+ Required. The name of the sandbox template to delete.
+ Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxTemplates/{sandbox_template}
+ config (DeleteSandboxEnvironmentTemplateConfig):
+ Optional. Configuration for the delete operation.
+
+ """
+
+ parameter_model = types._DeleteSandboxEnvironmentTemplateRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteSandboxEnvironmentTemplateOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetSandboxEnvironmentTemplateConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentTemplate:
+ """
+ Gets an agent engine sandbox template.
+
+ Args:
+ name (str): The resource name of the SandboxEnvironmentTemplate.
+ Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironmentTemplates/{sandbox_environment_template}`
+ config (GetSandboxEnvironmentTemplateConfig): Configuration for the
+ request.
+
+ Returns:
+ shared.SandboxEnvironmentTemplate: The retrieved sandbox environment
+ template.
+
+ """
+
+ parameter_model = types._GetSandboxEnvironmentTemplateRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSandboxEnvironmentTemplateRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentTemplate._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSandboxEnvironmentTemplatesConfigOrDict] = None,
+ ) -> types.ListSandboxEnvironmentTemplatesResponse:
+ """
+ Lists Agent Engine sandbox templates.
+
+ Args:
+ name (str): Name of the agent engine. Format: projects/{project}/locations/{location}/reasoningEngines/{resource_id}
+ config (ListSandboxEnvironmentTemplatesConfig): Configuration for listing sandbox templates.
+
+ Returns:
+ ListSandboxEnvironmentTemplatesResponse: A list of sandbox templates.
+
+ """
+
+ parameter_model = types._ListSandboxEnvironmentTemplatesRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSandboxEnvironmentTemplatesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironmentTemplates".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironmentTemplates"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSandboxEnvironmentTemplatesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def get_sandbox_environment_template_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.SandboxEnvironmentTemplateOperation:
+ parameter_model = types._GetSandboxEnvironmentTemplateOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSandboxEnvironmentTemplateOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironmentTemplateOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandboxes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandboxes.py
new file mode 100644
index 0000000000000000000000000000000000000000..80e3683a99348966b54a14a8a49a057e367b1562
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sandboxes.py
@@ -0,0 +1,1509 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import json
+import logging
+import mimetypes
+import secrets
+import time
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google import genai
+from google.cloud import iam_credentials_v1 # type: ignore[attr-defined]
+from google.genai import _api_module
+from google.genai import _common
+from google.genai import types as genai_types
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import Pager
+
+from . import _agent_engines_utils
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.sandboxes")
+
+logger.setLevel(logging.INFO)
+
+
+def _CreateAgentEngineSandboxConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["ttl"]) is not None:
+ setv(parent_object, ["ttl"], getv(from_object, ["ttl"]))
+
+ if getv(from_object, ["sandbox_environment_template"]) is not None:
+ setv(
+ parent_object,
+ ["sandboxEnvironmentTemplate"],
+ getv(from_object, ["sandbox_environment_template"]),
+ )
+
+ if getv(from_object, ["sandbox_environment_snapshot"]) is not None:
+ setv(
+ parent_object,
+ ["sandboxEnvironmentSnapshot"],
+ getv(from_object, ["sandbox_environment_snapshot"]),
+ )
+
+ if getv(from_object, ["owner"]) is not None:
+ setv(parent_object, ["owner"], getv(from_object, ["owner"]))
+
+ return to_object
+
+
+def _CreateAgentEngineSandboxRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["spec"]) is not None:
+ setv(to_object, ["spec"], getv(from_object, ["spec"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _CreateAgentEngineSandboxConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+def _DeleteAgentEngineSandboxRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ExecuteCodeAgentEngineSandboxRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["inputs"]) is not None:
+ setv(to_object, ["inputs"], [item for item in getv(from_object, ["inputs"])])
+
+ return to_object
+
+
+def _GetAgentEngineSandboxOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetAgentEngineSandboxRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ListAgentEngineSandboxesConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListAgentEngineSandboxesRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineSandboxesConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class Sandboxes(_api_module.BaseModule):
+
+ def _create(
+ self,
+ *,
+ name: str,
+ spec: Optional[types.SandboxEnvironmentSpecOrDict] = None,
+ config: Optional[types.CreateAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxOperation:
+ """
+ Creates a new sandbox in the Agent Engine.
+ """
+
+ parameter_model = types._CreateAgentEngineSandboxRequestParameters(
+ name=name,
+ spec=spec,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironments"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineSandboxOperation:
+ """
+ Delete an Agent Engine sandbox.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine sandbox to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox}`.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineSandboxRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineSandboxOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _execute_code(
+ self,
+ *,
+ name: str,
+ inputs: Optional[list[types.ChunkOrDict]] = None,
+ config: Optional[types.ExecuteCodeAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.ExecuteSandboxEnvironmentResponse:
+ """
+ Execute code in an Agent Engine sandbox.
+ """
+
+ parameter_model = types._ExecuteCodeAgentEngineSandboxRequestParameters(
+ name=name,
+ inputs=inputs,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ExecuteCodeAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/:execute".format_map(request_url_dict)
+ else:
+ path = "{name}/:execute"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ExecuteSandboxEnvironmentResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.SandboxEnvironment:
+ """
+ Gets an agent engine sandbox.
+
+ Args:
+ name (str): Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456/sandboxEnvironments/789"
+ or a shortened name such as "reasoningEngines/456/sandboxEnvironments/789".
+
+ """
+
+ parameter_model = types._GetAgentEngineSandboxRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironment._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSandboxesConfigOrDict] = None,
+ ) -> types.ListAgentEngineSandboxesResponse:
+ """
+ Lists Agent Engine sandboxes.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to list sessions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineSandboxesConfig):
+ Optional. Additional configurations for listing the Agent Engine sandboxes.
+
+ Returns:
+ ListReasoningEnginesSandboxesResponse: The requested Agent Engine sandboxes.
+
+ """
+
+ parameter_model = types._ListAgentEngineSandboxesRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineSandboxesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironments"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineSandboxesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_sandbox_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxOperation:
+ parameter_model = types._GetAgentEngineSandboxOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSandboxOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _templates = None
+ _snapshots = None
+
+ @property
+ def templates(self) -> Any:
+ if self._templates is None:
+ try:
+ self._templates = __import__("importlib").import_module(
+ ".sandbox_templates", __package__
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.sandboxes.templates' module requires "
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._templates.SandboxTemplates(self._api_client)
+
+ @property
+ def snapshots(self) -> Any:
+ if self._snapshots is None:
+ try:
+ self._snapshots = __import__("importlib").import_module(
+ ".sandbox_snapshots", __package__
+ )
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.sandboxes.snapshots' module requires "
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[sandbox_snapshots]"
+ ) from e
+ return self._snapshots.SandboxSnapshots(self._api_client)
+
+ def create(
+ self,
+ *,
+ name: str,
+ poll_interval_seconds: float = 0.1,
+ spec: Optional[types.SandboxEnvironmentSpecOrDict] = None,
+ config: Optional[types.CreateAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxOperation:
+ """Creates a new sandbox in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to create sandbox for.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}
+ poll_interval_seconds (float):
+ Optional. The interval in seconds to poll for sandbox creation
+ completion.
+ spec (SandboxEnvironmentSpec):
+ Optional. The specification for the sandbox to create.
+ config (CreateAgentEngineSandboxConfigOrDict):
+ Optional. The configuration for the sandbox.
+
+ Returns:
+ AgentEngineSandboxOperation: The operation for creating the sandbox.
+ """
+ if spec:
+ computer_use = False
+ if isinstance(spec, dict):
+ computer_use = spec.get("computer_use_environment") is not None
+ elif hasattr(spec, "computer_use_environment"):
+ computer_use = True
+
+ if computer_use:
+ logging.warning(
+ "The computer_use_environment feature in the sandboxes module is experimental and may change in future versions."
+ )
+ operation = self._create(
+ name=name,
+ spec=spec,
+ config=config,
+ )
+ if config is None:
+ config = types.CreateAgentEngineSandboxConfig()
+ elif isinstance(config, dict):
+ config = types.CreateAgentEngineSandboxConfig.model_validate(config)
+ if config.wait_for_completion:
+ if not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_sandbox_operation,
+ poll_interval_seconds=poll_interval_seconds,
+ )
+ # We need to make a call to get the sandbox because the operation
+ # response might not contain the relevant fields.
+ if not operation.response:
+ raise ValueError("Error retrieving sandbox.")
+ operation.response = self.get(name=operation.response.name)
+ return operation
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSandboxesConfigOrDict] = None,
+ ) -> Iterator[types.SandboxEnvironment]:
+ """Lists Agent Engine sandboxes.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to list sandboxes for.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/SandboxEnvironments/{sandbox_id}
+ config (ListAgentEngineSandboxConfig):
+ Optional. The configuration for the sandboxes to list.
+
+ Returns:
+ Iterable[SandboxEnvironment]: An iterable of agent engine sandboxes.
+ """
+ return Pager(
+ "sandbox_environments",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+ def execute_code(
+ self,
+ *,
+ name: str,
+ input_data: dict[str, Any],
+ config: Optional[types.ExecuteCodeAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.ExecuteSandboxEnvironmentResponse:
+ """Executes code in the Agent Engine sandbox.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine sandbox to run code in.
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/SandboxEnvironments/{sandbox_id}
+ input_data (dict[str, Any]):
+ Required. The input to the code to execute.
+ config (ExecuteCodeAgentEngineSandboxConfigOrDict):
+ Optional. The configuration for the sandboxes to run code in.
+
+ Returns:
+ ExecuteSandboxEnvironmentResponse: The response from executing the code.
+ """
+ input_chunks = []
+
+ if input_data.get("code") is not None:
+ code = input_data.get("code", "")
+ json_code = json.dumps({"code": code}).encode("utf-8")
+ input_chunks.append(
+ types.Chunk(
+ mime_type="application/json",
+ data=json_code,
+ )
+ )
+
+ for file in input_data.get("files", []):
+ file_name = file.get("name", "")
+ input_chunks.append(
+ types.Chunk(
+ mime_type=file.get("mimeType", ""),
+ data=file.get("content", b""),
+ metadata={"attributes": {"file_name": file_name.encode("utf-8")}},
+ )
+ )
+
+ response = self._execute_code(
+ name=name,
+ inputs=input_chunks,
+ config=config,
+ )
+
+ output_chunks = []
+ if response.outputs is not None:
+ for output in response.outputs:
+ if output.mime_type is None:
+ # if mime_type is not available, try to guess the mime_type from the file_name.
+ if (
+ output.metadata is not None
+ and output.metadata.attributes is not None
+ ):
+ file_name = output.metadata.attributes.get(
+ "file_name", b""
+ ).decode("utf-8")
+ mime_type, _ = mimetypes.guess_type(file_name)
+ output.mime_type = mime_type
+ output_chunks.append(output)
+
+ response = types.ExecuteSandboxEnvironmentResponse(outputs=output_chunks)
+
+ return response
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.SandboxEnvironment:
+ """Gets an agent engine sandbox.
+ Args:
+ name (str):
+ Required. A fully-qualified resource name or ID such as
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/SandboxEnvironments/{sandbox_id}
+ or a shortened name such as "reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox_id}".
+ config (GetAgentEngineSandboxConfigOrDict):
+ Optional. The configuration for the sandbox to get.
+
+ """
+ return self._get(name=name, config=config)
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineSandboxOperation:
+ """Deletes an agent engine sandbox.
+ Args:
+ name (str):
+ Required. A fully-qualified resource name or ID such as
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/SandboxEnvironments/{sandbox_id}
+ or a shortened name such as "reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox_id}".
+ config (DeleteAgentEngineSandboxConfigOrDict):
+ Optional. The configuration for the sandbox to delete.
+ """
+ return self._delete(name=name, config=config)
+
+ def generate_access_token(
+ self,
+ service_account_email: str,
+ timeout: int = 3600,
+ ) -> str:
+ """Signs a JWT with a Google Cloud service account.
+
+ Args:
+ service_account_email (str):
+ Required. The email of the service account to use for signing.
+ timeout (int):
+ Optional. The timeout in seconds for the token. Defaults to 3600.
+
+ Returns:
+ str: The signed JWT.
+ """
+ client = iam_credentials_v1.IAMCredentialsClient()
+ name = f"projects/-/serviceAccounts/{service_account_email}"
+ payload = {
+ "iat": int(time.time()),
+ "exp": int(time.time()) + timeout,
+ "iss": service_account_email,
+ "sub": service_account_email,
+ "nonce": secrets.randbelow(1000000000) + 1,
+ "aud": "https://aiplatform.googleapis.com/", # default audience for sandbox proxy
+ }
+ request = iam_credentials_v1.SignJwtRequest(
+ name=name,
+ payload=json.dumps(payload),
+ )
+ response = client.sign_jwt(request=request)
+ return response.signed_jwt # type: ignore[no-any-return]
+
+ def send_command(
+ self,
+ *,
+ http_method: str,
+ access_token: str,
+ sandbox_environment: types.SandboxEnvironment,
+ port: str = "8080",
+ path: Optional[str] = None,
+ query_params: Optional[dict[str, object]] = None,
+ headers: Optional[dict[str, str]] = None,
+ request_dict: Optional[dict[str, object]] = None,
+ ) -> genai_types.HttpResponse:
+ """Sends a command to the sandbox.
+
+ Args:
+ http_method (str):
+ Required. The HTTP method to use for the command.
+ access_token (str):
+ Required. The access token to use for authorization.
+ sandbox_environment (types.SandboxEnvironment):
+ Required. The sandbox environment to send the command to.
+ port (str):
+ Optional. The port to use for the token. Defaults to "8080". This should be one of the ports specified during template creation.
+ path (str):
+ Optional. The path to send the command to.
+ query_params (dict[str, object]):
+ Optional. The query parameters to include in the command.
+ headers (dict[str, str]):
+ Optional. The headers to include in the command.
+ request_dict (dict[str, object]):
+ Optional. The request body to include in the command.
+
+ Returns:
+ genai_types.HttpResponse: The response from the sandbox.
+ """
+ headers = headers or {}
+ request_dict = request_dict or {}
+ connection_info = sandbox_environment.connection_info
+ if not connection_info:
+ raise ValueError("Connection info is not available.")
+ if connection_info.load_balancer_hostname:
+ endpoint = "https://" + connection_info.load_balancer_hostname
+ elif connection_info.load_balancer_ip:
+ endpoint = "http://" + connection_info.load_balancer_ip
+ else:
+ raise ValueError("Load balancer hostname or ip is not available.")
+
+ routing_token = connection_info.routing_token
+ if not routing_token:
+ raise ValueError("Routing token is not available.")
+
+ path = path or ""
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ headers["Authorization"] = f"Bearer {access_token}"
+ headers["X-Sandbox-Routing-Token"] = routing_token
+ headers["X-Sandbox-Port"] = port
+ endpoint = endpoint + path if path.startswith("/") else endpoint + "/" + path
+ http_options = genai_types.HttpOptions(headers=headers, base_url=endpoint)
+ http_client = genai.Client(vertexai=True, http_options=http_options)
+ # Full path is constructed in this function. The passed in path into request
+ # function will not be used.
+ response = http_client._api_client.request(http_method, path, request_dict)
+ return genai_types.HttpResponse(
+ headers=response.headers,
+ body=response.body,
+ )
+
+ def generate_browser_ws_headers(
+ self,
+ sandbox_environment: types.SandboxEnvironment,
+ service_account_email: str,
+ port: str = "8080",
+ timeout: int = 3600,
+ ) -> tuple[str, dict[str, str]]:
+ """Generates the websocket upgrade headers for the browser.
+
+ Args:
+ sandbox_environment (types.SandboxEnvironment):
+ Required. The sandbox environment to generate websocket headers for.
+ service_account_email (str):
+ Required. The email of the service account to use for signing.
+ port (str):
+ Optional. The port to use for the CDP websocket endpoint url fetching.
+ Defaults to "8080". This should be one of the ports specified during template creation.
+ timeout (int):
+ Optional. The timeout in seconds for the token. Defaults to 3600.
+ Returns:
+ tuple[str, dict[str, str]]: A tuple containing the websocket URL and
+ the headers for websocket upgrade.
+ """
+ if not sandbox_environment.connection_info:
+ raise ValueError("Connection info is not available.")
+
+ connection_info = sandbox_environment.connection_info
+ if connection_info.load_balancer_hostname:
+ ws_base_url = "wss://" + connection_info.load_balancer_hostname
+ elif connection_info.load_balancer_ip:
+ ws_base_url = "ws://" + connection_info.load_balancer_ip
+ else:
+ raise ValueError("Load balancer hostname or ip is not available.")
+
+ http_access_token = self.generate_access_token(service_account_email, timeout)
+ response = self.send_command(
+ http_method="GET",
+ access_token=http_access_token,
+ sandbox_environment=sandbox_environment,
+ port=port,
+ path="/cdp_ws_endpoint",
+ )
+ if not response:
+ raise ValueError("Failed to get the websocket endpoint.")
+ body_dict = json.loads(response.body)
+ ws_path = body_dict["endpoint"]
+ ws_url = ws_base_url + "/" + ws_path
+
+ # port 9222 is the default port for the browser websocket endpoint.
+ ws_access_token = self.generate_access_token(service_account_email, timeout)
+
+ routing_token = connection_info.routing_token
+
+ headers = {}
+ headers["Sec-WebSocket-Protocol"] = (
+ f"v1.stream, {ws_access_token}, {routing_token}, 9222"
+ )
+ return ws_url, headers
+
+
+class AsyncSandboxes(_api_module.BaseModule):
+
+ async def _create(
+ self,
+ *,
+ name: str,
+ spec: Optional[types.SandboxEnvironmentSpecOrDict] = None,
+ config: Optional[types.CreateAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxOperation:
+ """
+ Creates a new sandbox in the Agent Engine.
+ """
+
+ parameter_model = types._CreateAgentEngineSandboxRequestParameters(
+ name=name,
+ spec=spec,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironments"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineSandboxOperation:
+ """
+ Delete an Agent Engine sandbox.
+
+ Args:
+ name (str):
+ Required. The name of the Agent Engine sandbox to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox}`.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineSandboxRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineSandboxOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _execute_code(
+ self,
+ *,
+ name: str,
+ inputs: Optional[list[types.ChunkOrDict]] = None,
+ config: Optional[types.ExecuteCodeAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.ExecuteSandboxEnvironmentResponse:
+ """
+ Execute code in an Agent Engine sandbox.
+ """
+
+ parameter_model = types._ExecuteCodeAgentEngineSandboxRequestParameters(
+ name=name,
+ inputs=inputs,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ExecuteCodeAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/:execute".format_map(request_url_dict)
+ else:
+ path = "{name}/:execute"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ExecuteSandboxEnvironmentResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineSandboxConfigOrDict] = None,
+ ) -> types.SandboxEnvironment:
+ """
+ Gets an agent engine sandbox.
+
+ Args:
+ name (str): Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456/sandboxEnvironments/789"
+ or a shortened name such as "reasoningEngines/456/sandboxEnvironments/789".
+
+ """
+
+ parameter_model = types._GetAgentEngineSandboxRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSandboxRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SandboxEnvironment._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSandboxesConfigOrDict] = None,
+ ) -> types.ListAgentEngineSandboxesResponse:
+ """
+ Lists Agent Engine sandboxes.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to list sessions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineSandboxesConfig):
+ Optional. Additional configurations for listing the Agent Engine sandboxes.
+
+ Returns:
+ ListReasoningEnginesSandboxesResponse: The requested Agent Engine sandboxes.
+
+ """
+
+ parameter_model = types._ListAgentEngineSandboxesRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineSandboxesRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
+ else:
+ path = "{name}/sandboxEnvironments"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineSandboxesResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_sandbox_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineSandboxOperation:
+ parameter_model = types._GetAgentEngineSandboxOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSandboxOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSandboxOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/session_events.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/session_events.py
new file mode 100644
index 0000000000000000000000000000000000000000..9333f295497919a1b9c32c3057c82d2a83f9313f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/session_events.py
@@ -0,0 +1,543 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import datetime
+import functools
+import json
+import logging
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.sessionevents")
+
+logger.setLevel(logging.INFO)
+
+
+def _AppendAgentEngineSessionEventConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["content"]) is not None:
+ setv(parent_object, ["content"], getv(from_object, ["content"]))
+
+ if getv(from_object, ["actions"]) is not None:
+ setv(parent_object, ["actions"], getv(from_object, ["actions"]))
+
+ if getv(from_object, ["error_code"]) is not None:
+ setv(parent_object, ["errorCode"], getv(from_object, ["error_code"]))
+
+ if getv(from_object, ["error_message"]) is not None:
+ setv(parent_object, ["errorMessage"], getv(from_object, ["error_message"]))
+
+ if getv(from_object, ["event_metadata"]) is not None:
+ setv(parent_object, ["eventMetadata"], getv(from_object, ["event_metadata"]))
+
+ if getv(from_object, ["raw_event"]) is not None:
+ setv(parent_object, ["rawEvent"], getv(from_object, ["raw_event"]))
+
+ return to_object
+
+
+def _AppendAgentEngineSessionEventRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["author"]) is not None:
+ setv(to_object, ["author"], getv(from_object, ["author"]))
+
+ if getv(from_object, ["invocation_id"]) is not None:
+ setv(to_object, ["invocationId"], getv(from_object, ["invocation_id"]))
+
+ if getv(from_object, ["timestamp"]) is not None:
+ setv(to_object, ["timestamp"], getv(from_object, ["timestamp"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _AppendAgentEngineSessionEventConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+def _ListAgentEngineSessionEventsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListAgentEngineSessionEventsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineSessionEventsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class SessionEvents(_api_module.BaseModule):
+
+ def append(
+ self,
+ *,
+ name: str,
+ author: str,
+ invocation_id: str,
+ timestamp: datetime.datetime,
+ config: Optional[types.AppendAgentEngineSessionEventConfigOrDict] = None,
+ ) -> types.AppendAgentEngineSessionEventResponse:
+ """
+ Appends Agent Engine session event.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to append the event to. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ author (str): Required. The author of the Agent Engine session event.
+ invocation_id (str): Required. The invocation ID of the Agent Engine session event.
+ timestamp (datetime.datetime): Required. The timestamp of the Agent Engine session event.
+ config (AppendAgentEngineSessionEventConfig):
+ Optional. Additional configurations for appending the Agent Engine session event.
+
+ Returns:
+ AppendAgentEngineSessionEventResponse: The requested Agent Engine session event.
+
+ """
+
+ parameter_model = types._AppendAgentEngineSessionEventRequestParameters(
+ name=name,
+ author=author,
+ invocation_id=invocation_id,
+ timestamp=timestamp,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AppendAgentEngineSessionEventRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:appendEvent".format_map(request_url_dict)
+ else:
+ path = "{name}:appendEvent"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AppendAgentEngineSessionEventResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionEventsConfigOrDict] = None,
+ ) -> types.ListAgentEngineSessionEventsResponse:
+ """
+ Lists Agent Engine session events.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to list events for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (ListAgentEngineSessionEventsConfig):
+ Optional. Additional configurations for listing the Agent Engine session events.
+
+ Returns:
+ ListAgentEngineSessionEventsResponse: The requested Agent Engine session events.
+
+ """
+
+ parameter_model = types._ListAgentEngineSessionEventsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineSessionEventsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/events".format_map(request_url_dict)
+ else:
+ path = "{name}/events"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineSessionEventsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionEventsConfigOrDict] = None,
+ ) -> Iterator[types.SessionEvent]:
+ """Lists Agent Engine session events.
+
+ Args:
+ name (str): Required. The name of the agent engine to list session
+ events for.
+ config (ListAgentEngineSessionEventsConfig): Optional. The configuration
+ for the session events to list. Currently, the `filter` field in
+ `config` only supports filtering by `timestamp`. The timestamp
+ value must be enclosed in double quotes and include the time zone
+ information. For example:
+ `config={'filter': 'timestamp>="2025-08-07T19:44:38.4Z"'}`.
+
+ Returns:
+ Iterator[SessionEvent]: An iterable of session events.
+ """
+
+ return Pager(
+ "session_events",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+
+class AsyncSessionEvents(_api_module.BaseModule):
+
+ async def append(
+ self,
+ *,
+ name: str,
+ author: str,
+ invocation_id: str,
+ timestamp: datetime.datetime,
+ config: Optional[types.AppendAgentEngineSessionEventConfigOrDict] = None,
+ ) -> types.AppendAgentEngineSessionEventResponse:
+ """
+ Appends Agent Engine session event.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to append the event to. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ author (str): Required. The author of the Agent Engine session event.
+ invocation_id (str): Required. The invocation ID of the Agent Engine session event.
+ timestamp (datetime.datetime): Required. The timestamp of the Agent Engine session event.
+ config (AppendAgentEngineSessionEventConfig):
+ Optional. Additional configurations for appending the Agent Engine session event.
+
+ Returns:
+ AppendAgentEngineSessionEventResponse: The requested Agent Engine session event.
+
+ """
+
+ parameter_model = types._AppendAgentEngineSessionEventRequestParameters(
+ name=name,
+ author=author,
+ invocation_id=invocation_id,
+ timestamp=timestamp,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _AppendAgentEngineSessionEventRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}:appendEvent".format_map(request_url_dict)
+ else:
+ path = "{name}:appendEvent"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AppendAgentEngineSessionEventResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionEventsConfigOrDict] = None,
+ ) -> types.ListAgentEngineSessionEventsResponse:
+ """
+ Lists Agent Engine session events.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to list events for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (ListAgentEngineSessionEventsConfig):
+ Optional. Additional configurations for listing the Agent Engine session events.
+
+ Returns:
+ ListAgentEngineSessionEventsResponse: The requested Agent Engine session events.
+
+ """
+
+ parameter_model = types._ListAgentEngineSessionEventsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineSessionEventsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/events".format_map(request_url_dict)
+ else:
+ path = "{name}/events"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListAgentEngineSessionEventsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionEventsConfigOrDict] = None,
+ ) -> AsyncPager[types.SessionEvent]:
+ """Lists Agent Engine session events.
+
+ Args:
+ name (str): Required. The name of the agent engine to list session
+ events for.
+ config (ListAgentEngineSessionEventsConfig): Optional. The configuration
+ for the session events to list. Currently, the `filter` field in
+ `config` only supports filtering by `timestamp`. The timestamp
+ value must be enclosed in double quotes and include the time zone
+ information. For example:
+ `config={'filter': 'timestamp>="2025-08-07T19:44:38.4Z"'}`.
+
+ Returns:
+ AsyncPager[SessionEvent]: An async pager of session events.
+ """
+
+ return AsyncPager(
+ "session_events",
+ functools.partial(self._list, name=name),
+ await self._list(name=name, config=config),
+ config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sessions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sessions.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcd486249443a091e4e3797209c02a42fb197c47
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/sessions.py
@@ -0,0 +1,1395 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import functools
+import importlib
+import json
+import logging
+import typing
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import _agent_engines_utils
+from . import types
+
+if typing.TYPE_CHECKING:
+ from . import session_events as session_events_module
+
+ _ = session_events_module
+
+
+logger = logging.getLogger("agentplatform_genai.sessions")
+
+logger.setLevel(logging.INFO)
+
+
+def _CreateAgentEngineSessionConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["session_state"]) is not None:
+ setv(parent_object, ["sessionState"], getv(from_object, ["session_state"]))
+
+ if getv(from_object, ["ttl"]) is not None:
+ setv(parent_object, ["ttl"], getv(from_object, ["ttl"]))
+
+ if getv(from_object, ["expire_time"]) is not None:
+ setv(parent_object, ["expireTime"], getv(from_object, ["expire_time"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(parent_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["session_id"]) is not None:
+ setv(parent_object, ["_query", "sessionId"], getv(from_object, ["session_id"]))
+
+ return to_object
+
+
+def _CreateAgentEngineSessionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["user_id"]) is not None:
+ setv(to_object, ["userId"], getv(from_object, ["user_id"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _CreateAgentEngineSessionConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+def _DeleteAgentEngineSessionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GetAgentEngineSessionOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetAgentEngineSessionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _ListAgentEngineSessionsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListAgentEngineSessionsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _ListAgentEngineSessionsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+def _UpdateAgentEngineSessionConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["session_state"]) is not None:
+ setv(parent_object, ["sessionState"], getv(from_object, ["session_state"]))
+
+ if getv(from_object, ["ttl"]) is not None:
+ setv(parent_object, ["ttl"], getv(from_object, ["ttl"]))
+
+ if getv(from_object, ["expire_time"]) is not None:
+ setv(parent_object, ["expireTime"], getv(from_object, ["expire_time"]))
+
+ if getv(from_object, ["labels"]) is not None:
+ setv(parent_object, ["labels"], getv(from_object, ["labels"]))
+
+ if getv(from_object, ["session_id"]) is not None:
+ setv(parent_object, ["_query", "sessionId"], getv(from_object, ["session_id"]))
+
+ if getv(from_object, ["update_mask"]) is not None:
+ setv(
+ parent_object, ["_query", "updateMask"], getv(from_object, ["update_mask"])
+ )
+
+ if getv(from_object, ["user_id"]) is not None:
+ setv(parent_object, ["userId"], getv(from_object, ["user_id"]))
+
+ return to_object
+
+
+def _UpdateAgentEngineSessionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _UpdateAgentEngineSessionConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ )
+
+ return to_object
+
+
+class Sessions(_api_module.BaseModule):
+
+ def _create(
+ self,
+ *,
+ name: str,
+ user_id: str,
+ config: Optional[types.CreateAgentEngineSessionConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ """
+ Creates a new session in the Agent Engine.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to create the session under. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ user_id (str): Required. The user ID of the session.
+ config (CreateAgentEngineSessionConfig):
+ Optional. Additional configurations for creating the Agent Engine session.
+
+ Returns:
+ AgentEngineSessionOperation: The operation for creating the Agent Engine session.
+
+ """
+
+ parameter_model = types._CreateAgentEngineSessionRequestParameters(
+ name=name,
+ user_id=user_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sessions".format_map(request_url_dict)
+ else:
+ path = "{name}/sessions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineSessionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineSessionOperation:
+ """
+ Delete an Agent Engine session.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (DeleteAgentEngineSessionConfig):
+ Optional. Additional configurations for deleting the Agent Engine session.
+
+ Returns:
+ DeleteAgentEngineSessionOperation: The operation for deleting the Agent Engine session.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineSessionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineSessionConfigOrDict] = None,
+ ) -> types.Session:
+ """
+ Gets an agent engine session.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (GetAgentEngineSessionConfig):
+ Optional. Additional configurations for getting the Agent Engine session.
+
+ Returns:
+ AgentEngineSession: The requested Agent Engine session.
+
+ """
+
+ parameter_model = types._GetAgentEngineSessionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Session._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionsConfigOrDict] = None,
+ ) -> types.ListReasoningEnginesSessionsResponse:
+ """
+ Lists Agent Engine sessions.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to list sessions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineSessionsConfig):
+ Optional. Additional configurations for listing the Agent Engine sessions.
+
+ Returns:
+ ListReasoningEnginesSessionsResponse: The requested Agent Engine sessions.
+
+ """
+
+ parameter_model = types._ListAgentEngineSessionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineSessionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sessions".format_map(request_url_dict)
+ else:
+ path = "{name}/sessions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListReasoningEnginesSessionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_session_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ parameter_model = types._GetAgentEngineSessionOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSessionOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _update(
+ self,
+ *,
+ name: str,
+ config: Optional[types.UpdateAgentEngineSessionConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ """
+ Updates an Agent Engine session.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to be updated. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (UpdateAgentEngineSessionConfig):
+ Optional. Additional configurations for updating the Agent Engine session.
+
+ Returns:
+ AgentEngineSessionOperation: The operation for updating the Agent Engine session.
+
+ """
+
+ parameter_model = types._UpdateAgentEngineSessionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("patch", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _events = None
+
+ @property
+ def events(self) -> "session_events_module.SessionEvents":
+ if self._events is None:
+ try:
+ # We need to lazy load the sessions.events module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._events = importlib.import_module(".session_events", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.sessions.events' module requires"
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._events.SessionEvents(self._api_client) # type: ignore[no-any-return]
+
+ def create(
+ self,
+ *,
+ name: str,
+ user_id: str,
+ config: Optional[types.CreateAgentEngineSessionConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ """Creates a new session in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to create the session for.
+ user_id (str):
+ Required. The user ID of the session.
+ config (CreateAgentEngineSessionConfig):
+ Optional. The configuration for the session to create.
+
+ Returns:
+ AgentEngineSessionOperation: The operation for creating the session.
+ """
+ if config is None:
+ config = types.CreateAgentEngineSessionConfig()
+ elif isinstance(config, dict):
+ config = types.CreateAgentEngineSessionConfig.model_validate(config)
+ operation = self._create(
+ name=name,
+ user_id=user_id,
+ config=config,
+ )
+ if config.wait_for_completion:
+ if not operation.done:
+ operation = _agent_engines_utils._await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_session_operation,
+ poll_interval_seconds=0.5,
+ )
+ # We need to make a call to get the session because the operation
+ # response might not contain the relevant fields.
+ if operation.response:
+ operation.response = self.get(name=operation.response.name)
+ elif operation.error:
+ raise RuntimeError(f"Failed to create session: {operation.error}")
+ else:
+ raise RuntimeError(
+ "Error retrieving session from the operation response. "
+ f"Operation name: {operation.name}"
+ )
+ return operation
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionsConfigOrDict] = None,
+ ) -> Iterator[types.Session]:
+ """Lists Agent Engine sessions.
+
+ Args:
+ name (str): Required. The name of the agent engine to list sessions
+ for.
+ config (ListAgentEngineSessionConfig): Optional. The configuration
+ for the sessions to list.
+
+ Returns:
+ Iterable[Session]: An iterable of sessions.
+ """
+
+ return Pager(
+ "sessions",
+ functools.partial(self._list, name=name),
+ self._list(name=name, config=config),
+ config,
+ )
+
+
+class AsyncSessions(_api_module.BaseModule):
+
+ async def _create(
+ self,
+ *,
+ name: str,
+ user_id: str,
+ config: Optional[types.CreateAgentEngineSessionConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ """
+ Creates a new session in the Agent Engine.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to create the session under. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ user_id (str): Required. The user ID of the session.
+ config (CreateAgentEngineSessionConfig):
+ Optional. Additional configurations for creating the Agent Engine session.
+
+ Returns:
+ AgentEngineSessionOperation: The operation for creating the Agent Engine session.
+
+ """
+
+ parameter_model = types._CreateAgentEngineSessionRequestParameters(
+ name=name,
+ user_id=user_id,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sessions".format_map(request_url_dict)
+ else:
+ path = "{name}/sessions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteAgentEngineSessionConfigOrDict] = None,
+ ) -> types.DeleteAgentEngineSessionOperation:
+ """
+ Delete an Agent Engine session.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (DeleteAgentEngineSessionConfig):
+ Optional. Additional configurations for deleting the Agent Engine session.
+
+ Returns:
+ DeleteAgentEngineSessionOperation: The operation for deleting the Agent Engine session.
+
+ """
+
+ parameter_model = types._DeleteAgentEngineSessionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteAgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def get(
+ self,
+ *,
+ name: str,
+ config: Optional[types.GetAgentEngineSessionConfigOrDict] = None,
+ ) -> types.Session:
+ """
+ Gets an agent engine session.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to get. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (GetAgentEngineSessionConfig):
+ Optional. Additional configurations for getting the Agent Engine session.
+
+ Returns:
+ AgentEngineSession: The requested Agent Engine session.
+
+ """
+
+ parameter_model = types._GetAgentEngineSessionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Session._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionsConfigOrDict] = None,
+ ) -> types.ListReasoningEnginesSessionsResponse:
+ """
+ Lists Agent Engine sessions.
+
+ Args:
+ name (str): Required. The name of the Agent Engine to list sessions for. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ config (ListAgentEngineSessionsConfig):
+ Optional. Additional configurations for listing the Agent Engine sessions.
+
+ Returns:
+ ListReasoningEnginesSessionsResponse: The requested Agent Engine sessions.
+
+ """
+
+ parameter_model = types._ListAgentEngineSessionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListAgentEngineSessionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/sessions".format_map(request_url_dict)
+ else:
+ path = "{name}/sessions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListReasoningEnginesSessionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_session_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ parameter_model = types._GetAgentEngineSessionOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetAgentEngineSessionOperationParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _update(
+ self,
+ *,
+ name: str,
+ config: Optional[types.UpdateAgentEngineSessionConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ """
+ Updates an Agent Engine session.
+
+ Args:
+ name (str): Required. The name of the Agent Engine session to be updated. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sessions/{session_id}`.
+ config (UpdateAgentEngineSessionConfig):
+ Optional. Additional configurations for updating the Agent Engine session.
+
+ Returns:
+ AgentEngineSessionOperation: The operation for updating the Agent Engine session.
+
+ """
+
+ parameter_model = types._UpdateAgentEngineSessionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateAgentEngineSessionRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "patch", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.AgentEngineSessionOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ _events = None
+
+ @property
+ def events(self) -> "session_events_module.AsyncSessionEvents":
+ if self._events is None:
+ try:
+ # We need to lazy load the sessions.events module to handle the
+ # possibility of ImportError when dependencies are not installed.
+ self._events = importlib.import_module(".session_events", __package__)
+ except ImportError as e:
+ raise ImportError(
+ "The 'agent_engines.sessions.events' module requires"
+ "additional packages. Please install them using pip install "
+ "google-cloud-aiplatform[agent_engines]"
+ ) from e
+ return self._events.AsyncSessionEvents(self._api_client) # type: ignore[no-any-return]
+
+ async def create(
+ self,
+ *,
+ name: str,
+ user_id: str,
+ config: Optional[types.CreateAgentEngineSessionConfigOrDict] = None,
+ ) -> types.AgentEngineSessionOperation:
+ """Creates a new session in the Agent Engine.
+
+ Args:
+ name (str):
+ Required. The name of the agent engine to create the session for.
+ user_id (str):
+ Required. The user ID of the session.
+ config (CreateAgentEngineSessionConfig):
+ Optional. The configuration for the session to create.
+
+ Returns:
+ AgentEngineSessionOperation: The operation for creating the session.
+ """
+ if config is None:
+ config = types.CreateAgentEngineSessionConfig()
+ elif isinstance(config, dict):
+ config = types.CreateAgentEngineSessionConfig.model_validate(config)
+ operation = await self._create(
+ name=name,
+ user_id=user_id,
+ config=config,
+ )
+ if config.wait_for_completion:
+ if not operation.done:
+ operation = await _agent_engines_utils._await_async_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_session_operation,
+ poll_interval_seconds=0.5,
+ )
+ # We need to make a call to get the session because the operation
+ # response might not contain the relevant fields.
+ if operation.response:
+ operation.response = await self.get(name=operation.response.name)
+ elif operation.error:
+ raise RuntimeError(f"Failed to create session: {operation.error}")
+ else:
+ raise RuntimeError(
+ "Error retrieving session from the operation response. "
+ f"Operation name: {operation.name}"
+ )
+ return operation
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListAgentEngineSessionsConfigOrDict] = None,
+ ) -> AsyncPager[types.Session]:
+ """Lists Agent Engine sessions.
+
+ Args:
+ name (str): Required. The name of the agent engine to list sessions
+ for.
+ config (ListAgentEngineSessionConfig): Optional. The configuration
+ for the sessions to list.
+
+ Returns:
+ AsyncPager[Session]: An async pager of sessions.
+ """
+
+ return AsyncPager(
+ "sessions",
+ functools.partial(self._list, name=name),
+ await self._list(name=name, config=config),
+ config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/skill_revisions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/skill_revisions.py
new file mode 100644
index 0000000000000000000000000000000000000000..11484e428bdd6d73770398e4f829d408002da8e1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/skill_revisions.py
@@ -0,0 +1,377 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import json
+import logging
+from typing import Any, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+
+from . import types
+
+logger = logging.getLogger("agentplatform_genai.skillrevisions")
+
+
+def _GetSkillRevisionRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _ListSkillRevisionsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ return to_object
+
+
+def _ListSkillRevisionsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _ListSkillRevisionsConfig_to_vertex(
+ getv(from_object, ["config"]), to_object
+ ),
+ )
+
+ return to_object
+
+
+class SkillRevisions(_api_module.BaseModule):
+ """Class for managing Skill Revisions in the Skill Registry."""
+
+ def get(
+ self, *, name: str, config: Optional[types.GetSkillRevisionConfigOrDict] = None
+ ) -> types.SkillRevision:
+ """
+ Gets a Skill Revision.
+ """
+
+ parameter_model = types._GetSkillRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSkillRevisionRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillRevision._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSkillRevisionsConfigOrDict] = None,
+ ) -> types.ListSkillRevisionsResponse:
+ """
+ Lists Skill Revisions.
+ """
+
+ parameter_model = types._ListSkillRevisionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSkillRevisionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/revisions".format_map(request_url_dict)
+ else:
+ path = "{name}/revisions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSkillRevisionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+
+class AsyncSkillRevisions(_api_module.BaseModule):
+ """Class for managing Skill Revisions in the Skill Registry."""
+
+ async def get(
+ self, *, name: str, config: Optional[types.GetSkillRevisionConfigOrDict] = None
+ ) -> types.SkillRevision:
+ """
+ Gets a Skill Revision.
+ """
+
+ parameter_model = types._GetSkillRevisionRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSkillRevisionRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillRevision._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def list(
+ self,
+ *,
+ name: str,
+ config: Optional[types.ListSkillRevisionsConfigOrDict] = None,
+ ) -> types.ListSkillRevisionsResponse:
+ """
+ Lists Skill Revisions.
+ """
+
+ parameter_model = types._ListSkillRevisionsRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSkillRevisionsRequestParameters_to_vertex(
+ parameter_model
+ )
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}/revisions".format_map(request_url_dict)
+ else:
+ path = "{name}/revisions"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSkillRevisionsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/skills.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/skills.py
new file mode 100644
index 0000000000000000000000000000000000000000..d340a67e50ee9f37b1300acf04cbeca98f35567e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/skills.py
@@ -0,0 +1,1713 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import asyncio
+import base64
+import importlib
+import json
+import logging
+import typing
+from typing import Any, Iterator, Optional, Union
+from urllib.parse import urlencode
+
+from google.genai import _api_module
+from google.genai import _common
+from google.genai._common import get_value_by_path as getv
+from google.genai._common import set_value_by_path as setv
+from google.genai.pagers import AsyncPager, Pager
+
+from . import _skills_utils
+from . import types
+
+if typing.TYPE_CHECKING:
+ from . import skill_revisions as skill_revisions_module
+
+ _ = skill_revisions_module
+
+
+logger = logging.getLogger("agentplatform_genai.skills")
+
+
+def _CreateSkillConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["zipped_filesystem"]) is not None:
+ setv(
+ parent_object,
+ ["zippedFilesystem"],
+ getv(from_object, ["zipped_filesystem"]),
+ )
+
+ if getv(from_object, ["skill_id"]) is not None:
+ setv(parent_object, ["_query", "skillId"], getv(from_object, ["skill_id"]))
+
+ return to_object
+
+
+def _CreateSkillRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["display_name"]) is not None:
+ setv(to_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(to_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _CreateSkillConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+def _DeleteSkillRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ return to_object
+
+
+def _GetSkillOperationParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["operation_name"]) is not None:
+ setv(
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
+ )
+
+ return to_object
+
+
+def _GetSkillRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(to_object, ["config"], getv(from_object, ["config"]))
+
+ return to_object
+
+
+def _ListSkillsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["page_size"]) is not None:
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
+
+ if getv(from_object, ["page_token"]) is not None:
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
+
+ if getv(from_object, ["filter"]) is not None:
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
+
+ return to_object
+
+
+def _ListSkillsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _ListSkillsConfig_to_vertex(getv(from_object, ["config"]), to_object),
+ )
+
+ return to_object
+
+
+def _RetrieveSkillsConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["top_k"]) is not None:
+ setv(parent_object, ["_query", "topK"], getv(from_object, ["top_k"]))
+
+ return to_object
+
+
+def _RetrieveSkillsRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["query"]) is not None:
+ setv(to_object, ["_query", "query"], getv(from_object, ["query"]))
+
+ if getv(from_object, ["config"]) is not None:
+ setv(
+ to_object,
+ ["config"],
+ _RetrieveSkillsConfig_to_vertex(getv(from_object, ["config"]), to_object),
+ )
+
+ return to_object
+
+
+def _UpdateSkillConfig_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+
+ if getv(from_object, ["display_name"]) is not None:
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
+
+ if getv(from_object, ["description"]) is not None:
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
+
+ if getv(from_object, ["zipped_filesystem"]) is not None:
+ setv(
+ parent_object,
+ ["zippedFilesystem"],
+ getv(from_object, ["zipped_filesystem"]),
+ )
+
+ if getv(from_object, ["update_mask"]) is not None:
+ setv(
+ parent_object, ["_query", "updateMask"], getv(from_object, ["update_mask"])
+ )
+
+ return to_object
+
+
+def _UpdateSkillRequestParameters_to_vertex(
+ from_object: Union[dict[str, Any], object],
+ parent_object: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ to_object: dict[str, Any] = {}
+ if getv(from_object, ["name"]) is not None:
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
+
+ if getv(from_object, ["config"]) is not None:
+ _UpdateSkillConfig_to_vertex(getv(from_object, ["config"]), to_object)
+
+ return to_object
+
+
+class Skills(_api_module.BaseModule):
+ """Class for managing Skills in the Skill Registry."""
+
+ def get(
+ self, *, name: str, config: Optional[types.GetSkillConfigOrDict] = None
+ ) -> types.Skill:
+ """
+ Gets a Skill.
+ """
+
+ parameter_model = types._GetSkillRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Skill._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def retrieve(
+ self, *, query: str, config: Optional[types.RetrieveSkillsConfigOrDict] = None
+ ) -> types.RetrieveSkillsResponse:
+ """
+ Retrieves skills semantically matched to a query.
+ """
+
+ parameter_model = types._RetrieveSkillsRequestParameters(
+ query=query,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RetrieveSkillsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "skills:retrieve".format_map(request_url_dict)
+ else:
+ path = "skills:retrieve"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RetrieveSkillsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _create(
+ self,
+ *,
+ display_name: str,
+ description: str,
+ config: Optional[types.CreateSkillConfigOrDict] = None,
+ ) -> types.SkillOperation:
+ """
+ Creates a new Skill.
+ """
+
+ parameter_model = types._CreateSkillRequestParameters(
+ display_name=display_name,
+ description=description,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "skills".format_map(request_url_dict)
+ else:
+ path = "skills"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("post", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _update(
+ self, *, name: str, config: Optional[types.UpdateSkillConfigOrDict] = None
+ ) -> types.SkillOperation:
+ """
+ Updates a Skill.
+ """
+
+ parameter_model = types._UpdateSkillRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("patch", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _list(
+ self, *, config: Optional[types.ListSkillsConfigOrDict] = None
+ ) -> types.ListSkillsResponse:
+ """
+ Lists Skills in the Skill Registry.
+ """
+
+ parameter_model = types._ListSkillsRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSkillsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "skills".format_map(request_url_dict)
+ else:
+ path = "skills"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSkillsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _delete(
+ self, *, name: str, config: Optional[types.DeleteSkillConfigOrDict] = None
+ ) -> types.DeleteSkillOperation:
+ """
+ Deletes a Skill.
+ """
+
+ parameter_model = types._DeleteSkillRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("delete", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteSkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def _get_skill_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetSkillOperationConfigOrDict] = None,
+ ) -> types.SkillOperation:
+ parameter_model = types._GetSkillOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSkillOperationParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = self._api_client.request("get", path, request_dict, http_options)
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ def create(
+ self,
+ *,
+ display_name: str,
+ description: str,
+ config: Optional[types.CreateSkillConfigOrDict] = None,
+ ) -> Union[types.Skill, types.SkillOperation]:
+ """Creates a new Skill.
+
+ Args:
+ display_name (str):
+ Required. The display name of the Skill.
+ description (str):
+ Required. The description of the Skill.
+ config (CreateSkillConfigOrDict):
+ Optional. The configuration for creating the Skill.
+
+ Returns:
+ Skill: The created Skill if wait_for_completion is True.
+ SkillOperation: The operation for creating the Skill if
+ wait_for_completion is False.
+ """
+ if config is None:
+ config = types.CreateSkillConfig()
+ elif isinstance(config, dict):
+ config = types.CreateSkillConfig.model_validate(config)
+ elif not isinstance(config, types.CreateSkillConfig):
+ raise TypeError(
+ f"config must be a dict or CreateSkillConfig, but got {type(config)}."
+ )
+
+ config = config.model_copy()
+
+ local_path = config.local_path
+ zipped_filesystem = config.zipped_filesystem
+
+ if local_path and zipped_filesystem:
+ raise ValueError(
+ "Only one of `local_path` or `zipped_filesystem` can be provided in config."
+ )
+ if not local_path and not zipped_filesystem:
+ raise ValueError(
+ "Either `local_path` or `zipped_filesystem` must be provided in config."
+ )
+
+ if local_path:
+ zipped_filesystem_payload = _skills_utils.get_zipped_filesystem_payload(
+ local_path
+ )
+ else:
+ # Narrow type for mypy
+ if zipped_filesystem is None:
+ raise ValueError(
+ "zipped_filesystem is required if local_path is not provided."
+ )
+ if isinstance(zipped_filesystem, bytes):
+ zipped_filesystem_payload = base64.b64encode(zipped_filesystem).decode(
+ "utf-8"
+ )
+ else:
+ zipped_filesystem_payload = zipped_filesystem
+
+ # Mutate the config object to populate the zipped_filesystem payload
+ config.zipped_filesystem = zipped_filesystem_payload
+
+ operation = self._create(
+ display_name=display_name,
+ description=description,
+ config=config,
+ )
+
+ if config.wait_for_completion:
+ operation = _skills_utils.await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_skill_operation,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to create Skill: {operation.error}")
+ # Fetch the fully populated Skill resource from the server
+ return self.get(name=operation.response.name)
+
+ return operation
+
+ def update(
+ self,
+ *,
+ name: str,
+ config: Optional[types.UpdateSkillConfigOrDict] = None,
+ ) -> Union[types.Skill, types.SkillOperation]:
+ """Updates an existing Skill.
+
+ Args:
+ name (str):
+ Required. The resource name of the Skill to update.
+ Format: projects/{project}/locations/{location}/skills/{skill}
+ config (UpdateSkillConfigOrDict):
+ Optional. The configuration for updating the Skill.
+
+ Returns:
+ Skill: The updated Skill if wait_for_completion is True.
+ SkillOperation: The operation for updating the Skill if
+ wait_for_completion is False.
+ """
+ if config is None:
+ config = types.UpdateSkillConfig()
+ elif isinstance(config, dict):
+ config = types.UpdateSkillConfig.model_validate(config)
+ elif not isinstance(config, types.UpdateSkillConfig):
+ raise TypeError(
+ f"config must be a dict or UpdateSkillConfig, but got {type(config)}."
+ )
+
+ config = config.model_copy()
+
+ display_name = config.display_name
+ description = config.description
+ local_path = config.local_path
+ zipped_filesystem = config.zipped_filesystem
+
+ if local_path and zipped_filesystem:
+ raise ValueError(
+ "Only one of `local_path` or `zipped_filesystem` can be provided in config."
+ )
+
+ # Construct update_mask and prepare payload
+ update_mask_paths = []
+ zipped_filesystem_payload = None
+
+ if display_name is not None:
+ update_mask_paths.append("displayName")
+
+ if description is not None:
+ update_mask_paths.append("description")
+
+ if local_path:
+ zipped_filesystem_payload = _skills_utils.get_zipped_filesystem_payload(
+ local_path
+ )
+ update_mask_paths.append("zippedFilesystem")
+ elif zipped_filesystem is not None:
+ if isinstance(zipped_filesystem, bytes):
+ zipped_filesystem_payload = base64.b64encode(zipped_filesystem).decode(
+ "utf-8"
+ )
+ else:
+ zipped_filesystem_payload = zipped_filesystem
+ update_mask_paths.append("zippedFilesystem")
+
+ if not update_mask_paths:
+ raise ValueError(
+ "At least one of `display_name`, `description`, `local_path`, or "
+ "`zipped_filesystem` must be provided for update in config."
+ )
+
+ update_mask = ",".join(update_mask_paths)
+
+ # Mutate config in place to populate the generated update_mask and zipped_filesystem
+ config.update_mask = update_mask
+ config.zipped_filesystem = zipped_filesystem_payload
+
+ operation = self._update(
+ name=name,
+ config=config,
+ )
+
+ if config.wait_for_completion:
+ operation = _skills_utils.await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_skill_operation,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to update Skill: {operation.error}")
+ # Fetch the fully populated Skill resource from the server
+ return self.get(name=name)
+
+ return operation
+
+ def list(
+ self,
+ *,
+ config: Optional[types.ListSkillsConfigOrDict] = None,
+ ) -> Iterator[types.Skill]:
+ """Lists Skills in the Skill Registry.
+
+ Args:
+ config (ListSkillsConfigOrDict):
+ Optional. Additional configuration for listing Skills.
+
+ Returns:
+ Iterator[Skill]: An iterator (Pager) of Skills.
+ """
+ return Pager(
+ "skills",
+ self._list,
+ self._list(config=config),
+ config,
+ )
+
+ def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSkillConfigOrDict] = None,
+ ) -> Optional[types.DeleteSkillOperation]:
+ """Deletes a Skill.
+
+ Args:
+ name (str):
+ Required. The resource name of the Skill to delete.
+ Format: projects/{project}/locations/{location}/skills/{skill}
+ config (DeleteSkillConfigOrDict):
+ Optional. Additional configuration for the delete operation.
+
+ Returns:
+ DeleteSkillOperation: The pending LRO if wait_for_completion is False,
+ otherwise None (blocks until done).
+ """
+ if config is None:
+ config = types.DeleteSkillConfig()
+ elif isinstance(config, dict):
+ config = types.DeleteSkillConfig.model_validate(config)
+ elif not isinstance(config, types.DeleteSkillConfig):
+ raise TypeError(
+ f"config must be a dict or DeleteSkillConfig, but got {type(config)}."
+ )
+
+ operation = self._delete(name=name, config=config)
+
+ if config.wait_for_completion:
+ operation = _skills_utils.await_operation(
+ operation_name=operation.name,
+ get_operation_fn=self._get_skill_operation,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to delete Skill: {operation.error}")
+ return None
+
+ return operation
+
+ _revisions = None
+
+ @property
+ def revisions(self) -> "skill_revisions_module.SkillRevisions":
+ """Returns the revisions sub-module."""
+ if self._revisions is None:
+ # Lazy load to avoid circular imports
+ self._revisions = importlib.import_module(".skill_revisions", __package__)
+ return self._revisions.SkillRevisions(self._api_client) # type: ignore[no-any-return]
+
+
+class AsyncSkills(_api_module.BaseModule):
+ """Class for managing Skills in the Skill Registry."""
+
+ async def get(
+ self, *, name: str, config: Optional[types.GetSkillConfigOrDict] = None
+ ) -> types.Skill:
+ """
+ Gets a Skill.
+ """
+
+ parameter_model = types._GetSkillRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.Skill._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def retrieve(
+ self, *, query: str, config: Optional[types.RetrieveSkillsConfigOrDict] = None
+ ) -> types.RetrieveSkillsResponse:
+ """
+ Retrieves skills semantically matched to a query.
+ """
+
+ parameter_model = types._RetrieveSkillsRequestParameters(
+ query=query,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _RetrieveSkillsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "skills:retrieve".format_map(request_url_dict)
+ else:
+ path = "skills:retrieve"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.RetrieveSkillsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _create(
+ self,
+ *,
+ display_name: str,
+ description: str,
+ config: Optional[types.CreateSkillConfigOrDict] = None,
+ ) -> types.SkillOperation:
+ """
+ Creates a new Skill.
+ """
+
+ parameter_model = types._CreateSkillRequestParameters(
+ display_name=display_name,
+ description=description,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _CreateSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "skills".format_map(request_url_dict)
+ else:
+ path = "skills"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "post", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _update(
+ self, *, name: str, config: Optional[types.UpdateSkillConfigOrDict] = None
+ ) -> types.SkillOperation:
+ """
+ Updates a Skill.
+ """
+
+ parameter_model = types._UpdateSkillRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _UpdateSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "patch", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _list(
+ self, *, config: Optional[types.ListSkillsConfigOrDict] = None
+ ) -> types.ListSkillsResponse:
+ """
+ Lists Skills in the Skill Registry.
+ """
+
+ parameter_model = types._ListSkillsRequestParameters(
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _ListSkillsRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "skills".format_map(request_url_dict)
+ else:
+ path = "skills"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.ListSkillsResponse._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _delete(
+ self, *, name: str, config: Optional[types.DeleteSkillConfigOrDict] = None
+ ) -> types.DeleteSkillOperation:
+ """
+ Deletes a Skill.
+ """
+
+ parameter_model = types._DeleteSkillRequestParameters(
+ name=name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _DeleteSkillRequestParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{name}".format_map(request_url_dict)
+ else:
+ path = "{name}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "delete", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.DeleteSkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def _get_skill_operation(
+ self,
+ *,
+ operation_name: str,
+ config: Optional[types.GetSkillOperationConfigOrDict] = None,
+ ) -> types.SkillOperation:
+ parameter_model = types._GetSkillOperationParameters(
+ operation_name=operation_name,
+ config=config,
+ )
+
+ request_url_dict: Optional[dict[str, str]]
+ if not self._api_client.vertexai:
+ raise ValueError(
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
+ )
+ else:
+ request_dict = _GetSkillOperationParameters_to_vertex(parameter_model)
+ request_url_dict = request_dict.get("_url")
+ if request_url_dict:
+ path = "{operationName}".format_map(request_url_dict)
+ else:
+ path = "{operationName}"
+
+ query_params = request_dict.get("_query")
+ if query_params:
+ path = f"{path}?{urlencode(query_params)}"
+ # TODO: remove the hack that pops config.
+ request_dict.pop("config", None)
+
+ http_options: Optional[types.HttpOptions] = None
+ if (
+ parameter_model.config is not None
+ and parameter_model.config.http_options is not None
+ ):
+ http_options = parameter_model.config.http_options
+
+ request_dict = _common.convert_to_dict(request_dict)
+ request_dict = _common.encode_unserializable_types(request_dict)
+
+ response = await self._api_client.async_request(
+ "get", path, request_dict, http_options
+ )
+
+ response_dict = {} if not response.body else json.loads(response.body)
+
+ return_value = types.SkillOperation._from_response(
+ response=response_dict,
+ kwargs=(
+ {
+ "config": {
+ "response_schema": getattr(
+ parameter_model.config, "response_schema", None
+ ),
+ "response_json_schema": getattr(
+ parameter_model.config, "response_json_schema", None
+ ),
+ "include_all_fields": getattr(
+ parameter_model.config, "include_all_fields", None
+ ),
+ }
+ }
+ if getattr(parameter_model, "config", None)
+ else {}
+ ),
+ )
+
+ self._api_client._verify_response(return_value)
+ return return_value
+
+ async def create(
+ self,
+ *,
+ display_name: str,
+ description: str,
+ config: Optional[types.CreateSkillConfigOrDict] = None,
+ ) -> Union[types.Skill, types.SkillOperation]:
+ """Creates a new Skill asynchronously.
+
+ Args:
+ display_name (str):
+ Required. The display name of the Skill.
+ description (str):
+ Required. The description of the Skill.
+ config (CreateSkillConfigOrDict):
+ Optional. The configuration for creating the Skill.
+
+ Returns:
+ Skill: The created Skill if wait_for_completion is True.
+ SkillOperation: The operation for creating the Skill if
+ wait_for_completion is False.
+ """
+ if config is None:
+ config = types.CreateSkillConfig()
+ elif isinstance(config, dict):
+ config = types.CreateSkillConfig.model_validate(config)
+ elif not isinstance(config, types.CreateSkillConfig):
+ raise TypeError(
+ f"config must be a dict or CreateSkillConfig, but got {type(config)}."
+ )
+
+ config = config.model_copy()
+
+ local_path = config.local_path
+ zipped_filesystem = config.zipped_filesystem
+
+ if local_path and zipped_filesystem:
+ raise ValueError(
+ "Only one of `local_path` or `zipped_filesystem` can be provided in config."
+ )
+ if not local_path and not zipped_filesystem:
+ raise ValueError(
+ "Either `local_path` or `zipped_filesystem` must be provided in config."
+ )
+
+ if local_path:
+ loop = asyncio.get_running_loop()
+ zipped_filesystem_payload = await loop.run_in_executor(
+ None, _skills_utils.get_zipped_filesystem_payload, local_path
+ )
+ else:
+ # Narrow type for mypy
+ if zipped_filesystem is None:
+ raise ValueError(
+ "zipped_filesystem is required if local_path is not provided."
+ )
+ if isinstance(zipped_filesystem, bytes):
+ zipped_filesystem_payload = base64.b64encode(zipped_filesystem).decode(
+ "utf-8"
+ )
+ else:
+ zipped_filesystem_payload = zipped_filesystem
+
+ # Mutate the config object to populate the zipped_filesystem payload
+ config.zipped_filesystem = zipped_filesystem_payload
+
+ operation = await self._create(
+ display_name=display_name,
+ description=description,
+ config=config,
+ )
+
+ if config.wait_for_completion:
+ operation = await _skills_utils.await_operation_async(
+ operation_name=operation.name,
+ get_operation_fn=self._get_skill_operation,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to create Skill: {operation.error}")
+ # Fetch the fully populated Skill resource asynchronously
+ return await self.get(name=operation.response.name)
+
+ return operation
+
+ async def update(
+ self,
+ *,
+ name: str,
+ config: Optional[types.UpdateSkillConfigOrDict] = None,
+ ) -> Union[types.Skill, types.SkillOperation]:
+ """Updates an existing Skill asynchronously.
+
+ Args:
+ name (str):
+ Required. The resource name of the Skill to update.
+ Format: projects/{project}/locations/{location}/skills/{skill}
+ config (UpdateSkillConfigOrDict):
+ Optional. The configuration for updating the Skill.
+
+ Returns:
+ Skill: The updated Skill if wait_for_completion is True.
+ SkillOperation: The operation for updating the Skill if
+ wait_for_completion is False.
+ """
+ if config is None:
+ config = types.UpdateSkillConfig()
+ elif isinstance(config, dict):
+ config = types.UpdateSkillConfig.model_validate(config)
+ elif not isinstance(config, types.UpdateSkillConfig):
+ raise TypeError(
+ f"config must be a dict or UpdateSkillConfig, but got {type(config)}."
+ )
+
+ config = config.model_copy()
+
+ display_name = config.display_name
+ description = config.description
+ local_path = config.local_path
+ zipped_filesystem = config.zipped_filesystem
+
+ if local_path and zipped_filesystem:
+ raise ValueError(
+ "Only one of `local_path` or `zipped_filesystem` can be provided in config."
+ )
+
+ # Construct update_mask and prepare payload
+ update_mask_paths = []
+ zipped_filesystem_payload = None
+
+ if display_name is not None:
+ update_mask_paths.append("displayName")
+
+ if description is not None:
+ update_mask_paths.append("description")
+
+ if local_path:
+ loop = asyncio.get_running_loop()
+ zipped_filesystem_payload = await loop.run_in_executor(
+ None, _skills_utils.get_zipped_filesystem_payload, local_path
+ )
+ update_mask_paths.append("zippedFilesystem")
+ elif zipped_filesystem is not None:
+ if isinstance(zipped_filesystem, bytes):
+ zipped_filesystem_payload = base64.b64encode(zipped_filesystem).decode(
+ "utf-8"
+ )
+ else:
+ zipped_filesystem_payload = zipped_filesystem
+ update_mask_paths.append("zippedFilesystem")
+
+ if not update_mask_paths:
+ raise ValueError(
+ "At least one of `display_name`, `description`, `local_path`, or "
+ "`zipped_filesystem` must be provided for update in config."
+ )
+
+ update_mask = ",".join(update_mask_paths)
+
+ # Mutate config in place to populate the generated update_mask and zipped_filesystem
+ config.update_mask = update_mask
+ config.zipped_filesystem = zipped_filesystem_payload
+
+ operation = await self._update(
+ name=name,
+ config=config,
+ )
+
+ if config.wait_for_completion:
+ operation = await _skills_utils.await_operation_async(
+ operation_name=operation.name,
+ get_operation_fn=self._get_skill_operation,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to update Skill: {operation.error}")
+ # Fetch the fully populated Skill resource asynchronously
+ return await self.get(name=name)
+
+ return operation
+
+ async def list(
+ self,
+ *,
+ config: Optional[types.ListSkillsConfigOrDict] = None,
+ ) -> AsyncPager[types.Skill]:
+ """Lists Skills in the Skill Registry asynchronously.
+
+ Args:
+ config (ListSkillsConfigOrDict):
+ Optional. Additional configuration for listing Skills.
+
+ Returns:
+ AsyncPager[Skill]: An async pager of Skills.
+ """
+ return AsyncPager(
+ "skills",
+ self._list,
+ await self._list(config=config),
+ config,
+ )
+
+ async def delete(
+ self,
+ *,
+ name: str,
+ config: Optional[types.DeleteSkillConfigOrDict] = None,
+ ) -> Optional[types.DeleteSkillOperation]:
+ """Deletes a Skill asynchronously.
+
+ Args:
+ name (str):
+ Required. The resource name of the Skill to delete.
+ Format: projects/{project}/locations/{location}/skills/{skill}
+ config (DeleteSkillConfigOrDict):
+ Optional. Additional configuration for the delete operation.
+
+ Returns:
+ DeleteSkillOperation: The pending LRO if wait_for_completion is False,
+ otherwise None (blocks until done).
+ """
+ if config is None:
+ config = types.DeleteSkillConfig()
+ elif isinstance(config, dict):
+ config = types.DeleteSkillConfig.model_validate(config)
+ elif not isinstance(config, types.DeleteSkillConfig):
+ raise TypeError(
+ f"config must be a dict or DeleteSkillConfig, but got {type(config)}."
+ )
+
+ operation = await self._delete(name=name, config=config)
+
+ if config.wait_for_completion:
+ operation = await _skills_utils.await_operation_async(
+ operation_name=operation.name,
+ get_operation_fn=self._get_skill_operation,
+ )
+ if operation.error:
+ raise RuntimeError(f"Failed to delete Skill: {operation.error}")
+ return None
+
+ return operation
+
+ _revisions = None
+
+ @property
+ def revisions(self) -> "skill_revisions_module.AsyncSkillRevisions":
+ """Returns the revisions sub-module asynchronously."""
+ if self._revisions is None:
+ self._revisions = importlib.import_module(".skill_revisions", __package__)
+ return self._revisions.AsyncSkillRevisions(self._api_client) # type: ignore[no-any-return]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..706188be8f2ab0c00626b626d6b390eb3e71187d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__init__.py
@@ -0,0 +1,2885 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+# flake8: noqa: F401
+
+import importlib
+import typing
+
+from . import agent_engines
+from . import evals
+from . import prompts
+from .common import _AppendAgentEngineSessionEventRequestParameters
+from .common import _AppendAgentEngineTaskEventRequestParameters
+from .common import _AssembleDatasetParameters
+from .common import _AssessDatasetParameters
+from .common import _CancelQueryJobAgentEngineRequestParameters
+from .common import _CheckQueryJobAgentEngineRequestParameters
+from .common import _CreateAgentEngineMemoryRequestParameters
+from .common import _CreateAgentEngineRequestParameters
+from .common import _CreateAgentEngineSandboxRequestParameters
+from .common import _CreateAgentEngineSessionRequestParameters
+from .common import _CreateAgentEngineTaskRequestParameters
+from .common import _CreateDatasetParameters
+from .common import _CreateDatasetVersionParameters
+from .common import _CreateEvaluationItemParameters
+from .common import _CreateEvaluationMetricParameters
+from .common import _CreateEvaluationRunParameters
+from .common import _CreateEvaluationSetParameters
+from .common import _CreateMultimodalDatasetParameters
+from .common import _CreateSandboxEnvironmentSnapshotRequestParameters
+from .common import _CreateSandboxEnvironmentTemplateRequestParameters
+from .common import _CreateSkillRequestParameters
+from .common import _CustomJobParameters
+from .common import _CustomJobParameters
+from .common import _DeleteAgentEngineMemoryRequestParameters
+from .common import _DeleteAgentEngineRequestParameters
+from .common import _DeleteAgentEngineRuntimeRevisionRequestParameters
+from .common import _DeleteAgentEngineSandboxRequestParameters
+from .common import _DeleteAgentEngineSessionRequestParameters
+from .common import _DeleteAgentEngineTaskRequestParameters
+from .common import _DeleteDatasetRequestParameters
+from .common import _DeleteEvaluationMetricParameters
+from .common import _DeleteMultimodalDatasetRequestParameters
+from .common import _DeletePromptVersionRequestParameters
+from .common import _DeleteSandboxEnvironmentSnapshotRequestParameters
+from .common import _DeleteSandboxEnvironmentTemplateRequestParameters
+from .common import _DeleteSkillRequestParameters
+from .common import _EvaluateInstancesRequestParameters
+from .common import _ExecuteCodeAgentEngineSandboxRequestParameters
+from .common import _GenerateAgentEngineMemoriesRequestParameters
+from .common import _GenerateInstanceRubricsRequest
+from .common import _GenerateLossClustersParameters
+from .common import _GenerateUserScenariosParameters
+from .common import _GetAgentEngineGenerateMemoriesOperationParameters
+from .common import _GetAgentEngineMemoryOperationParameters
+from .common import _GetAgentEngineMemoryRequestParameters
+from .common import _GetAgentEngineMemoryRevisionRequestParameters
+from .common import _GetAgentEngineOperationParameters
+from .common import _GetAgentEngineRequestParameters
+from .common import _GetAgentEngineRuntimeRevisionRequestParameters
+from .common import _GetAgentEngineSandboxOperationParameters
+from .common import _GetAgentEngineSandboxRequestParameters
+from .common import _GetAgentEngineSandboxSnapshotOperationParameters
+from .common import _GetAgentEngineSessionOperationParameters
+from .common import _GetAgentEngineSessionRequestParameters
+from .common import _GetAgentEngineTaskRequestParameters
+from .common import _GetCustomJobParameters
+from .common import _GetCustomJobParameters
+from .common import _GetDatasetOperationParameters
+from .common import _GetDatasetParameters
+from .common import _GetDatasetVersionParameters
+from .common import _GetDeleteAgentEngineRuntimeRevisionOperationParameters
+from .common import _GetEvaluationItemParameters
+from .common import _GetEvaluationMetricParameters
+from .common import _GetEvaluationRunParameters
+from .common import _GetEvaluationSetParameters
+from .common import _GetMultimodalDatasetOperationParameters
+from .common import _GetMultimodalDatasetParameters
+from .common import _GetSandboxEnvironmentSnapshotRequestParameters
+from .common import _GetSandboxEnvironmentTemplateOperationParameters
+from .common import _GetSandboxEnvironmentTemplateRequestParameters
+from .common import _GetSkillOperationParameters
+from .common import _GetSkillRequestParameters
+from .common import _GetSkillRevisionRequestParameters
+from .common import _IngestEventsRequestParameters
+from .common import _ListAgentEngineMemoryRequestParameters
+from .common import _ListAgentEngineMemoryRevisionsRequestParameters
+from .common import _ListAgentEngineRequestParameters
+from .common import _ListAgentEngineRuntimeRevisionsRequestParameters
+from .common import _ListAgentEngineSandboxesRequestParameters
+from .common import _ListAgentEngineSessionEventsRequestParameters
+from .common import _ListAgentEngineSessionsRequestParameters
+from .common import _ListAgentEngineTaskEventsRequestParameters
+from .common import _ListAgentEngineTasksRequestParameters
+from .common import _ListDatasetsRequestParameters
+from .common import _ListDatasetVersionsRequestParameters
+from .common import _ListEvaluationMetricsParameters
+from .common import _ListMultimodalDatasetsRequestParameters
+from .common import _ListSandboxEnvironmentSnapshotsRequestParameters
+from .common import _ListSandboxEnvironmentTemplatesRequestParameters
+from .common import _ListSkillRevisionsRequestParameters
+from .common import _ListSkillsRequestParameters
+from .common import _OptimizeRequestParameters
+from .common import _OptimizeRequestParameters
+from .common import _PurgeAgentEngineMemoriesRequestParameters
+from .common import _QueryAgentEngineRequestParameters
+from .common import _QueryAgentEngineRuntimeRevisionRequestParameters
+from .common import _RestoreVersionRequestParameters
+from .common import _RetrieveAgentEngineMemoriesRequestParameters
+from .common import _RetrieveMemoryProfilesRequestParameters
+from .common import _RetrieveSkillsRequestParameters
+from .common import _RollbackAgentEngineMemoryRequestParameters
+from .common import _RunQueryJobAgentEngineConfig
+from .common import _RunQueryJobAgentEngineConfigDict
+from .common import _RunQueryJobAgentEngineConfigOrDict
+from .common import _RunQueryJobAgentEngineRequestParameters
+from .common import _UpdateAgentEngineMemoryRequestParameters
+from .common import _UpdateAgentEngineRequestParameters
+from .common import _UpdateAgentEngineSessionRequestParameters
+from .common import _UpdateDatasetParameters
+from .common import _UpdateMultimodalDatasetParameters
+from .common import _UpdateSkillRequestParameters
+from .common import A2aTask
+from .common import A2aTaskDict
+from .common import A2aTaskOrDict
+from .common import A2aTaskState
+from .common import AcceleratorType
+from .common import AgentEngine
+from .common import AgentEngineConfig
+from .common import AgentEngineConfigDict
+from .common import AgentEngineConfigOrDict
+from .common import AgentEngineDict
+from .common import AgentEngineGenerateMemoriesOperation
+from .common import AgentEngineGenerateMemoriesOperationDict
+from .common import AgentEngineGenerateMemoriesOperationOrDict
+from .common import AgentEngineMemoryConfig
+from .common import AgentEngineMemoryConfigDict
+from .common import AgentEngineMemoryConfigOrDict
+from .common import AgentEngineMemoryOperation
+from .common import AgentEngineMemoryOperationDict
+from .common import AgentEngineMemoryOperationOrDict
+from .common import AgentEngineOperation
+from .common import AgentEngineOperationDict
+from .common import AgentEngineOperationOrDict
+from .common import AgentEngineOrDict
+from .common import AgentEnginePurgeMemoriesOperation
+from .common import AgentEnginePurgeMemoriesOperationDict
+from .common import AgentEnginePurgeMemoriesOperationOrDict
+from .common import AgentEngineRollbackMemoryOperation
+from .common import AgentEngineRollbackMemoryOperationDict
+from .common import AgentEngineRollbackMemoryOperationOrDict
+from .common import AgentEngineRuntimeRevision
+from .common import AgentEngineRuntimeRevisionDict
+from .common import AgentEngineRuntimeRevisionOrDict
+from .common import AgentEngineSandboxOperation
+from .common import AgentEngineSandboxOperationDict
+from .common import AgentEngineSandboxOperationOrDict
+from .common import AgentEngineSandboxSnapshotOperation
+from .common import AgentEngineSandboxSnapshotOperationDict
+from .common import AgentEngineSandboxSnapshotOperationOrDict
+from .common import AgentEngineSessionOperation
+from .common import AgentEngineSessionOperationDict
+from .common import AgentEngineSessionOperationOrDict
+from .common import AgentRunConfig
+from .common import AgentRunConfigDict
+from .common import AgentRunConfigOrDict
+from .common import AgentServerMode
+from .common import AggregatedMetricResult
+from .common import AggregatedMetricResultDict
+from .common import AggregatedMetricResultOrDict
+from .common import AnalysisConfig
+from .common import AnalysisConfigDict
+from .common import AnalysisConfigOrDict
+from .common import AppendAgentEngineSessionEventConfig
+from .common import AppendAgentEngineSessionEventConfigDict
+from .common import AppendAgentEngineSessionEventConfigOrDict
+from .common import AppendAgentEngineSessionEventResponse
+from .common import AppendAgentEngineSessionEventResponseDict
+from .common import AppendAgentEngineSessionEventResponseOrDict
+from .common import AppendAgentEngineTaskEventConfig
+from .common import AppendAgentEngineTaskEventConfigDict
+from .common import AppendAgentEngineTaskEventConfigOrDict
+from .common import AppendAgentEngineTaskEventResponse
+from .common import AppendAgentEngineTaskEventResponseDict
+from .common import AppendAgentEngineTaskEventResponseOrDict
+from .common import AssembleDataset
+from .common import AssembleDatasetConfig
+from .common import AssembleDatasetConfigDict
+from .common import AssembleDatasetConfigOrDict
+from .common import AssembleDatasetDict
+from .common import AssembleDatasetOrDict
+from .common import AssessDatasetConfig
+from .common import AssessDatasetConfigDict
+from .common import AssessDatasetConfigOrDict
+from .common import AttackCategoryResult
+from .common import AttackCategoryResultDict
+from .common import AttackCategoryResultOrDict
+from .common import BatchPredictionResourceUsageAssessmentConfig
+from .common import BatchPredictionResourceUsageAssessmentConfigDict
+from .common import BatchPredictionResourceUsageAssessmentConfigOrDict
+from .common import BatchPredictionResourceUsageAssessmentResult
+from .common import BatchPredictionResourceUsageAssessmentResultDict
+from .common import BatchPredictionResourceUsageAssessmentResultOrDict
+from .common import BatchPredictionValidationAssessmentConfig
+from .common import BatchPredictionValidationAssessmentConfigDict
+from .common import BatchPredictionValidationAssessmentConfigOrDict
+from .common import BatchPredictionValidationAssessmentResult
+from .common import BatchPredictionValidationAssessmentResultDict
+from .common import BatchPredictionValidationAssessmentResultOrDict
+from .common import BigQueryRequestSet
+from .common import BigQueryRequestSetDict
+from .common import BigQueryRequestSetOrDict
+from .common import BleuInput
+from .common import BleuInputDict
+from .common import BleuInputOrDict
+from .common import BleuInstance
+from .common import BleuInstanceDict
+from .common import BleuInstanceOrDict
+from .common import BleuResults
+from .common import BleuResultsDict
+from .common import BleuResultsOrDict
+from .common import CancelQueryJobAgentEngineConfig
+from .common import CancelQueryJobAgentEngineConfigDict
+from .common import CancelQueryJobAgentEngineConfigOrDict
+from .common import CancelQueryJobResult
+from .common import CancelQueryJobResultDict
+from .common import CancelQueryJobResultOrDict
+from .common import CandidateResponse
+from .common import CandidateResponseDict
+from .common import CandidateResponseOrDict
+from .common import CandidateResult
+from .common import CandidateResultDict
+from .common import CheckQueryJobAgentEngineConfig
+from .common import CheckQueryJobAgentEngineConfigDict
+from .common import CheckQueryJobAgentEngineConfigOrDict
+from .common import CheckQueryJobResponse
+from .common import CheckQueryJobResponseDict
+from .common import CheckQueryJobResponseOrDict
+from .common import CheckQueryJobResult
+from .common import CheckQueryJobResultDict
+from .common import CheckQueryJobResultOrDict
+from .common import Chunk
+from .common import ChunkDict
+from .common import ChunkOrDict
+from .common import CodeExecutionMetric
+from .common import CometResult
+from .common import CometResultDict
+from .common import CometResultOrDict
+from .common import ContainerSpec
+from .common import ContainerSpecDict
+from .common import ContainerSpecOrDict
+from .common import ContentMap
+from .common import ContentMapContents
+from .common import ContentMapContentsDict
+from .common import ContentMapContentsOrDict
+from .common import ContentMapDict
+from .common import ContentMapOrDict
+from .common import CreateAgentEngineConfig
+from .common import CreateAgentEngineConfigDict
+from .common import CreateAgentEngineConfigOrDict
+from .common import CreateAgentEngineSandboxConfig
+from .common import CreateAgentEngineSandboxConfigDict
+from .common import CreateAgentEngineSandboxConfigOrDict
+from .common import CreateAgentEngineSandboxSnapshotConfig
+from .common import CreateAgentEngineSandboxSnapshotConfigDict
+from .common import CreateAgentEngineSandboxSnapshotConfigOrDict
+from .common import CreateAgentEngineSessionConfig
+from .common import CreateAgentEngineSessionConfigDict
+from .common import CreateAgentEngineSessionConfigOrDict
+from .common import CreateAgentEngineTaskConfig
+from .common import CreateAgentEngineTaskConfigDict
+from .common import CreateAgentEngineTaskConfigOrDict
+from .common import CreateDatasetConfig
+from .common import CreateDatasetConfigDict
+from .common import CreateDatasetConfigOrDict
+from .common import CreateDatasetVersionConfig
+from .common import CreateDatasetVersionConfigDict
+from .common import CreateDatasetVersionConfigOrDict
+from .common import CreateEvaluationItemConfig
+from .common import CreateEvaluationItemConfigDict
+from .common import CreateEvaluationItemConfigOrDict
+from .common import CreateEvaluationMetricConfig
+from .common import CreateEvaluationMetricConfigDict
+from .common import CreateEvaluationMetricConfigOrDict
+from .common import CreateEvaluationRunConfig
+from .common import CreateEvaluationRunConfigDict
+from .common import CreateEvaluationRunConfigOrDict
+from .common import CreateEvaluationSetConfig
+from .common import CreateEvaluationSetConfigDict
+from .common import CreateEvaluationSetConfigOrDict
+from .common import CreateMultimodalDatasetConfig
+from .common import CreateMultimodalDatasetConfigDict
+from .common import CreateMultimodalDatasetConfigOrDict
+from .common import CreatePromptConfig
+from .common import CreatePromptConfigDict
+from .common import CreatePromptConfigOrDict
+from .common import CreatePromptVersionConfig
+from .common import CreatePromptVersionConfigDict
+from .common import CreatePromptVersionConfigOrDict
+from .common import CreateSandboxEnvironmentTemplateConfig
+from .common import CreateSandboxEnvironmentTemplateConfigDict
+from .common import CreateSandboxEnvironmentTemplateConfigOrDict
+from .common import CreateSkillConfig
+from .common import CreateSkillConfigDict
+from .common import CreateSkillConfigOrDict
+from .common import CustomCodeExecutionSpec
+from .common import CustomCodeExecutionSpecDict
+from .common import CustomCodeExecutionSpecOrDict
+from .common import CustomJob
+from .common import CustomJobDict
+from .common import CustomJobOrDict
+from .common import CustomJobSpec
+from .common import CustomJobSpecDict
+from .common import CustomJobSpecOrDict
+from .common import Dataset
+from .common import DatasetDict
+from .common import DatasetOperation
+from .common import DatasetOperationDict
+from .common import DatasetOperationOrDict
+from .common import DatasetOrDict
+from .common import DatasetVersion
+from .common import DatasetVersionDict
+from .common import DatasetVersionOrDict
+from .common import DefaultContainerCategory
+from .common import DeleteAgentEngineConfig
+from .common import DeleteAgentEngineConfigDict
+from .common import DeleteAgentEngineConfigOrDict
+from .common import DeleteAgentEngineMemoryConfig
+from .common import DeleteAgentEngineMemoryConfigDict
+from .common import DeleteAgentEngineMemoryConfigOrDict
+from .common import DeleteAgentEngineMemoryOperation
+from .common import DeleteAgentEngineMemoryOperationDict
+from .common import DeleteAgentEngineMemoryOperationOrDict
+from .common import DeleteAgentEngineOperation
+from .common import DeleteAgentEngineOperationDict
+from .common import DeleteAgentEngineOperationOrDict
+from .common import DeleteAgentEngineRuntimeRevisionConfig
+from .common import DeleteAgentEngineRuntimeRevisionConfigDict
+from .common import DeleteAgentEngineRuntimeRevisionConfigOrDict
+from .common import DeleteAgentEngineRuntimeRevisionOperation
+from .common import DeleteAgentEngineRuntimeRevisionOperationDict
+from .common import DeleteAgentEngineRuntimeRevisionOperationOrDict
+from .common import DeleteAgentEngineSandboxConfig
+from .common import DeleteAgentEngineSandboxConfigDict
+from .common import DeleteAgentEngineSandboxConfigOrDict
+from .common import DeleteAgentEngineSandboxOperation
+from .common import DeleteAgentEngineSandboxOperationDict
+from .common import DeleteAgentEngineSandboxOperationOrDict
+from .common import DeleteAgentEngineSessionConfig
+from .common import DeleteAgentEngineSessionConfigDict
+from .common import DeleteAgentEngineSessionConfigOrDict
+from .common import DeleteAgentEngineSessionOperation
+from .common import DeleteAgentEngineSessionOperationDict
+from .common import DeleteAgentEngineSessionOperationOrDict
+from .common import DeleteAgentEngineTaskConfig
+from .common import DeleteAgentEngineTaskConfigDict
+from .common import DeleteAgentEngineTaskConfigOrDict
+from .common import DeleteEvaluationMetricConfig
+from .common import DeleteEvaluationMetricConfigDict
+from .common import DeleteEvaluationMetricConfigOrDict
+from .common import DeleteEvaluationMetricOperation
+from .common import DeleteEvaluationMetricOperationDict
+from .common import DeleteEvaluationMetricOperationOrDict
+from .common import DeletePromptConfig
+from .common import DeletePromptConfigDict
+from .common import DeletePromptConfigOrDict
+from .common import DeletePromptOperation
+from .common import DeletePromptOperationDict
+from .common import DeletePromptOperationOrDict
+from .common import DeletePromptVersionOperation
+from .common import DeletePromptVersionOperationDict
+from .common import DeletePromptVersionOperationOrDict
+from .common import DeleteSandboxEnvironmentSnapshotConfig
+from .common import DeleteSandboxEnvironmentSnapshotConfigDict
+from .common import DeleteSandboxEnvironmentSnapshotConfigOrDict
+from .common import DeleteSandboxEnvironmentSnapshotOperation
+from .common import DeleteSandboxEnvironmentSnapshotOperationDict
+from .common import DeleteSandboxEnvironmentSnapshotOperationOrDict
+from .common import DeleteSandboxEnvironmentTemplateConfig
+from .common import DeleteSandboxEnvironmentTemplateConfigDict
+from .common import DeleteSandboxEnvironmentTemplateConfigOrDict
+from .common import DeleteSandboxEnvironmentTemplateOperation
+from .common import DeleteSandboxEnvironmentTemplateOperationDict
+from .common import DeleteSandboxEnvironmentTemplateOperationOrDict
+from .common import DeleteSkillConfig
+from .common import DeleteSkillConfigDict
+from .common import DeleteSkillConfigOrDict
+from .common import DeleteSkillOperation
+from .common import DeleteSkillOperationDict
+from .common import DeleteSkillOperationOrDict
+from .common import DiskSpec
+from .common import DiskSpecDict
+from .common import DiskSpecOrDict
+from .common import DnsPeeringConfig
+from .common import DnsPeeringConfigDict
+from .common import DnsPeeringConfigOrDict
+from .common import EnvVar
+from .common import EnvVarDict
+from .common import EnvVarOrDict
+from .common import EvalCase
+from .common import EvalCaseDict
+from .common import EvalCaseMetricResult
+from .common import EvalCaseMetricResultDict
+from .common import EvalCaseMetricResultOrDict
+from .common import EvalCaseOrDict
+from .common import EvalCaseResult
+from .common import EvalCaseResultDict
+from .common import EvalCaseResultOrDict
+from .common import EvalRunInferenceConfig
+from .common import EvalRunInferenceConfigDict
+from .common import EvalRunInferenceConfigOrDict
+from .common import EvaluateDatasetConfig
+from .common import EvaluateDatasetConfigDict
+from .common import EvaluateDatasetConfigOrDict
+from .common import EvaluateDatasetOperation
+from .common import EvaluateDatasetOperationDict
+from .common import EvaluateDatasetOperationOrDict
+from .common import EvaluateDatasetRequestParameters
+from .common import EvaluateDatasetRequestParametersDict
+from .common import EvaluateDatasetRequestParametersOrDict
+from .common import EvaluateInstancesConfig
+from .common import EvaluateInstancesConfigDict
+from .common import EvaluateInstancesConfigOrDict
+from .common import EvaluateInstancesResponse
+from .common import EvaluateInstancesResponseDict
+from .common import EvaluateInstancesResponseOrDict
+from .common import EvaluateMethodConfig
+from .common import EvaluateMethodConfigDict
+from .common import EvaluateMethodConfigOrDict
+from .common import EvaluationDataset
+from .common import EvaluationDatasetDict
+from .common import EvaluationDatasetOrDict
+from .common import EvaluationInstance
+from .common import EvaluationInstanceDict
+from .common import EvaluationInstanceOrDict
+from .common import EvaluationItem
+from .common import EvaluationItemDict
+from .common import EvaluationItemOrDict
+from .common import EvaluationItemRequest
+from .common import EvaluationItemRequestDict
+from .common import EvaluationItemRequestOrDict
+from .common import EvaluationItemResult
+from .common import EvaluationItemResultDict
+from .common import EvaluationItemResultOrDict
+from .common import EvaluationItemType
+from .common import EvaluationMetric
+from .common import EvaluationMetricDict
+from .common import EvaluationMetricOrDict
+from .common import EvaluationPrompt
+from .common import EvaluationPromptDict
+from .common import EvaluationPromptOrDict
+from .common import EvaluationResult
+from .common import EvaluationResultDict
+from .common import EvaluationResultOrDict
+from .common import EvaluationRun
+from .common import EvaluationRunAgentConfig
+from .common import EvaluationRunAgentConfigDict
+from .common import EvaluationRunAgentConfigOrDict
+from .common import EvaluationRunConfig
+from .common import EvaluationRunConfigDict
+from .common import EvaluationRunConfigOrDict
+from .common import EvaluationRunDataSource
+from .common import EvaluationRunDataSourceDict
+from .common import EvaluationRunDataSourceOrDict
+from .common import EvaluationRunDict
+from .common import EvaluationRunInferenceConfig
+from .common import EvaluationRunInferenceConfigDict
+from .common import EvaluationRunInferenceConfigOrDict
+from .common import EvaluationRunMetadata
+from .common import EvaluationRunMetadataDict
+from .common import EvaluationRunMetadataOrDict
+from .common import EvaluationRunMetric
+from .common import EvaluationRunMetricDict
+from .common import EvaluationRunMetricOrDict
+from .common import EvaluationRunOrDict
+from .common import EvaluationRunPromptTemplate
+from .common import EvaluationRunPromptTemplateDict
+from .common import EvaluationRunPromptTemplateOrDict
+from .common import EvaluationRunResults
+from .common import EvaluationRunResultsDict
+from .common import EvaluationRunResultsOrDict
+from .common import EvaluationRunState
+from .common import EvaluationSet
+from .common import EvaluationSetDict
+from .common import EvaluationSetOrDict
+from .common import Event
+from .common import EventActions
+from .common import EventActionsDict
+from .common import EventActionsOrDict
+from .common import EventDict
+from .common import EventMetadata
+from .common import EventMetadataDict
+from .common import EventMetadataOrDict
+from .common import ExactMatchInput
+from .common import ExactMatchInputDict
+from .common import ExactMatchInputOrDict
+from .common import ExactMatchInstance
+from .common import ExactMatchInstanceDict
+from .common import ExactMatchInstanceOrDict
+from .common import ExactMatchResults
+from .common import ExactMatchResultsDict
+from .common import ExactMatchResultsOrDict
+from .common import ExactMatchSpec
+from .common import ExactMatchSpecDict
+from .common import ExactMatchSpecOrDict
+from .common import ExecuteCodeAgentEngineSandboxConfig
+from .common import ExecuteCodeAgentEngineSandboxConfigDict
+from .common import ExecuteCodeAgentEngineSandboxConfigOrDict
+from .common import ExecuteSandboxEnvironmentResponse
+from .common import ExecuteSandboxEnvironmentResponseDict
+from .common import ExecuteSandboxEnvironmentResponseOrDict
+from .common import FailedRubric
+from .common import FailedRubricDict
+from .common import FailedRubricOrDict
+from .common import Framework
+from .common import GeminiExample
+from .common import GeminiExampleDict
+from .common import GeminiExampleOrDict
+from .common import GeminiRequestReadConfig
+from .common import GeminiRequestReadConfigDict
+from .common import GeminiRequestReadConfigOrDict
+from .common import GeminiTemplateConfig
+from .common import GeminiTemplateConfigDict
+from .common import GeminiTemplateConfigOrDict
+from .common import GenerateAgentEngineMemoriesConfig
+from .common import GenerateAgentEngineMemoriesConfigDict
+from .common import GenerateAgentEngineMemoriesConfigOrDict
+from .common import GenerateInstanceRubricsResponse
+from .common import GenerateInstanceRubricsResponseDict
+from .common import GenerateInstanceRubricsResponseOrDict
+from .common import GenerateLossClustersConfig
+from .common import GenerateLossClustersConfigDict
+from .common import GenerateLossClustersConfigOrDict
+from .common import GenerateLossClustersOperation
+from .common import GenerateLossClustersOperationDict
+from .common import GenerateLossClustersOperationOrDict
+from .common import GenerateLossClustersResponse
+from .common import GenerateLossClustersResponseDict
+from .common import GenerateLossClustersResponseOrDict
+from .common import GenerateMemoriesRequestDirectContentsSource
+from .common import GenerateMemoriesRequestDirectContentsSourceDict
+from .common import GenerateMemoriesRequestDirectContentsSourceEvent
+from .common import GenerateMemoriesRequestDirectContentsSourceEventDict
+from .common import GenerateMemoriesRequestDirectContentsSourceEventOrDict
+from .common import GenerateMemoriesRequestDirectContentsSourceOrDict
+from .common import GenerateMemoriesRequestDirectMemoriesSource
+from .common import GenerateMemoriesRequestDirectMemoriesSourceDict
+from .common import GenerateMemoriesRequestDirectMemoriesSourceDirectMemory
+from .common import GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict
+from .common import GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryOrDict
+from .common import GenerateMemoriesRequestDirectMemoriesSourceOrDict
+from .common import GenerateMemoriesRequestVertexSessionSource
+from .common import GenerateMemoriesRequestVertexSessionSourceDict
+from .common import GenerateMemoriesRequestVertexSessionSourceOrDict
+from .common import GenerateMemoriesResponse
+from .common import GenerateMemoriesResponseDict
+from .common import GenerateMemoriesResponseGeneratedMemory
+from .common import GenerateMemoriesResponseGeneratedMemoryAction
+from .common import GenerateMemoriesResponseGeneratedMemoryDict
+from .common import GenerateMemoriesResponseGeneratedMemoryOrDict
+from .common import GenerateMemoriesResponseOrDict
+from .common import GenerateUserScenariosConfig
+from .common import GenerateUserScenariosConfigDict
+from .common import GenerateUserScenariosConfigOrDict
+from .common import GenerateUserScenariosResponse
+from .common import GenerateUserScenariosResponseDict
+from .common import GenerateUserScenariosResponseOrDict
+from .common import GetAgentEngineConfig
+from .common import GetAgentEngineConfigDict
+from .common import GetAgentEngineConfigOrDict
+from .common import GetAgentEngineMemoryConfig
+from .common import GetAgentEngineMemoryConfigDict
+from .common import GetAgentEngineMemoryConfigOrDict
+from .common import GetAgentEngineMemoryRevisionConfig
+from .common import GetAgentEngineMemoryRevisionConfigDict
+from .common import GetAgentEngineMemoryRevisionConfigOrDict
+from .common import GetAgentEngineOperationConfig
+from .common import GetAgentEngineOperationConfigDict
+from .common import GetAgentEngineOperationConfigOrDict
+from .common import GetAgentEngineRuntimeRevisionConfig
+from .common import GetAgentEngineRuntimeRevisionConfigDict
+from .common import GetAgentEngineRuntimeRevisionConfigOrDict
+from .common import GetAgentEngineSandboxConfig
+from .common import GetAgentEngineSandboxConfigDict
+from .common import GetAgentEngineSandboxConfigOrDict
+from .common import GetAgentEngineSessionConfig
+from .common import GetAgentEngineSessionConfigDict
+from .common import GetAgentEngineSessionConfigOrDict
+from .common import GetAgentEngineTaskConfig
+from .common import GetAgentEngineTaskConfigDict
+from .common import GetAgentEngineTaskConfigOrDict
+from .common import GetDatasetOperationConfig
+from .common import GetDatasetOperationConfigDict
+from .common import GetDatasetOperationConfigOrDict
+from .common import GetDeleteAgentEngineRuntimeRevisionOperationConfig
+from .common import GetDeleteAgentEngineRuntimeRevisionOperationConfigDict
+from .common import GetDeleteAgentEngineRuntimeRevisionOperationConfigOrDict
+from .common import GetEvaluationItemConfig
+from .common import GetEvaluationItemConfigDict
+from .common import GetEvaluationItemConfigOrDict
+from .common import GetEvaluationMetricConfig
+from .common import GetEvaluationMetricConfigDict
+from .common import GetEvaluationMetricConfigOrDict
+from .common import GetEvaluationRunConfig
+from .common import GetEvaluationRunConfigDict
+from .common import GetEvaluationRunConfigOrDict
+from .common import GetEvaluationSetConfig
+from .common import GetEvaluationSetConfigDict
+from .common import GetEvaluationSetConfigOrDict
+from .common import GetMultimodalDatasetOperationConfig
+from .common import GetMultimodalDatasetOperationConfigDict
+from .common import GetMultimodalDatasetOperationConfigOrDict
+from .common import GetPromptConfig
+from .common import GetPromptConfigDict
+from .common import GetPromptConfigOrDict
+from .common import GetSandboxEnvironmentSnapshotConfig
+from .common import GetSandboxEnvironmentSnapshotConfigDict
+from .common import GetSandboxEnvironmentSnapshotConfigOrDict
+from .common import GetSandboxEnvironmentTemplateConfig
+from .common import GetSandboxEnvironmentTemplateConfigDict
+from .common import GetSandboxEnvironmentTemplateConfigOrDict
+from .common import GetSkillConfig
+from .common import GetSkillConfigDict
+from .common import GetSkillConfigOrDict
+from .common import GetSkillOperationConfig
+from .common import GetSkillOperationConfigDict
+from .common import GetSkillOperationConfigOrDict
+from .common import GetSkillRevisionConfig
+from .common import GetSkillRevisionConfigDict
+from .common import GetSkillRevisionConfigOrDict
+from .common import IdentityType
+from .common import Importance
+from .common import IngestEventsConfig
+from .common import IngestEventsConfigDict
+from .common import IngestEventsConfigOrDict
+from .common import IngestionDirectContentsSource
+from .common import IngestionDirectContentsSourceDict
+from .common import IngestionDirectContentsSourceEvent
+from .common import IngestionDirectContentsSourceEventDict
+from .common import IngestionDirectContentsSourceEventOrDict
+from .common import IngestionDirectContentsSourceOrDict
+from .common import IntermediateExtractedMemory
+from .common import IntermediateExtractedMemoryDict
+from .common import IntermediateExtractedMemoryOrDict
+from .common import JobState
+from .common import KeepAliveProbe
+from .common import KeepAliveProbeDict
+from .common import KeepAliveProbeHttpGet
+from .common import KeepAliveProbeHttpGetDict
+from .common import KeepAliveProbeHttpGetOrDict
+from .common import KeepAliveProbeOrDict
+from .common import Language
+from .common import ListAgentEngineConfig
+from .common import ListAgentEngineConfigDict
+from .common import ListAgentEngineConfigOrDict
+from .common import ListAgentEngineMemoryConfig
+from .common import ListAgentEngineMemoryConfigDict
+from .common import ListAgentEngineMemoryConfigOrDict
+from .common import ListAgentEngineMemoryRevisionsConfig
+from .common import ListAgentEngineMemoryRevisionsConfigDict
+from .common import ListAgentEngineMemoryRevisionsConfigOrDict
+from .common import ListAgentEngineMemoryRevisionsResponse
+from .common import ListAgentEngineMemoryRevisionsResponseDict
+from .common import ListAgentEngineMemoryRevisionsResponseOrDict
+from .common import ListAgentEngineRuntimeRevisionsConfig
+from .common import ListAgentEngineRuntimeRevisionsConfigDict
+from .common import ListAgentEngineRuntimeRevisionsConfigOrDict
+from .common import ListAgentEngineSandboxesConfig
+from .common import ListAgentEngineSandboxesConfigDict
+from .common import ListAgentEngineSandboxesConfigOrDict
+from .common import ListAgentEngineSandboxesResponse
+from .common import ListAgentEngineSandboxesResponseDict
+from .common import ListAgentEngineSandboxesResponseOrDict
+from .common import ListAgentEngineSessionEventsConfig
+from .common import ListAgentEngineSessionEventsConfigDict
+from .common import ListAgentEngineSessionEventsConfigOrDict
+from .common import ListAgentEngineSessionEventsResponse
+from .common import ListAgentEngineSessionEventsResponseDict
+from .common import ListAgentEngineSessionEventsResponseOrDict
+from .common import ListAgentEngineSessionsConfig
+from .common import ListAgentEngineSessionsConfigDict
+from .common import ListAgentEngineSessionsConfigOrDict
+from .common import ListAgentEngineTaskEventsConfig
+from .common import ListAgentEngineTaskEventsConfigDict
+from .common import ListAgentEngineTaskEventsConfigOrDict
+from .common import ListAgentEngineTaskEventsResponse
+from .common import ListAgentEngineTaskEventsResponseDict
+from .common import ListAgentEngineTaskEventsResponseOrDict
+from .common import ListAgentEngineTasksConfig
+from .common import ListAgentEngineTasksConfigDict
+from .common import ListAgentEngineTasksConfigOrDict
+from .common import ListAgentEngineTasksResponse
+from .common import ListAgentEngineTasksResponseDict
+from .common import ListAgentEngineTasksResponseOrDict
+from .common import ListDatasetsResponse
+from .common import ListDatasetsResponseDict
+from .common import ListDatasetsResponseOrDict
+from .common import ListDatasetVersionsResponse
+from .common import ListDatasetVersionsResponseDict
+from .common import ListDatasetVersionsResponseOrDict
+from .common import ListEvaluationMetricsConfig
+from .common import ListEvaluationMetricsConfigDict
+from .common import ListEvaluationMetricsConfigOrDict
+from .common import ListEvaluationMetricsResponse
+from .common import ListEvaluationMetricsResponseDict
+from .common import ListEvaluationMetricsResponseOrDict
+from .common import ListMultimodalDatasetsConfig
+from .common import ListMultimodalDatasetsConfigDict
+from .common import ListMultimodalDatasetsConfigOrDict
+from .common import ListMultimodalDatasetsResponse
+from .common import ListMultimodalDatasetsResponseDict
+from .common import ListMultimodalDatasetsResponseOrDict
+from .common import ListPromptsConfig
+from .common import ListPromptsConfigDict
+from .common import ListPromptsConfigOrDict
+from .common import ListReasoningEnginesMemoriesResponse
+from .common import ListReasoningEnginesMemoriesResponseDict
+from .common import ListReasoningEnginesMemoriesResponseOrDict
+from .common import ListReasoningEnginesResponse
+from .common import ListReasoningEnginesResponseDict
+from .common import ListReasoningEnginesResponseOrDict
+from .common import ListReasoningEnginesRuntimeRevisionsResponse
+from .common import ListReasoningEnginesRuntimeRevisionsResponseDict
+from .common import ListReasoningEnginesRuntimeRevisionsResponseOrDict
+from .common import ListReasoningEnginesSessionsResponse
+from .common import ListReasoningEnginesSessionsResponseDict
+from .common import ListReasoningEnginesSessionsResponseOrDict
+from .common import ListSandboxEnvironmentSnapshotsConfig
+from .common import ListSandboxEnvironmentSnapshotsConfigDict
+from .common import ListSandboxEnvironmentSnapshotsConfigOrDict
+from .common import ListSandboxEnvironmentSnapshotsResponse
+from .common import ListSandboxEnvironmentSnapshotsResponseDict
+from .common import ListSandboxEnvironmentSnapshotsResponseOrDict
+from .common import ListSandboxEnvironmentTemplatesConfig
+from .common import ListSandboxEnvironmentTemplatesConfigDict
+from .common import ListSandboxEnvironmentTemplatesConfigOrDict
+from .common import ListSandboxEnvironmentTemplatesResponse
+from .common import ListSandboxEnvironmentTemplatesResponseDict
+from .common import ListSandboxEnvironmentTemplatesResponseOrDict
+from .common import ListSkillRevisionsConfig
+from .common import ListSkillRevisionsConfigDict
+from .common import ListSkillRevisionsConfigOrDict
+from .common import ListSkillRevisionsResponse
+from .common import ListSkillRevisionsResponseDict
+from .common import ListSkillRevisionsResponseOrDict
+from .common import ListSkillsConfig
+from .common import ListSkillsConfigDict
+from .common import ListSkillsConfigOrDict
+from .common import ListSkillsResponse
+from .common import ListSkillsResponseDict
+from .common import ListSkillsResponseOrDict
+from .common import LLMMetric
+from .common import LossAnalysisConfig
+from .common import LossAnalysisConfigDict
+from .common import LossAnalysisConfigOrDict
+from .common import LossAnalysisResult
+from .common import LossAnalysisResultDict
+from .common import LossAnalysisResultOrDict
+from .common import LossCluster
+from .common import LossClusterDict
+from .common import LossClusterOrDict
+from .common import LossExample
+from .common import LossExampleDict
+from .common import LossExampleOrDict
+from .common import LossTaxonomyEntry
+from .common import LossTaxonomyEntryDict
+from .common import LossTaxonomyEntryOrDict
+from .common import LustreMount
+from .common import LustreMountDict
+from .common import LustreMountOrDict
+from .common import MachineConfig
+from .common import MachineSpec
+from .common import MachineSpecDict
+from .common import MachineSpecOrDict
+from .common import ManagedTopicEnum
+from .common import MapInstance
+from .common import MapInstanceDict
+from .common import MapInstanceOrDict
+from .common import Memory
+from .common import MemoryBankCustomizationConfig
+from .common import MemoryBankCustomizationConfigConsolidationConfig
+from .common import MemoryBankCustomizationConfigConsolidationConfigDict
+from .common import MemoryBankCustomizationConfigConsolidationConfigOrDict
+from .common import MemoryBankCustomizationConfigDict
+from .common import MemoryBankCustomizationConfigGenerateMemoriesExample
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource,
+)
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict,
+)
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent,
+)
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict,
+)
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventOrDict,
+)
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceOrDict,
+)
+from .common import MemoryBankCustomizationConfigGenerateMemoriesExampleDict
+from .common import MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict,
+)
+from .common import (
+ MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryOrDict,
+)
+from .common import MemoryBankCustomizationConfigGenerateMemoriesExampleOrDict
+from .common import MemoryBankCustomizationConfigMemoryTopic
+from .common import MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic
+from .common import MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict
+from .common import MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicOrDict
+from .common import MemoryBankCustomizationConfigMemoryTopicDict
+from .common import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic
+from .common import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict
+from .common import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicOrDict
+from .common import MemoryBankCustomizationConfigMemoryTopicOrDict
+from .common import MemoryBankCustomizationConfigOrDict
+from .common import MemoryBankIngestEventsOperation
+from .common import MemoryBankIngestEventsOperationDict
+from .common import MemoryBankIngestEventsOperationOrDict
+from .common import MemoryConjunctionFilter
+from .common import MemoryConjunctionFilterDict
+from .common import MemoryConjunctionFilterOrDict
+from .common import MemoryDict
+from .common import MemoryFilter
+from .common import MemoryFilterDict
+from .common import MemoryFilterOrDict
+from .common import MemoryGenerationTriggerConfig
+from .common import MemoryGenerationTriggerConfigDict
+from .common import MemoryGenerationTriggerConfigGenerationTriggerRule
+from .common import MemoryGenerationTriggerConfigGenerationTriggerRuleDict
+from .common import MemoryGenerationTriggerConfigGenerationTriggerRuleOrDict
+from .common import MemoryGenerationTriggerConfigOrDict
+from .common import MemoryMetadataMergeStrategy
+from .common import MemoryMetadataValue
+from .common import MemoryMetadataValueDict
+from .common import MemoryMetadataValueOrDict
+from .common import MemoryOrDict
+from .common import MemoryProfile
+from .common import MemoryProfileDict
+from .common import MemoryProfileOrDict
+from .common import MemoryRevision
+from .common import MemoryRevisionDict
+from .common import MemoryRevisionOrDict
+from .common import MemoryStructuredContent
+from .common import MemoryStructuredContentDict
+from .common import MemoryStructuredContentOrDict
+from .common import MemoryTopicId
+from .common import MemoryTopicIdDict
+from .common import MemoryTopicIdOrDict
+from .common import MemoryType
+from .common import Message
+from .common import MessageDict
+from .common import Metadata
+from .common import MetadataDict
+from .common import MetadataOrDict
+from .common import Metric
+from .common import MetricDict
+from .common import MetricOrDict
+from .common import MetricPromptBuilder
+from .common import MetricResult
+from .common import MetricResultDict
+from .common import MetricResultOrDict
+from .common import MetricSource
+from .common import MetricSourceDict
+from .common import MetricSourceOrDict
+from .common import MetricxResult
+from .common import MetricxResultDict
+from .common import MetricxResultOrDict
+from .common import MultimodalDataset
+from .common import MultimodalDatasetDict
+from .common import MultimodalDatasetOperation
+from .common import MultimodalDatasetOperationDict
+from .common import MultimodalDatasetOperationOrDict
+from .common import MultimodalDatasetOrDict
+from .common import NfsMount
+from .common import NfsMountDict
+from .common import NfsMountOrDict
+from .common import ObservabilityEvalCase
+from .common import ObservabilityEvalCaseDict
+from .common import ObservabilityEvalCaseOrDict
+from .common import Operator
+from .common import OptimizationMethod
+from .common import OptimizeConfig
+from .common import OptimizeConfigDict
+from .common import OptimizeConfigOrDict
+from .common import OptimizeJobConfig
+from .common import OptimizeJobConfigDict
+from .common import OptimizeJobConfigOrDict
+from .common import OptimizeResponse
+from .common import OptimizeResponseDict
+from .common import OptimizeResponseEndpoint
+from .common import OptimizeResponseEndpointDict
+from .common import OptimizeResponseEndpointOrDict
+from .common import OptimizeResponseOrDict
+from .common import OptimizeTarget
+from .common import PairwiseMetricInput
+from .common import PairwiseMetricInputDict
+from .common import PairwiseMetricInputOrDict
+from .common import PairwiseMetricInstance
+from .common import PairwiseMetricInstanceDict
+from .common import PairwiseMetricInstanceOrDict
+from .common import ParsedResponseUnion
+from .common import PointwiseMetricInput
+from .common import PointwiseMetricInputDict
+from .common import PointwiseMetricInputOrDict
+from .common import PointwiseMetricInstance
+from .common import PointwiseMetricInstanceDict
+from .common import PointwiseMetricInstanceOrDict
+from .common import PostSnapshotAction
+from .common import Prompt
+from .common import PromptData
+from .common import PromptDataDict
+from .common import PromptDataOrDict
+from .common import PromptDict
+from .common import PromptOptimizerConfig
+from .common import PromptOptimizerConfigDict
+from .common import PromptOptimizerConfigOrDict
+from .common import PromptOptimizerMethod
+from .common import PromptOrDict
+from .common import PromptRef
+from .common import PromptRefDict
+from .common import PromptRefOrDict
+from .common import PromptTemplate
+from .common import PromptTemplateData
+from .common import PromptTemplateDataDict
+from .common import PromptTemplateDataOrDict
+from .common import PromptTemplateDict
+from .common import PromptTemplateOrDict
+from .common import PromptVersionRef
+from .common import PromptVersionRefDict
+from .common import PromptVersionRefOrDict
+from .common import Protocol
+from .common import PscInterfaceConfig
+from .common import PscInterfaceConfigDict
+from .common import PscInterfaceConfigOrDict
+from .common import PurgeAgentEngineMemoriesConfig
+from .common import PurgeAgentEngineMemoriesConfigDict
+from .common import PurgeAgentEngineMemoriesConfigOrDict
+from .common import PurgeMemoriesResponse
+from .common import PurgeMemoriesResponseDict
+from .common import PurgeMemoriesResponseOrDict
+from .common import PythonPackageSpec
+from .common import PythonPackageSpecDict
+from .common import PythonPackageSpecOrDict
+from .common import QueryAgentEngineConfig
+from .common import QueryAgentEngineConfigDict
+from .common import QueryAgentEngineConfigOrDict
+from .common import QueryAgentEngineRuntimeRevisionConfig
+from .common import QueryAgentEngineRuntimeRevisionConfigDict
+from .common import QueryAgentEngineRuntimeRevisionConfigOrDict
+from .common import QueryReasoningEngineResponse
+from .common import QueryReasoningEngineResponseDict
+from .common import QueryReasoningEngineResponseOrDict
+from .common import ReasoningEngine
+from .common import ReasoningEngineContextSpec
+from .common import ReasoningEngineContextSpecDict
+from .common import ReasoningEngineContextSpecMemoryBankConfig
+from .common import ReasoningEngineContextSpecMemoryBankConfigDict
+from .common import ReasoningEngineContextSpecMemoryBankConfigGenerationConfig
+from .common import ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict
+from .common import ReasoningEngineContextSpecMemoryBankConfigGenerationConfigOrDict
+from .common import ReasoningEngineContextSpecMemoryBankConfigOrDict
+from .common import ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig
+from .common import ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict
+from .common import (
+ ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigOrDict,
+)
+from .common import ReasoningEngineContextSpecMemoryBankConfigTtlConfig
+from .common import ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict
+from .common import ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig
+from .common import (
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict,
+)
+from .common import (
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigOrDict,
+)
+from .common import ReasoningEngineContextSpecMemoryBankConfigTtlConfigOrDict
+from .common import ReasoningEngineContextSpecOrDict
+from .common import ReasoningEngineDict
+from .common import ReasoningEngineOrDict
+from .common import ReasoningEngineRuntimeRevision
+from .common import ReasoningEngineRuntimeRevisionDict
+from .common import ReasoningEngineRuntimeRevisionOrDict
+from .common import ReasoningEngineSpec
+from .common import ReasoningEngineSpecContainerSpec
+from .common import ReasoningEngineSpecContainerSpecDict
+from .common import ReasoningEngineSpecContainerSpecOrDict
+from .common import ReasoningEngineSpecDeploymentSpec
+from .common import ReasoningEngineSpecDeploymentSpecAgentGatewayConfig
+from .common import (
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfig,
+)
+from .common import (
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigDict,
+)
+from .common import (
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigOrDict,
+)
+from .common import (
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfig,
+)
+from .common import (
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigDict,
+)
+from .common import (
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigOrDict,
+)
+from .common import ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
+from .common import ReasoningEngineSpecDeploymentSpecAgentGatewayConfigOrDict
+from .common import ReasoningEngineSpecDeploymentSpecDict
+from .common import ReasoningEngineSpecDeploymentSpecOrDict
+from .common import ReasoningEngineSpecDict
+from .common import ReasoningEngineSpecOrDict
+from .common import ReasoningEngineSpecPackageSpec
+from .common import ReasoningEngineSpecPackageSpecDict
+from .common import ReasoningEngineSpecPackageSpecOrDict
+from .common import ReasoningEngineSpecSourceCodeSpec
+from .common import ReasoningEngineSpecSourceCodeSpecAgentConfigSource
+from .common import ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfig
+from .common import ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigDict
+from .common import ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigOrDict
+from .common import ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict
+from .common import ReasoningEngineSpecSourceCodeSpecAgentConfigSourceOrDict
+from .common import ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig
+from .common import ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
+from .common import ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigOrDict
+from .common import ReasoningEngineSpecSourceCodeSpecDeveloperConnectSource
+from .common import ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceDict
+from .common import ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceOrDict
+from .common import ReasoningEngineSpecSourceCodeSpecDict
+from .common import ReasoningEngineSpecSourceCodeSpecImageSpec
+from .common import ReasoningEngineSpecSourceCodeSpecImageSpecDict
+from .common import ReasoningEngineSpecSourceCodeSpecImageSpecOrDict
+from .common import ReasoningEngineSpecSourceCodeSpecInlineSource
+from .common import ReasoningEngineSpecSourceCodeSpecInlineSourceDict
+from .common import ReasoningEngineSpecSourceCodeSpecInlineSourceOrDict
+from .common import ReasoningEngineSpecSourceCodeSpecOrDict
+from .common import ReasoningEngineSpecSourceCodeSpecPythonSpec
+from .common import ReasoningEngineSpecSourceCodeSpecPythonSpecDict
+from .common import ReasoningEngineSpecSourceCodeSpecPythonSpecOrDict
+from .common import ReasoningEngineTrafficConfig
+from .common import ReasoningEngineTrafficConfigDict
+from .common import ReasoningEngineTrafficConfigOrDict
+from .common import ReasoningEngineTrafficConfigTrafficSplitAlwaysLatest
+from .common import ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestDict
+from .common import ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestOrDict
+from .common import ReasoningEngineTrafficConfigTrafficSplitManual
+from .common import ReasoningEngineTrafficConfigTrafficSplitManualDict
+from .common import ReasoningEngineTrafficConfigTrafficSplitManualOrDict
+from .common import ReasoningEngineTrafficConfigTrafficSplitManualTarget
+from .common import ReasoningEngineTrafficConfigTrafficSplitManualTargetDict
+from .common import ReasoningEngineTrafficConfigTrafficSplitManualTargetOrDict
+from .common import RedTeamingAnalysisConfig
+from .common import RedTeamingAnalysisConfigDict
+from .common import RedTeamingAnalysisConfigOrDict
+from .common import RedTeamingAnalysisResult
+from .common import RedTeamingAnalysisResultDict
+from .common import RedTeamingAnalysisResultOrDict
+from .common import ReservationAffinity
+from .common import ReservationAffinityDict
+from .common import ReservationAffinityOrDict
+from .common import ResponseCandidate
+from .common import ResponseCandidateDict
+from .common import ResponseCandidateOrDict
+from .common import ResponseCandidateResult
+from .common import ResponseCandidateResultDict
+from .common import ResponseCandidateResultOrDict
+from .common import RestoreVersionConfig
+from .common import RestoreVersionConfigDict
+from .common import RestoreVersionConfigOrDict
+from .common import RestoreVersionOperation
+from .common import RestoreVersionOperationDict
+from .common import RestoreVersionOperationOrDict
+from .common import RetrieveAgentEngineMemoriesConfig
+from .common import RetrieveAgentEngineMemoriesConfigDict
+from .common import RetrieveAgentEngineMemoriesConfigOrDict
+from .common import RetrievedSkill
+from .common import RetrievedSkillDict
+from .common import RetrievedSkillOrDict
+from .common import RetrieveMemoriesRequestSimilaritySearchParams
+from .common import RetrieveMemoriesRequestSimilaritySearchParamsDict
+from .common import RetrieveMemoriesRequestSimilaritySearchParamsOrDict
+from .common import RetrieveMemoriesRequestSimpleRetrievalParams
+from .common import RetrieveMemoriesRequestSimpleRetrievalParamsDict
+from .common import RetrieveMemoriesRequestSimpleRetrievalParamsOrDict
+from .common import RetrieveMemoriesResponse
+from .common import RetrieveMemoriesResponseDict
+from .common import RetrieveMemoriesResponseOrDict
+from .common import RetrieveMemoriesResponseRetrievedMemory
+from .common import RetrieveMemoriesResponseRetrievedMemoryDict
+from .common import RetrieveMemoriesResponseRetrievedMemoryOrDict
+from .common import RetrieveMemoryProfilesConfig
+from .common import RetrieveMemoryProfilesConfigDict
+from .common import RetrieveMemoryProfilesConfigOrDict
+from .common import RetrieveProfilesResponse
+from .common import RetrieveProfilesResponseDict
+from .common import RetrieveProfilesResponseOrDict
+from .common import RetrieveSkillsConfig
+from .common import RetrieveSkillsConfigDict
+from .common import RetrieveSkillsConfigOrDict
+from .common import RetrieveSkillsResponse
+from .common import RetrieveSkillsResponseDict
+from .common import RetrieveSkillsResponseOrDict
+from .common import RollbackAgentEngineMemoryConfig
+from .common import RollbackAgentEngineMemoryConfigDict
+from .common import RollbackAgentEngineMemoryConfigOrDict
+from .common import RougeInput
+from .common import RougeInputDict
+from .common import RougeInputOrDict
+from .common import RougeInstance
+from .common import RougeInstanceDict
+from .common import RougeInstanceOrDict
+from .common import RougeResults
+from .common import RougeResultsDict
+from .common import RougeResultsOrDict
+from .common import Rubric
+from .common import RubricBasedMetricInput
+from .common import RubricBasedMetricInputDict
+from .common import RubricBasedMetricInputOrDict
+from .common import RubricBasedMetricInstance
+from .common import RubricBasedMetricInstanceDict
+from .common import RubricBasedMetricInstanceOrDict
+from .common import RubricBasedMetricResult
+from .common import RubricBasedMetricResultDict
+from .common import RubricBasedMetricResultOrDict
+from .common import RubricBasedMetricSpec
+from .common import RubricBasedMetricSpecDict
+from .common import RubricBasedMetricSpecOrDict
+from .common import RubricContent
+from .common import RubricContentDict
+from .common import RubricContentProperty
+from .common import RubricContentPropertyDict
+from .common import RubricDict
+from .common import RubricEnhancedContents
+from .common import RubricEnhancedContentsDict
+from .common import RubricEnhancedContentsOrDict
+from .common import RubricGenerationConfig
+from .common import RubricGenerationConfigDict
+from .common import RubricGenerationConfigOrDict
+from .common import RubricGroup
+from .common import RubricGroupDict
+from .common import RubricGroupOrDict
+from .common import RubricVerdict
+from .common import RubricVerdictDict
+from .common import RunQueryJobAgentEngineConfig
+from .common import RunQueryJobAgentEngineConfigDict
+from .common import RunQueryJobAgentEngineConfigOrDict
+from .common import RunQueryJobResult
+from .common import RunQueryJobResultDict
+from .common import RunQueryJobResultOrDict
+from .common import SamplingConfig
+from .common import SamplingConfigDict
+from .common import SamplingConfigOrDict
+from .common import SamplingMethod
+from .common import SandboxEnvironment
+from .common import SandboxEnvironmentConnectionInfo
+from .common import SandboxEnvironmentConnectionInfoDict
+from .common import SandboxEnvironmentConnectionInfoOrDict
+from .common import SandboxEnvironmentDict
+from .common import SandboxEnvironmentOrDict
+from .common import SandboxEnvironmentSnapshot
+from .common import SandboxEnvironmentSnapshotDict
+from .common import SandboxEnvironmentSnapshotOrDict
+from .common import SandboxEnvironmentSpec
+from .common import SandboxEnvironmentSpecCodeExecutionEnvironment
+from .common import SandboxEnvironmentSpecCodeExecutionEnvironmentDict
+from .common import SandboxEnvironmentSpecCodeExecutionEnvironmentOrDict
+from .common import SandboxEnvironmentSpecComputerUseEnvironment
+from .common import SandboxEnvironmentSpecComputerUseEnvironmentDict
+from .common import SandboxEnvironmentSpecComputerUseEnvironmentOrDict
+from .common import SandboxEnvironmentSpecDict
+from .common import SandboxEnvironmentSpecOrDict
+from .common import SandboxEnvironmentTemplate
+from .common import SandboxEnvironmentTemplateCustomContainerEnvironment
+from .common import SandboxEnvironmentTemplateCustomContainerEnvironmentDict
+from .common import SandboxEnvironmentTemplateCustomContainerEnvironmentOrDict
+from .common import SandboxEnvironmentTemplateCustomContainerSpec
+from .common import SandboxEnvironmentTemplateCustomContainerSpecDict
+from .common import SandboxEnvironmentTemplateCustomContainerSpecOrDict
+from .common import SandboxEnvironmentTemplateDefaultContainerEnvironment
+from .common import SandboxEnvironmentTemplateDefaultContainerEnvironmentDict
+from .common import SandboxEnvironmentTemplateDefaultContainerEnvironmentOrDict
+from .common import SandboxEnvironmentTemplateDict
+from .common import SandboxEnvironmentTemplateEgressControlConfig
+from .common import SandboxEnvironmentTemplateEgressControlConfigDict
+from .common import SandboxEnvironmentTemplateEgressControlConfigOrDict
+from .common import SandboxEnvironmentTemplateNetworkPort
+from .common import SandboxEnvironmentTemplateNetworkPortDict
+from .common import SandboxEnvironmentTemplateNetworkPortOrDict
+from .common import SandboxEnvironmentTemplateOperation
+from .common import SandboxEnvironmentTemplateOperationDict
+from .common import SandboxEnvironmentTemplateOperationOrDict
+from .common import SandboxEnvironmentTemplateOrDict
+from .common import SandboxEnvironmentTemplateResourceRequirements
+from .common import SandboxEnvironmentTemplateResourceRequirementsDict
+from .common import SandboxEnvironmentTemplateResourceRequirementsOrDict
+from .common import SandboxEnvironmentTemplateWarmPoolConfig
+from .common import SandboxEnvironmentTemplateWarmPoolConfigDict
+from .common import SandboxEnvironmentTemplateWarmPoolConfigOrDict
+from .common import SandboxState
+from .common import SavedQuery
+from .common import SavedQueryDict
+from .common import SavedQueryOrDict
+from .common import Scheduling
+from .common import SchedulingDict
+from .common import SchedulingOrDict
+from .common import SchemaPredictParamsGroundingConfig
+from .common import SchemaPredictParamsGroundingConfigDict
+from .common import SchemaPredictParamsGroundingConfigOrDict
+from .common import SchemaPredictParamsGroundingConfigSourceEntry
+from .common import SchemaPredictParamsGroundingConfigSourceEntryDict
+from .common import SchemaPredictParamsGroundingConfigSourceEntryOrDict
+from .common import SchemaPromptApiSchema
+from .common import SchemaPromptApiSchemaDict
+from .common import SchemaPromptApiSchemaOrDict
+from .common import SchemaPromptInstancePromptExecution
+from .common import SchemaPromptInstancePromptExecutionDict
+from .common import SchemaPromptInstancePromptExecutionOrDict
+from .common import SchemaPromptInstanceVariableValue
+from .common import SchemaPromptInstanceVariableValueDict
+from .common import SchemaPromptInstanceVariableValueOrDict
+from .common import SchemaPromptSpecAppBuilderData
+from .common import SchemaPromptSpecAppBuilderDataDict
+from .common import SchemaPromptSpecAppBuilderDataLinkedResource
+from .common import SchemaPromptSpecAppBuilderDataLinkedResourceDict
+from .common import SchemaPromptSpecAppBuilderDataLinkedResourceOrDict
+from .common import SchemaPromptSpecAppBuilderDataOrDict
+from .common import SchemaPromptSpecMultimodalPrompt
+from .common import SchemaPromptSpecMultimodalPromptDict
+from .common import SchemaPromptSpecMultimodalPromptOrDict
+from .common import SchemaPromptSpecPartList
+from .common import SchemaPromptSpecPartListDict
+from .common import SchemaPromptSpecPartListOrDict
+from .common import SchemaPromptSpecPromptMessage
+from .common import SchemaPromptSpecPromptMessageDict
+from .common import SchemaPromptSpecPromptMessageOrDict
+from .common import SchemaPromptSpecReferenceSentencePair
+from .common import SchemaPromptSpecReferenceSentencePairDict
+from .common import SchemaPromptSpecReferenceSentencePairList
+from .common import SchemaPromptSpecReferenceSentencePairListDict
+from .common import SchemaPromptSpecReferenceSentencePairListOrDict
+from .common import SchemaPromptSpecReferenceSentencePairOrDict
+from .common import SchemaPromptSpecStructuredPrompt
+from .common import SchemaPromptSpecStructuredPromptDict
+from .common import SchemaPromptSpecStructuredPromptOrDict
+from .common import SchemaPromptSpecTranslationExample
+from .common import SchemaPromptSpecTranslationExampleDict
+from .common import SchemaPromptSpecTranslationExampleOrDict
+from .common import SchemaPromptSpecTranslationFileInputSource
+from .common import SchemaPromptSpecTranslationFileInputSourceDict
+from .common import SchemaPromptSpecTranslationFileInputSourceOrDict
+from .common import SchemaPromptSpecTranslationGcsInputSource
+from .common import SchemaPromptSpecTranslationGcsInputSourceDict
+from .common import SchemaPromptSpecTranslationGcsInputSourceOrDict
+from .common import SchemaPromptSpecTranslationOption
+from .common import SchemaPromptSpecTranslationOptionDict
+from .common import SchemaPromptSpecTranslationOptionOrDict
+from .common import SchemaPromptSpecTranslationPrompt
+from .common import SchemaPromptSpecTranslationPromptDict
+from .common import SchemaPromptSpecTranslationPromptOrDict
+from .common import SchemaPromptSpecTranslationSentenceFileInput
+from .common import SchemaPromptSpecTranslationSentenceFileInputDict
+from .common import SchemaPromptSpecTranslationSentenceFileInputOrDict
+from .common import SchemaTablesDatasetMetadata
+from .common import SchemaTablesDatasetMetadataBigQuerySource
+from .common import SchemaTablesDatasetMetadataBigQuerySourceDict
+from .common import SchemaTablesDatasetMetadataBigQuerySourceOrDict
+from .common import SchemaTablesDatasetMetadataDict
+from .common import SchemaTablesDatasetMetadataInputConfig
+from .common import SchemaTablesDatasetMetadataInputConfigDict
+from .common import SchemaTablesDatasetMetadataInputConfigOrDict
+from .common import SchemaTablesDatasetMetadataOrDict
+from .common import SchemaTextPromptDatasetMetadata
+from .common import SchemaTextPromptDatasetMetadataDict
+from .common import SchemaTextPromptDatasetMetadataOrDict
+from .common import SecretEnvVar
+from .common import SecretEnvVarDict
+from .common import SecretEnvVarOrDict
+from .common import SecretRef
+from .common import SecretRefDict
+from .common import SecretRefOrDict
+from .common import Session
+from .common import SessionDict
+from .common import SessionEvent
+from .common import SessionEventDict
+from .common import SessionEventOrDict
+from .common import SessionOrDict
+from .common import Skill
+from .common import SkillDict
+from .common import SkillOperation
+from .common import SkillOperationDict
+from .common import SkillOperationOrDict
+from .common import SkillOrDict
+from .common import SkillRevision
+from .common import SkillRevisionDict
+from .common import SkillRevisionOrDict
+from .common import SkillState
+from .common import State
+from .common import Strategy
+from .common import StructuredMemoryConfig
+from .common import StructuredMemoryConfigDict
+from .common import StructuredMemoryConfigOrDict
+from .common import StructuredMemorySchemaConfig
+from .common import StructuredMemorySchemaConfigDict
+from .common import StructuredMemorySchemaConfigOrDict
+from .common import SummaryMetric
+from .common import SummaryMetricDict
+from .common import SummaryMetricOrDict
+from .common import TaskArtifact
+from .common import TaskArtifactChange
+from .common import TaskArtifactChangeDict
+from .common import TaskArtifactChangeOrDict
+from .common import TaskArtifactDict
+from .common import TaskArtifactOrDict
+from .common import TaskEvent
+from .common import TaskEventData
+from .common import TaskEventDataDict
+from .common import TaskEventDataOrDict
+from .common import TaskEventDict
+from .common import TaskEventOrDict
+from .common import TaskMessage
+from .common import TaskMessageDict
+from .common import TaskMessageOrDict
+from .common import TaskMetadataChange
+from .common import TaskMetadataChangeDict
+from .common import TaskMetadataChangeOrDict
+from .common import TaskOutput
+from .common import TaskOutputChange
+from .common import TaskOutputChangeDict
+from .common import TaskOutputChangeOrDict
+from .common import TaskOutputDict
+from .common import TaskOutputOrDict
+from .common import TaskStateChange
+from .common import TaskStateChangeDict
+from .common import TaskStateChangeOrDict
+from .common import TaskStatusDetails
+from .common import TaskStatusDetailsChange
+from .common import TaskStatusDetailsChangeDict
+from .common import TaskStatusDetailsChangeOrDict
+from .common import TaskStatusDetailsDict
+from .common import TaskStatusDetailsOrDict
+from .common import ToolCallValidInput
+from .common import ToolCallValidInputDict
+from .common import ToolCallValidInputOrDict
+from .common import ToolCallValidInstance
+from .common import ToolCallValidInstanceDict
+from .common import ToolCallValidInstanceOrDict
+from .common import ToolCallValidMetricValue
+from .common import ToolCallValidMetricValueDict
+from .common import ToolCallValidMetricValueOrDict
+from .common import ToolCallValidResults
+from .common import ToolCallValidResultsDict
+from .common import ToolCallValidResultsOrDict
+from .common import ToolCallValidSpec
+from .common import ToolCallValidSpecDict
+from .common import ToolCallValidSpecOrDict
+from .common import ToolNameMatchInput
+from .common import ToolNameMatchInputDict
+from .common import ToolNameMatchInputOrDict
+from .common import ToolNameMatchInstance
+from .common import ToolNameMatchInstanceDict
+from .common import ToolNameMatchInstanceOrDict
+from .common import ToolNameMatchMetricValue
+from .common import ToolNameMatchMetricValueDict
+from .common import ToolNameMatchMetricValueOrDict
+from .common import ToolNameMatchResults
+from .common import ToolNameMatchResultsDict
+from .common import ToolNameMatchResultsOrDict
+from .common import ToolNameMatchSpec
+from .common import ToolNameMatchSpecDict
+from .common import ToolNameMatchSpecOrDict
+from .common import ToolParameterKeyMatchInput
+from .common import ToolParameterKeyMatchInputDict
+from .common import ToolParameterKeyMatchInputOrDict
+from .common import ToolParameterKeyMatchInstance
+from .common import ToolParameterKeyMatchInstanceDict
+from .common import ToolParameterKeyMatchInstanceOrDict
+from .common import ToolParameterKeyMatchMetricValue
+from .common import ToolParameterKeyMatchMetricValueDict
+from .common import ToolParameterKeyMatchMetricValueOrDict
+from .common import ToolParameterKeyMatchResults
+from .common import ToolParameterKeyMatchResultsDict
+from .common import ToolParameterKeyMatchResultsOrDict
+from .common import ToolParameterKeyMatchSpec
+from .common import ToolParameterKeyMatchSpecDict
+from .common import ToolParameterKeyMatchSpecOrDict
+from .common import ToolParameterKVMatchInput
+from .common import ToolParameterKVMatchInputDict
+from .common import ToolParameterKVMatchInputOrDict
+from .common import ToolParameterKVMatchInstance
+from .common import ToolParameterKVMatchInstanceDict
+from .common import ToolParameterKVMatchInstanceOrDict
+from .common import ToolParameterKVMatchMetricValue
+from .common import ToolParameterKVMatchMetricValueDict
+from .common import ToolParameterKVMatchMetricValueOrDict
+from .common import ToolParameterKVMatchResults
+from .common import ToolParameterKVMatchResultsDict
+from .common import ToolParameterKVMatchResultsOrDict
+from .common import ToolParameterKVMatchSpec
+from .common import ToolParameterKVMatchSpecDict
+from .common import ToolParameterKVMatchSpecOrDict
+from .common import TuningResourceUsageAssessmentConfig
+from .common import TuningResourceUsageAssessmentConfigDict
+from .common import TuningResourceUsageAssessmentConfigOrDict
+from .common import TuningResourceUsageAssessmentResult
+from .common import TuningResourceUsageAssessmentResultDict
+from .common import TuningResourceUsageAssessmentResultOrDict
+from .common import TuningValidationAssessmentConfig
+from .common import TuningValidationAssessmentConfigDict
+from .common import TuningValidationAssessmentConfigOrDict
+from .common import TuningValidationAssessmentResult
+from .common import TuningValidationAssessmentResultDict
+from .common import TuningValidationAssessmentResultOrDict
+from .common import Type
+from .common import UnifiedMetric
+from .common import UnifiedMetricDict
+from .common import UnifiedMetricOrDict
+from .common import UpdateAgentEngineConfig
+from .common import UpdateAgentEngineConfigDict
+from .common import UpdateAgentEngineConfigOrDict
+from .common import UpdateAgentEngineMemoryConfig
+from .common import UpdateAgentEngineMemoryConfigDict
+from .common import UpdateAgentEngineMemoryConfigOrDict
+from .common import UpdateAgentEngineSessionConfig
+from .common import UpdateAgentEngineSessionConfigDict
+from .common import UpdateAgentEngineSessionConfigOrDict
+from .common import UpdatePromptConfig
+from .common import UpdatePromptConfigDict
+from .common import UpdatePromptConfigOrDict
+from .common import UpdateSkillConfig
+from .common import UpdateSkillConfigDict
+from .common import UpdateSkillConfigOrDict
+from .common import VertexBaseConfig
+from .common import VertexBaseConfigDict
+from .common import VertexBaseConfigOrDict
+from .common import VulnerableTool
+from .common import VulnerableToolDict
+from .common import VulnerableToolOrDict
+from .common import WinRateStats
+from .common import WinRateStatsDict
+from .common import WinRateStatsOrDict
+from .common import WorkerPoolSpec
+from .common import WorkerPoolSpecDict
+from .common import WorkerPoolSpecOrDict
+
+__all__ = [
+ "DeleteAgentEngineTaskConfig",
+ "DeleteAgentEngineTaskConfigDict",
+ "DeleteAgentEngineTaskConfigOrDict",
+ "GetAgentEngineTaskConfig",
+ "GetAgentEngineTaskConfigDict",
+ "GetAgentEngineTaskConfigOrDict",
+ "TaskArtifact",
+ "TaskArtifactDict",
+ "TaskArtifactOrDict",
+ "TaskOutput",
+ "TaskOutputDict",
+ "TaskOutputOrDict",
+ "TaskMessage",
+ "TaskMessageDict",
+ "TaskMessageOrDict",
+ "TaskStatusDetails",
+ "TaskStatusDetailsDict",
+ "TaskStatusDetailsOrDict",
+ "A2aTask",
+ "A2aTaskDict",
+ "A2aTaskOrDict",
+ "ListAgentEngineTasksConfig",
+ "ListAgentEngineTasksConfigDict",
+ "ListAgentEngineTasksConfigOrDict",
+ "ListAgentEngineTasksResponse",
+ "ListAgentEngineTasksResponseDict",
+ "ListAgentEngineTasksResponseOrDict",
+ "CreateAgentEngineTaskConfig",
+ "CreateAgentEngineTaskConfigDict",
+ "CreateAgentEngineTaskConfigOrDict",
+ "TaskMetadataChange",
+ "TaskMetadataChangeDict",
+ "TaskMetadataChangeOrDict",
+ "TaskArtifactChange",
+ "TaskArtifactChangeDict",
+ "TaskArtifactChangeOrDict",
+ "TaskOutputChange",
+ "TaskOutputChangeDict",
+ "TaskOutputChangeOrDict",
+ "TaskStateChange",
+ "TaskStateChangeDict",
+ "TaskStateChangeOrDict",
+ "TaskStatusDetailsChange",
+ "TaskStatusDetailsChangeDict",
+ "TaskStatusDetailsChangeOrDict",
+ "TaskEventData",
+ "TaskEventDataDict",
+ "TaskEventDataOrDict",
+ "TaskEvent",
+ "TaskEventDict",
+ "TaskEventOrDict",
+ "AppendAgentEngineTaskEventConfig",
+ "AppendAgentEngineTaskEventConfigDict",
+ "AppendAgentEngineTaskEventConfigOrDict",
+ "AppendAgentEngineTaskEventResponse",
+ "AppendAgentEngineTaskEventResponseDict",
+ "AppendAgentEngineTaskEventResponseOrDict",
+ "ListAgentEngineTaskEventsConfig",
+ "ListAgentEngineTaskEventsConfigDict",
+ "ListAgentEngineTaskEventsConfigOrDict",
+ "ListAgentEngineTaskEventsResponse",
+ "ListAgentEngineTaskEventsResponseDict",
+ "ListAgentEngineTaskEventsResponseOrDict",
+ "CreateEvaluationItemConfig",
+ "CreateEvaluationItemConfigDict",
+ "CreateEvaluationItemConfigOrDict",
+ "PromptTemplateData",
+ "PromptTemplateDataDict",
+ "PromptTemplateDataOrDict",
+ "EvaluationPrompt",
+ "EvaluationPromptDict",
+ "EvaluationPromptOrDict",
+ "CandidateResponse",
+ "CandidateResponseDict",
+ "CandidateResponseOrDict",
+ "EvaluationItemRequest",
+ "EvaluationItemRequestDict",
+ "EvaluationItemRequestOrDict",
+ "EvaluationItemResult",
+ "EvaluationItemResultDict",
+ "EvaluationItemResultOrDict",
+ "EvaluationItem",
+ "EvaluationItemDict",
+ "EvaluationItemOrDict",
+ "Metric",
+ "MetricDict",
+ "MetricOrDict",
+ "CreateEvaluationMetricConfig",
+ "CreateEvaluationMetricConfigDict",
+ "CreateEvaluationMetricConfigOrDict",
+ "CustomCodeExecutionSpec",
+ "CustomCodeExecutionSpecDict",
+ "CustomCodeExecutionSpecOrDict",
+ "UnifiedMetric",
+ "UnifiedMetricDict",
+ "UnifiedMetricOrDict",
+ "EvaluationMetric",
+ "EvaluationMetricDict",
+ "EvaluationMetricOrDict",
+ "SamplingConfig",
+ "SamplingConfigDict",
+ "SamplingConfigOrDict",
+ "BigQueryRequestSet",
+ "BigQueryRequestSetDict",
+ "BigQueryRequestSetOrDict",
+ "EvaluationRunDataSource",
+ "EvaluationRunDataSourceDict",
+ "EvaluationRunDataSourceOrDict",
+ "EvaluationRunMetric",
+ "EvaluationRunMetricDict",
+ "EvaluationRunMetricOrDict",
+ "EvaluationRunPromptTemplate",
+ "EvaluationRunPromptTemplateDict",
+ "EvaluationRunPromptTemplateOrDict",
+ "LossAnalysisConfig",
+ "LossAnalysisConfigDict",
+ "LossAnalysisConfigOrDict",
+ "EvaluationRunConfig",
+ "EvaluationRunConfigDict",
+ "EvaluationRunConfigOrDict",
+ "EvaluationRunAgentConfig",
+ "EvaluationRunAgentConfigDict",
+ "EvaluationRunAgentConfigOrDict",
+ "AgentRunConfig",
+ "AgentRunConfigDict",
+ "AgentRunConfigOrDict",
+ "EvaluationRunInferenceConfig",
+ "EvaluationRunInferenceConfigDict",
+ "EvaluationRunInferenceConfigOrDict",
+ "VulnerableTool",
+ "VulnerableToolDict",
+ "VulnerableToolOrDict",
+ "RedTeamingAnalysisConfig",
+ "RedTeamingAnalysisConfigDict",
+ "RedTeamingAnalysisConfigOrDict",
+ "AnalysisConfig",
+ "AnalysisConfigDict",
+ "AnalysisConfigOrDict",
+ "CreateEvaluationRunConfig",
+ "CreateEvaluationRunConfigDict",
+ "CreateEvaluationRunConfigOrDict",
+ "SummaryMetric",
+ "SummaryMetricDict",
+ "SummaryMetricOrDict",
+ "AttackCategoryResult",
+ "AttackCategoryResultDict",
+ "AttackCategoryResultOrDict",
+ "RedTeamingAnalysisResult",
+ "RedTeamingAnalysisResultDict",
+ "RedTeamingAnalysisResultOrDict",
+ "LossTaxonomyEntry",
+ "LossTaxonomyEntryDict",
+ "LossTaxonomyEntryOrDict",
+ "FailedRubric",
+ "FailedRubricDict",
+ "FailedRubricOrDict",
+ "LossExample",
+ "LossExampleDict",
+ "LossExampleOrDict",
+ "LossCluster",
+ "LossClusterDict",
+ "LossClusterOrDict",
+ "LossAnalysisResult",
+ "LossAnalysisResultDict",
+ "LossAnalysisResultOrDict",
+ "EvaluationRunResults",
+ "EvaluationRunResultsDict",
+ "EvaluationRunResultsOrDict",
+ "EvalCaseMetricResult",
+ "EvalCaseMetricResultDict",
+ "EvalCaseMetricResultOrDict",
+ "ResponseCandidateResult",
+ "ResponseCandidateResultDict",
+ "ResponseCandidateResultOrDict",
+ "EvalCaseResult",
+ "EvalCaseResultDict",
+ "EvalCaseResultOrDict",
+ "AggregatedMetricResult",
+ "AggregatedMetricResultDict",
+ "AggregatedMetricResultOrDict",
+ "WinRateStats",
+ "WinRateStatsDict",
+ "WinRateStatsOrDict",
+ "ResponseCandidate",
+ "ResponseCandidateDict",
+ "ResponseCandidateOrDict",
+ "EvalCase",
+ "EvalCaseDict",
+ "EvalCaseOrDict",
+ "EvaluationDataset",
+ "EvaluationDatasetDict",
+ "EvaluationDatasetOrDict",
+ "EvaluationRunMetadata",
+ "EvaluationRunMetadataDict",
+ "EvaluationRunMetadataOrDict",
+ "EvaluationResult",
+ "EvaluationResultDict",
+ "EvaluationResultOrDict",
+ "EvaluationRun",
+ "EvaluationRunDict",
+ "EvaluationRunOrDict",
+ "CreateEvaluationSetConfig",
+ "CreateEvaluationSetConfigDict",
+ "CreateEvaluationSetConfigOrDict",
+ "EvaluationSet",
+ "EvaluationSetDict",
+ "EvaluationSetOrDict",
+ "DeleteEvaluationMetricConfig",
+ "DeleteEvaluationMetricConfigDict",
+ "DeleteEvaluationMetricConfigOrDict",
+ "DeleteEvaluationMetricOperation",
+ "DeleteEvaluationMetricOperationDict",
+ "DeleteEvaluationMetricOperationOrDict",
+ "BleuInstance",
+ "BleuInstanceDict",
+ "BleuInstanceOrDict",
+ "BleuInput",
+ "BleuInputDict",
+ "BleuInputOrDict",
+ "ExactMatchInstance",
+ "ExactMatchInstanceDict",
+ "ExactMatchInstanceOrDict",
+ "ExactMatchSpec",
+ "ExactMatchSpecDict",
+ "ExactMatchSpecOrDict",
+ "ExactMatchInput",
+ "ExactMatchInputDict",
+ "ExactMatchInputOrDict",
+ "RougeInstance",
+ "RougeInstanceDict",
+ "RougeInstanceOrDict",
+ "RougeInput",
+ "RougeInputDict",
+ "RougeInputOrDict",
+ "ContentMap",
+ "ContentMapDict",
+ "ContentMapOrDict",
+ "PointwiseMetricInstance",
+ "PointwiseMetricInstanceDict",
+ "PointwiseMetricInstanceOrDict",
+ "PointwiseMetricInput",
+ "PointwiseMetricInputDict",
+ "PointwiseMetricInputOrDict",
+ "PairwiseMetricInstance",
+ "PairwiseMetricInstanceDict",
+ "PairwiseMetricInstanceOrDict",
+ "PairwiseMetricInput",
+ "PairwiseMetricInputDict",
+ "PairwiseMetricInputOrDict",
+ "ToolCallValidInstance",
+ "ToolCallValidInstanceDict",
+ "ToolCallValidInstanceOrDict",
+ "ToolCallValidSpec",
+ "ToolCallValidSpecDict",
+ "ToolCallValidSpecOrDict",
+ "ToolCallValidInput",
+ "ToolCallValidInputDict",
+ "ToolCallValidInputOrDict",
+ "ToolNameMatchInstance",
+ "ToolNameMatchInstanceDict",
+ "ToolNameMatchInstanceOrDict",
+ "ToolNameMatchSpec",
+ "ToolNameMatchSpecDict",
+ "ToolNameMatchSpecOrDict",
+ "ToolNameMatchInput",
+ "ToolNameMatchInputDict",
+ "ToolNameMatchInputOrDict",
+ "ToolParameterKeyMatchInstance",
+ "ToolParameterKeyMatchInstanceDict",
+ "ToolParameterKeyMatchInstanceOrDict",
+ "ToolParameterKeyMatchSpec",
+ "ToolParameterKeyMatchSpecDict",
+ "ToolParameterKeyMatchSpecOrDict",
+ "ToolParameterKeyMatchInput",
+ "ToolParameterKeyMatchInputDict",
+ "ToolParameterKeyMatchInputOrDict",
+ "ToolParameterKVMatchInstance",
+ "ToolParameterKVMatchInstanceDict",
+ "ToolParameterKVMatchInstanceOrDict",
+ "ToolParameterKVMatchSpec",
+ "ToolParameterKVMatchSpecDict",
+ "ToolParameterKVMatchSpecOrDict",
+ "ToolParameterKVMatchInput",
+ "ToolParameterKVMatchInputDict",
+ "ToolParameterKVMatchInputOrDict",
+ "MapInstance",
+ "MapInstanceDict",
+ "MapInstanceOrDict",
+ "EvaluationInstance",
+ "EvaluationInstanceDict",
+ "EvaluationInstanceOrDict",
+ "EvaluateInstancesConfig",
+ "EvaluateInstancesConfigDict",
+ "EvaluateInstancesConfigOrDict",
+ "RubricBasedMetricSpec",
+ "RubricBasedMetricSpecDict",
+ "RubricBasedMetricSpecOrDict",
+ "RubricEnhancedContents",
+ "RubricEnhancedContentsDict",
+ "RubricEnhancedContentsOrDict",
+ "RubricBasedMetricInstance",
+ "RubricBasedMetricInstanceDict",
+ "RubricBasedMetricInstanceOrDict",
+ "RubricBasedMetricInput",
+ "RubricBasedMetricInputDict",
+ "RubricBasedMetricInputOrDict",
+ "MetricSource",
+ "MetricSourceDict",
+ "MetricSourceOrDict",
+ "MetricResult",
+ "MetricResultDict",
+ "MetricResultOrDict",
+ "BleuResults",
+ "BleuResultsDict",
+ "BleuResultsOrDict",
+ "ExactMatchResults",
+ "ExactMatchResultsDict",
+ "ExactMatchResultsOrDict",
+ "RougeResults",
+ "RougeResultsDict",
+ "RougeResultsOrDict",
+ "RubricBasedMetricResult",
+ "RubricBasedMetricResultDict",
+ "RubricBasedMetricResultOrDict",
+ "CometResult",
+ "CometResultDict",
+ "CometResultOrDict",
+ "MetricxResult",
+ "MetricxResultDict",
+ "MetricxResultOrDict",
+ "ToolCallValidMetricValue",
+ "ToolCallValidMetricValueDict",
+ "ToolCallValidMetricValueOrDict",
+ "ToolCallValidResults",
+ "ToolCallValidResultsDict",
+ "ToolCallValidResultsOrDict",
+ "ToolNameMatchMetricValue",
+ "ToolNameMatchMetricValueDict",
+ "ToolNameMatchMetricValueOrDict",
+ "ToolNameMatchResults",
+ "ToolNameMatchResultsDict",
+ "ToolNameMatchResultsOrDict",
+ "ToolParameterKeyMatchMetricValue",
+ "ToolParameterKeyMatchMetricValueDict",
+ "ToolParameterKeyMatchMetricValueOrDict",
+ "ToolParameterKeyMatchResults",
+ "ToolParameterKeyMatchResultsDict",
+ "ToolParameterKeyMatchResultsOrDict",
+ "ToolParameterKVMatchMetricValue",
+ "ToolParameterKVMatchMetricValueDict",
+ "ToolParameterKVMatchMetricValueOrDict",
+ "ToolParameterKVMatchResults",
+ "ToolParameterKVMatchResultsDict",
+ "ToolParameterKVMatchResultsOrDict",
+ "EvaluateInstancesResponse",
+ "EvaluateInstancesResponseDict",
+ "EvaluateInstancesResponseOrDict",
+ "GenerateUserScenariosConfig",
+ "GenerateUserScenariosConfigDict",
+ "GenerateUserScenariosConfigOrDict",
+ "GenerateUserScenariosResponse",
+ "GenerateUserScenariosResponseDict",
+ "GenerateUserScenariosResponseOrDict",
+ "GenerateLossClustersConfig",
+ "GenerateLossClustersConfigDict",
+ "GenerateLossClustersConfigOrDict",
+ "GenerateLossClustersResponse",
+ "GenerateLossClustersResponseDict",
+ "GenerateLossClustersResponseOrDict",
+ "GenerateLossClustersOperation",
+ "GenerateLossClustersOperationDict",
+ "GenerateLossClustersOperationOrDict",
+ "RubricGenerationConfig",
+ "RubricGenerationConfigDict",
+ "RubricGenerationConfigOrDict",
+ "GenerateInstanceRubricsResponse",
+ "GenerateInstanceRubricsResponseDict",
+ "GenerateInstanceRubricsResponseOrDict",
+ "GetEvaluationMetricConfig",
+ "GetEvaluationMetricConfigDict",
+ "GetEvaluationMetricConfigOrDict",
+ "GetEvaluationRunConfig",
+ "GetEvaluationRunConfigDict",
+ "GetEvaluationRunConfigOrDict",
+ "GetEvaluationSetConfig",
+ "GetEvaluationSetConfigDict",
+ "GetEvaluationSetConfigOrDict",
+ "GetEvaluationItemConfig",
+ "GetEvaluationItemConfigDict",
+ "GetEvaluationItemConfigOrDict",
+ "ListEvaluationMetricsConfig",
+ "ListEvaluationMetricsConfigDict",
+ "ListEvaluationMetricsConfigOrDict",
+ "ListEvaluationMetricsResponse",
+ "ListEvaluationMetricsResponseDict",
+ "ListEvaluationMetricsResponseOrDict",
+ "OptimizeConfig",
+ "OptimizeConfigDict",
+ "OptimizeConfigOrDict",
+ "OptimizeResponseEndpoint",
+ "OptimizeResponseEndpointDict",
+ "OptimizeResponseEndpointOrDict",
+ "DnsPeeringConfig",
+ "DnsPeeringConfigDict",
+ "DnsPeeringConfigOrDict",
+ "PscInterfaceConfig",
+ "PscInterfaceConfigDict",
+ "PscInterfaceConfigOrDict",
+ "Scheduling",
+ "SchedulingDict",
+ "SchedulingOrDict",
+ "EnvVar",
+ "EnvVarDict",
+ "EnvVarOrDict",
+ "ContainerSpec",
+ "ContainerSpecDict",
+ "ContainerSpecOrDict",
+ "DiskSpec",
+ "DiskSpecDict",
+ "DiskSpecOrDict",
+ "LustreMount",
+ "LustreMountDict",
+ "LustreMountOrDict",
+ "ReservationAffinity",
+ "ReservationAffinityDict",
+ "ReservationAffinityOrDict",
+ "MachineSpec",
+ "MachineSpecDict",
+ "MachineSpecOrDict",
+ "NfsMount",
+ "NfsMountDict",
+ "NfsMountOrDict",
+ "PythonPackageSpec",
+ "PythonPackageSpecDict",
+ "PythonPackageSpecOrDict",
+ "WorkerPoolSpec",
+ "WorkerPoolSpecDict",
+ "WorkerPoolSpecOrDict",
+ "CustomJobSpec",
+ "CustomJobSpecDict",
+ "CustomJobSpecOrDict",
+ "CustomJob",
+ "CustomJobDict",
+ "CustomJobOrDict",
+ "VertexBaseConfig",
+ "VertexBaseConfigDict",
+ "VertexBaseConfigOrDict",
+ "CancelQueryJobAgentEngineConfig",
+ "CancelQueryJobAgentEngineConfigDict",
+ "CancelQueryJobAgentEngineConfigOrDict",
+ "CancelQueryJobResult",
+ "CancelQueryJobResultDict",
+ "CancelQueryJobResultOrDict",
+ "CheckQueryJobAgentEngineConfig",
+ "CheckQueryJobAgentEngineConfigDict",
+ "CheckQueryJobAgentEngineConfigOrDict",
+ "CheckQueryJobResult",
+ "CheckQueryJobResultDict",
+ "CheckQueryJobResultOrDict",
+ "_RunQueryJobAgentEngineConfig",
+ "_RunQueryJobAgentEngineConfigDict",
+ "_RunQueryJobAgentEngineConfigOrDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventOrDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceOrDict",
+ "MemoryTopicId",
+ "MemoryTopicIdDict",
+ "MemoryTopicIdOrDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryOrDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExample",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleDict",
+ "MemoryBankCustomizationConfigGenerateMemoriesExampleOrDict",
+ "MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic",
+ "MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict",
+ "MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicOrDict",
+ "MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic",
+ "MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict",
+ "MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicOrDict",
+ "MemoryBankCustomizationConfigMemoryTopic",
+ "MemoryBankCustomizationConfigMemoryTopicDict",
+ "MemoryBankCustomizationConfigMemoryTopicOrDict",
+ "MemoryBankCustomizationConfigConsolidationConfig",
+ "MemoryBankCustomizationConfigConsolidationConfigDict",
+ "MemoryBankCustomizationConfigConsolidationConfigOrDict",
+ "MemoryBankCustomizationConfig",
+ "MemoryBankCustomizationConfigDict",
+ "MemoryBankCustomizationConfigOrDict",
+ "MemoryGenerationTriggerConfigGenerationTriggerRule",
+ "MemoryGenerationTriggerConfigGenerationTriggerRuleDict",
+ "MemoryGenerationTriggerConfigGenerationTriggerRuleOrDict",
+ "MemoryGenerationTriggerConfig",
+ "MemoryGenerationTriggerConfigDict",
+ "MemoryGenerationTriggerConfigOrDict",
+ "ReasoningEngineContextSpecMemoryBankConfigGenerationConfig",
+ "ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict",
+ "ReasoningEngineContextSpecMemoryBankConfigGenerationConfigOrDict",
+ "ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig",
+ "ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict",
+ "ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigOrDict",
+ "ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig",
+ "ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict",
+ "ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigOrDict",
+ "ReasoningEngineContextSpecMemoryBankConfigTtlConfig",
+ "ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict",
+ "ReasoningEngineContextSpecMemoryBankConfigTtlConfigOrDict",
+ "StructuredMemorySchemaConfig",
+ "StructuredMemorySchemaConfigDict",
+ "StructuredMemorySchemaConfigOrDict",
+ "StructuredMemoryConfig",
+ "StructuredMemoryConfigDict",
+ "StructuredMemoryConfigOrDict",
+ "ReasoningEngineContextSpecMemoryBankConfig",
+ "ReasoningEngineContextSpecMemoryBankConfigDict",
+ "ReasoningEngineContextSpecMemoryBankConfigOrDict",
+ "ReasoningEngineContextSpec",
+ "ReasoningEngineContextSpecDict",
+ "ReasoningEngineContextSpecOrDict",
+ "SecretRef",
+ "SecretRefDict",
+ "SecretRefOrDict",
+ "SecretEnvVar",
+ "SecretEnvVarDict",
+ "SecretEnvVarOrDict",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfig",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigDict",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigOrDict",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfig",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigDict",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigOrDict",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfig",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict",
+ "ReasoningEngineSpecDeploymentSpecAgentGatewayConfigOrDict",
+ "KeepAliveProbeHttpGet",
+ "KeepAliveProbeHttpGetDict",
+ "KeepAliveProbeHttpGetOrDict",
+ "KeepAliveProbe",
+ "KeepAliveProbeDict",
+ "KeepAliveProbeOrDict",
+ "ReasoningEngineSpecDeploymentSpec",
+ "ReasoningEngineSpecDeploymentSpecDict",
+ "ReasoningEngineSpecDeploymentSpecOrDict",
+ "ReasoningEngineSpecPackageSpec",
+ "ReasoningEngineSpecPackageSpecDict",
+ "ReasoningEngineSpecPackageSpecOrDict",
+ "ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfig",
+ "ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigDict",
+ "ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigOrDict",
+ "ReasoningEngineSpecSourceCodeSpecInlineSource",
+ "ReasoningEngineSpecSourceCodeSpecInlineSourceDict",
+ "ReasoningEngineSpecSourceCodeSpecInlineSourceOrDict",
+ "ReasoningEngineSpecSourceCodeSpecAgentConfigSource",
+ "ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict",
+ "ReasoningEngineSpecSourceCodeSpecAgentConfigSourceOrDict",
+ "ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig",
+ "ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict",
+ "ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigOrDict",
+ "ReasoningEngineSpecSourceCodeSpecDeveloperConnectSource",
+ "ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceDict",
+ "ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceOrDict",
+ "ReasoningEngineSpecSourceCodeSpecImageSpec",
+ "ReasoningEngineSpecSourceCodeSpecImageSpecDict",
+ "ReasoningEngineSpecSourceCodeSpecImageSpecOrDict",
+ "ReasoningEngineSpecSourceCodeSpecPythonSpec",
+ "ReasoningEngineSpecSourceCodeSpecPythonSpecDict",
+ "ReasoningEngineSpecSourceCodeSpecPythonSpecOrDict",
+ "ReasoningEngineSpecSourceCodeSpec",
+ "ReasoningEngineSpecSourceCodeSpecDict",
+ "ReasoningEngineSpecSourceCodeSpecOrDict",
+ "ReasoningEngineSpecContainerSpec",
+ "ReasoningEngineSpecContainerSpecDict",
+ "ReasoningEngineSpecContainerSpecOrDict",
+ "ReasoningEngineSpec",
+ "ReasoningEngineSpecDict",
+ "ReasoningEngineSpecOrDict",
+ "ReasoningEngineTrafficConfigTrafficSplitAlwaysLatest",
+ "ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestDict",
+ "ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestOrDict",
+ "ReasoningEngineTrafficConfigTrafficSplitManualTarget",
+ "ReasoningEngineTrafficConfigTrafficSplitManualTargetDict",
+ "ReasoningEngineTrafficConfigTrafficSplitManualTargetOrDict",
+ "ReasoningEngineTrafficConfigTrafficSplitManual",
+ "ReasoningEngineTrafficConfigTrafficSplitManualDict",
+ "ReasoningEngineTrafficConfigTrafficSplitManualOrDict",
+ "ReasoningEngineTrafficConfig",
+ "ReasoningEngineTrafficConfigDict",
+ "ReasoningEngineTrafficConfigOrDict",
+ "ReasoningEngine",
+ "ReasoningEngineDict",
+ "ReasoningEngineOrDict",
+ "AgentEngineOperation",
+ "AgentEngineOperationDict",
+ "AgentEngineOperationOrDict",
+ "CreateAgentEngineConfig",
+ "CreateAgentEngineConfigDict",
+ "CreateAgentEngineConfigOrDict",
+ "DeleteAgentEngineConfig",
+ "DeleteAgentEngineConfigDict",
+ "DeleteAgentEngineConfigOrDict",
+ "DeleteAgentEngineOperation",
+ "DeleteAgentEngineOperationDict",
+ "DeleteAgentEngineOperationOrDict",
+ "GetAgentEngineConfig",
+ "GetAgentEngineConfigDict",
+ "GetAgentEngineConfigOrDict",
+ "ListAgentEngineConfig",
+ "ListAgentEngineConfigDict",
+ "ListAgentEngineConfigOrDict",
+ "ListReasoningEnginesResponse",
+ "ListReasoningEnginesResponseDict",
+ "ListReasoningEnginesResponseOrDict",
+ "GetAgentEngineOperationConfig",
+ "GetAgentEngineOperationConfigDict",
+ "GetAgentEngineOperationConfigOrDict",
+ "QueryAgentEngineConfig",
+ "QueryAgentEngineConfigDict",
+ "QueryAgentEngineConfigOrDict",
+ "QueryReasoningEngineResponse",
+ "QueryReasoningEngineResponseDict",
+ "QueryReasoningEngineResponseOrDict",
+ "UpdateAgentEngineConfig",
+ "UpdateAgentEngineConfigDict",
+ "UpdateAgentEngineConfigOrDict",
+ "MemoryMetadataValue",
+ "MemoryMetadataValueDict",
+ "MemoryMetadataValueOrDict",
+ "AgentEngineMemoryConfig",
+ "AgentEngineMemoryConfigDict",
+ "AgentEngineMemoryConfigOrDict",
+ "MemoryStructuredContent",
+ "MemoryStructuredContentDict",
+ "MemoryStructuredContentOrDict",
+ "Memory",
+ "MemoryDict",
+ "MemoryOrDict",
+ "AgentEngineMemoryOperation",
+ "AgentEngineMemoryOperationDict",
+ "AgentEngineMemoryOperationOrDict",
+ "DeleteAgentEngineMemoryConfig",
+ "DeleteAgentEngineMemoryConfigDict",
+ "DeleteAgentEngineMemoryConfigOrDict",
+ "DeleteAgentEngineMemoryOperation",
+ "DeleteAgentEngineMemoryOperationDict",
+ "DeleteAgentEngineMemoryOperationOrDict",
+ "GenerateMemoriesRequestVertexSessionSource",
+ "GenerateMemoriesRequestVertexSessionSourceDict",
+ "GenerateMemoriesRequestVertexSessionSourceOrDict",
+ "GenerateMemoriesRequestDirectContentsSourceEvent",
+ "GenerateMemoriesRequestDirectContentsSourceEventDict",
+ "GenerateMemoriesRequestDirectContentsSourceEventOrDict",
+ "GenerateMemoriesRequestDirectContentsSource",
+ "GenerateMemoriesRequestDirectContentsSourceDict",
+ "GenerateMemoriesRequestDirectContentsSourceOrDict",
+ "GenerateMemoriesRequestDirectMemoriesSourceDirectMemory",
+ "GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict",
+ "GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryOrDict",
+ "GenerateMemoriesRequestDirectMemoriesSource",
+ "GenerateMemoriesRequestDirectMemoriesSourceDict",
+ "GenerateMemoriesRequestDirectMemoriesSourceOrDict",
+ "GenerateAgentEngineMemoriesConfig",
+ "GenerateAgentEngineMemoriesConfigDict",
+ "GenerateAgentEngineMemoriesConfigOrDict",
+ "GenerateMemoriesResponseGeneratedMemory",
+ "GenerateMemoriesResponseGeneratedMemoryDict",
+ "GenerateMemoriesResponseGeneratedMemoryOrDict",
+ "GenerateMemoriesResponse",
+ "GenerateMemoriesResponseDict",
+ "GenerateMemoriesResponseOrDict",
+ "AgentEngineGenerateMemoriesOperation",
+ "AgentEngineGenerateMemoriesOperationDict",
+ "AgentEngineGenerateMemoriesOperationOrDict",
+ "GetAgentEngineMemoryConfig",
+ "GetAgentEngineMemoryConfigDict",
+ "GetAgentEngineMemoryConfigOrDict",
+ "IngestionDirectContentsSourceEvent",
+ "IngestionDirectContentsSourceEventDict",
+ "IngestionDirectContentsSourceEventOrDict",
+ "IngestionDirectContentsSource",
+ "IngestionDirectContentsSourceDict",
+ "IngestionDirectContentsSourceOrDict",
+ "IngestEventsConfig",
+ "IngestEventsConfigDict",
+ "IngestEventsConfigOrDict",
+ "MemoryBankIngestEventsOperation",
+ "MemoryBankIngestEventsOperationDict",
+ "MemoryBankIngestEventsOperationOrDict",
+ "ListAgentEngineMemoryConfig",
+ "ListAgentEngineMemoryConfigDict",
+ "ListAgentEngineMemoryConfigOrDict",
+ "ListReasoningEnginesMemoriesResponse",
+ "ListReasoningEnginesMemoriesResponseDict",
+ "ListReasoningEnginesMemoriesResponseOrDict",
+ "RetrieveMemoriesRequestSimilaritySearchParams",
+ "RetrieveMemoriesRequestSimilaritySearchParamsDict",
+ "RetrieveMemoriesRequestSimilaritySearchParamsOrDict",
+ "RetrieveMemoriesRequestSimpleRetrievalParams",
+ "RetrieveMemoriesRequestSimpleRetrievalParamsDict",
+ "RetrieveMemoriesRequestSimpleRetrievalParamsOrDict",
+ "MemoryFilter",
+ "MemoryFilterDict",
+ "MemoryFilterOrDict",
+ "MemoryConjunctionFilter",
+ "MemoryConjunctionFilterDict",
+ "MemoryConjunctionFilterOrDict",
+ "RetrieveAgentEngineMemoriesConfig",
+ "RetrieveAgentEngineMemoriesConfigDict",
+ "RetrieveAgentEngineMemoriesConfigOrDict",
+ "RetrieveMemoriesResponseRetrievedMemory",
+ "RetrieveMemoriesResponseRetrievedMemoryDict",
+ "RetrieveMemoriesResponseRetrievedMemoryOrDict",
+ "RetrieveMemoriesResponse",
+ "RetrieveMemoriesResponseDict",
+ "RetrieveMemoriesResponseOrDict",
+ "RetrieveMemoryProfilesConfig",
+ "RetrieveMemoryProfilesConfigDict",
+ "RetrieveMemoryProfilesConfigOrDict",
+ "MemoryProfile",
+ "MemoryProfileDict",
+ "MemoryProfileOrDict",
+ "RetrieveProfilesResponse",
+ "RetrieveProfilesResponseDict",
+ "RetrieveProfilesResponseOrDict",
+ "RollbackAgentEngineMemoryConfig",
+ "RollbackAgentEngineMemoryConfigDict",
+ "RollbackAgentEngineMemoryConfigOrDict",
+ "AgentEngineRollbackMemoryOperation",
+ "AgentEngineRollbackMemoryOperationDict",
+ "AgentEngineRollbackMemoryOperationOrDict",
+ "UpdateAgentEngineMemoryConfig",
+ "UpdateAgentEngineMemoryConfigDict",
+ "UpdateAgentEngineMemoryConfigOrDict",
+ "PurgeAgentEngineMemoriesConfig",
+ "PurgeAgentEngineMemoriesConfigDict",
+ "PurgeAgentEngineMemoriesConfigOrDict",
+ "PurgeMemoriesResponse",
+ "PurgeMemoriesResponseDict",
+ "PurgeMemoriesResponseOrDict",
+ "AgentEnginePurgeMemoriesOperation",
+ "AgentEnginePurgeMemoriesOperationDict",
+ "AgentEnginePurgeMemoriesOperationOrDict",
+ "GetAgentEngineMemoryRevisionConfig",
+ "GetAgentEngineMemoryRevisionConfigDict",
+ "GetAgentEngineMemoryRevisionConfigOrDict",
+ "IntermediateExtractedMemory",
+ "IntermediateExtractedMemoryDict",
+ "IntermediateExtractedMemoryOrDict",
+ "MemoryRevision",
+ "MemoryRevisionDict",
+ "MemoryRevisionOrDict",
+ "ListAgentEngineMemoryRevisionsConfig",
+ "ListAgentEngineMemoryRevisionsConfigDict",
+ "ListAgentEngineMemoryRevisionsConfigOrDict",
+ "ListAgentEngineMemoryRevisionsResponse",
+ "ListAgentEngineMemoryRevisionsResponseDict",
+ "ListAgentEngineMemoryRevisionsResponseOrDict",
+ "GetAgentEngineRuntimeRevisionConfig",
+ "GetAgentEngineRuntimeRevisionConfigDict",
+ "GetAgentEngineRuntimeRevisionConfigOrDict",
+ "ReasoningEngineRuntimeRevision",
+ "ReasoningEngineRuntimeRevisionDict",
+ "ReasoningEngineRuntimeRevisionOrDict",
+ "ListAgentEngineRuntimeRevisionsConfig",
+ "ListAgentEngineRuntimeRevisionsConfigDict",
+ "ListAgentEngineRuntimeRevisionsConfigOrDict",
+ "ListReasoningEnginesRuntimeRevisionsResponse",
+ "ListReasoningEnginesRuntimeRevisionsResponseDict",
+ "ListReasoningEnginesRuntimeRevisionsResponseOrDict",
+ "DeleteAgentEngineRuntimeRevisionConfig",
+ "DeleteAgentEngineRuntimeRevisionConfigDict",
+ "DeleteAgentEngineRuntimeRevisionConfigOrDict",
+ "DeleteAgentEngineRuntimeRevisionOperation",
+ "DeleteAgentEngineRuntimeRevisionOperationDict",
+ "DeleteAgentEngineRuntimeRevisionOperationOrDict",
+ "GetDeleteAgentEngineRuntimeRevisionOperationConfig",
+ "GetDeleteAgentEngineRuntimeRevisionOperationConfigDict",
+ "GetDeleteAgentEngineRuntimeRevisionOperationConfigOrDict",
+ "QueryAgentEngineRuntimeRevisionConfig",
+ "QueryAgentEngineRuntimeRevisionConfigDict",
+ "QueryAgentEngineRuntimeRevisionConfigOrDict",
+ "SandboxEnvironmentSpecCodeExecutionEnvironment",
+ "SandboxEnvironmentSpecCodeExecutionEnvironmentDict",
+ "SandboxEnvironmentSpecCodeExecutionEnvironmentOrDict",
+ "SandboxEnvironmentSpecComputerUseEnvironment",
+ "SandboxEnvironmentSpecComputerUseEnvironmentDict",
+ "SandboxEnvironmentSpecComputerUseEnvironmentOrDict",
+ "SandboxEnvironmentSpec",
+ "SandboxEnvironmentSpecDict",
+ "SandboxEnvironmentSpecOrDict",
+ "CreateAgentEngineSandboxConfig",
+ "CreateAgentEngineSandboxConfigDict",
+ "CreateAgentEngineSandboxConfigOrDict",
+ "SandboxEnvironmentConnectionInfo",
+ "SandboxEnvironmentConnectionInfoDict",
+ "SandboxEnvironmentConnectionInfoOrDict",
+ "SandboxEnvironment",
+ "SandboxEnvironmentDict",
+ "SandboxEnvironmentOrDict",
+ "AgentEngineSandboxOperation",
+ "AgentEngineSandboxOperationDict",
+ "AgentEngineSandboxOperationOrDict",
+ "DeleteAgentEngineSandboxConfig",
+ "DeleteAgentEngineSandboxConfigDict",
+ "DeleteAgentEngineSandboxConfigOrDict",
+ "DeleteAgentEngineSandboxOperation",
+ "DeleteAgentEngineSandboxOperationDict",
+ "DeleteAgentEngineSandboxOperationOrDict",
+ "Metadata",
+ "MetadataDict",
+ "MetadataOrDict",
+ "Chunk",
+ "ChunkDict",
+ "ChunkOrDict",
+ "ExecuteCodeAgentEngineSandboxConfig",
+ "ExecuteCodeAgentEngineSandboxConfigDict",
+ "ExecuteCodeAgentEngineSandboxConfigOrDict",
+ "ExecuteSandboxEnvironmentResponse",
+ "ExecuteSandboxEnvironmentResponseDict",
+ "ExecuteSandboxEnvironmentResponseOrDict",
+ "GetAgentEngineSandboxConfig",
+ "GetAgentEngineSandboxConfigDict",
+ "GetAgentEngineSandboxConfigOrDict",
+ "ListAgentEngineSandboxesConfig",
+ "ListAgentEngineSandboxesConfigDict",
+ "ListAgentEngineSandboxesConfigOrDict",
+ "ListAgentEngineSandboxesResponse",
+ "ListAgentEngineSandboxesResponseDict",
+ "ListAgentEngineSandboxesResponseOrDict",
+ "SandboxEnvironmentTemplateCustomContainerSpec",
+ "SandboxEnvironmentTemplateCustomContainerSpecDict",
+ "SandboxEnvironmentTemplateCustomContainerSpecOrDict",
+ "SandboxEnvironmentTemplateNetworkPort",
+ "SandboxEnvironmentTemplateNetworkPortDict",
+ "SandboxEnvironmentTemplateNetworkPortOrDict",
+ "SandboxEnvironmentTemplateResourceRequirements",
+ "SandboxEnvironmentTemplateResourceRequirementsDict",
+ "SandboxEnvironmentTemplateResourceRequirementsOrDict",
+ "SandboxEnvironmentTemplateCustomContainerEnvironment",
+ "SandboxEnvironmentTemplateCustomContainerEnvironmentDict",
+ "SandboxEnvironmentTemplateCustomContainerEnvironmentOrDict",
+ "SandboxEnvironmentTemplateDefaultContainerEnvironment",
+ "SandboxEnvironmentTemplateDefaultContainerEnvironmentDict",
+ "SandboxEnvironmentTemplateDefaultContainerEnvironmentOrDict",
+ "SandboxEnvironmentTemplateEgressControlConfig",
+ "SandboxEnvironmentTemplateEgressControlConfigDict",
+ "SandboxEnvironmentTemplateEgressControlConfigOrDict",
+ "CreateSandboxEnvironmentTemplateConfig",
+ "CreateSandboxEnvironmentTemplateConfigDict",
+ "CreateSandboxEnvironmentTemplateConfigOrDict",
+ "SandboxEnvironmentTemplateWarmPoolConfig",
+ "SandboxEnvironmentTemplateWarmPoolConfigDict",
+ "SandboxEnvironmentTemplateWarmPoolConfigOrDict",
+ "SandboxEnvironmentTemplate",
+ "SandboxEnvironmentTemplateDict",
+ "SandboxEnvironmentTemplateOrDict",
+ "SandboxEnvironmentTemplateOperation",
+ "SandboxEnvironmentTemplateOperationDict",
+ "SandboxEnvironmentTemplateOperationOrDict",
+ "DeleteSandboxEnvironmentTemplateConfig",
+ "DeleteSandboxEnvironmentTemplateConfigDict",
+ "DeleteSandboxEnvironmentTemplateConfigOrDict",
+ "DeleteSandboxEnvironmentTemplateOperation",
+ "DeleteSandboxEnvironmentTemplateOperationDict",
+ "DeleteSandboxEnvironmentTemplateOperationOrDict",
+ "GetSandboxEnvironmentTemplateConfig",
+ "GetSandboxEnvironmentTemplateConfigDict",
+ "GetSandboxEnvironmentTemplateConfigOrDict",
+ "ListSandboxEnvironmentTemplatesConfig",
+ "ListSandboxEnvironmentTemplatesConfigDict",
+ "ListSandboxEnvironmentTemplatesConfigOrDict",
+ "ListSandboxEnvironmentTemplatesResponse",
+ "ListSandboxEnvironmentTemplatesResponseDict",
+ "ListSandboxEnvironmentTemplatesResponseOrDict",
+ "CreateAgentEngineSandboxSnapshotConfig",
+ "CreateAgentEngineSandboxSnapshotConfigDict",
+ "CreateAgentEngineSandboxSnapshotConfigOrDict",
+ "SandboxEnvironmentSnapshot",
+ "SandboxEnvironmentSnapshotDict",
+ "SandboxEnvironmentSnapshotOrDict",
+ "AgentEngineSandboxSnapshotOperation",
+ "AgentEngineSandboxSnapshotOperationDict",
+ "AgentEngineSandboxSnapshotOperationOrDict",
+ "DeleteSandboxEnvironmentSnapshotConfig",
+ "DeleteSandboxEnvironmentSnapshotConfigDict",
+ "DeleteSandboxEnvironmentSnapshotConfigOrDict",
+ "DeleteSandboxEnvironmentSnapshotOperation",
+ "DeleteSandboxEnvironmentSnapshotOperationDict",
+ "DeleteSandboxEnvironmentSnapshotOperationOrDict",
+ "GetSandboxEnvironmentSnapshotConfig",
+ "GetSandboxEnvironmentSnapshotConfigDict",
+ "GetSandboxEnvironmentSnapshotConfigOrDict",
+ "ListSandboxEnvironmentSnapshotsConfig",
+ "ListSandboxEnvironmentSnapshotsConfigDict",
+ "ListSandboxEnvironmentSnapshotsConfigOrDict",
+ "ListSandboxEnvironmentSnapshotsResponse",
+ "ListSandboxEnvironmentSnapshotsResponseDict",
+ "ListSandboxEnvironmentSnapshotsResponseOrDict",
+ "CreateAgentEngineSessionConfig",
+ "CreateAgentEngineSessionConfigDict",
+ "CreateAgentEngineSessionConfigOrDict",
+ "Session",
+ "SessionDict",
+ "SessionOrDict",
+ "AgentEngineSessionOperation",
+ "AgentEngineSessionOperationDict",
+ "AgentEngineSessionOperationOrDict",
+ "DeleteAgentEngineSessionConfig",
+ "DeleteAgentEngineSessionConfigDict",
+ "DeleteAgentEngineSessionConfigOrDict",
+ "DeleteAgentEngineSessionOperation",
+ "DeleteAgentEngineSessionOperationDict",
+ "DeleteAgentEngineSessionOperationOrDict",
+ "GetAgentEngineSessionConfig",
+ "GetAgentEngineSessionConfigDict",
+ "GetAgentEngineSessionConfigOrDict",
+ "ListAgentEngineSessionsConfig",
+ "ListAgentEngineSessionsConfigDict",
+ "ListAgentEngineSessionsConfigOrDict",
+ "ListReasoningEnginesSessionsResponse",
+ "ListReasoningEnginesSessionsResponseDict",
+ "ListReasoningEnginesSessionsResponseOrDict",
+ "UpdateAgentEngineSessionConfig",
+ "UpdateAgentEngineSessionConfigDict",
+ "UpdateAgentEngineSessionConfigOrDict",
+ "EventActions",
+ "EventActionsDict",
+ "EventActionsOrDict",
+ "EventMetadata",
+ "EventMetadataDict",
+ "EventMetadataOrDict",
+ "AppendAgentEngineSessionEventConfig",
+ "AppendAgentEngineSessionEventConfigDict",
+ "AppendAgentEngineSessionEventConfigOrDict",
+ "AppendAgentEngineSessionEventResponse",
+ "AppendAgentEngineSessionEventResponseDict",
+ "AppendAgentEngineSessionEventResponseOrDict",
+ "ListAgentEngineSessionEventsConfig",
+ "ListAgentEngineSessionEventsConfigDict",
+ "ListAgentEngineSessionEventsConfigOrDict",
+ "SessionEvent",
+ "SessionEventDict",
+ "SessionEventOrDict",
+ "ListAgentEngineSessionEventsResponse",
+ "ListAgentEngineSessionEventsResponseDict",
+ "ListAgentEngineSessionEventsResponseOrDict",
+ "GeminiExample",
+ "GeminiExampleDict",
+ "GeminiExampleOrDict",
+ "GeminiTemplateConfig",
+ "GeminiTemplateConfigDict",
+ "GeminiTemplateConfigOrDict",
+ "GeminiRequestReadConfig",
+ "GeminiRequestReadConfigDict",
+ "GeminiRequestReadConfigOrDict",
+ "AssembleDatasetConfig",
+ "AssembleDatasetConfigDict",
+ "AssembleDatasetConfigOrDict",
+ "MultimodalDatasetOperation",
+ "MultimodalDatasetOperationDict",
+ "MultimodalDatasetOperationOrDict",
+ "TuningResourceUsageAssessmentConfig",
+ "TuningResourceUsageAssessmentConfigDict",
+ "TuningResourceUsageAssessmentConfigOrDict",
+ "TuningValidationAssessmentConfig",
+ "TuningValidationAssessmentConfigDict",
+ "TuningValidationAssessmentConfigOrDict",
+ "BatchPredictionResourceUsageAssessmentConfig",
+ "BatchPredictionResourceUsageAssessmentConfigDict",
+ "BatchPredictionResourceUsageAssessmentConfigOrDict",
+ "BatchPredictionValidationAssessmentConfig",
+ "BatchPredictionValidationAssessmentConfigDict",
+ "BatchPredictionValidationAssessmentConfigOrDict",
+ "AssessDatasetConfig",
+ "AssessDatasetConfigDict",
+ "AssessDatasetConfigOrDict",
+ "SchemaTablesDatasetMetadataBigQuerySource",
+ "SchemaTablesDatasetMetadataBigQuerySourceDict",
+ "SchemaTablesDatasetMetadataBigQuerySourceOrDict",
+ "SchemaTablesDatasetMetadataInputConfig",
+ "SchemaTablesDatasetMetadataInputConfigDict",
+ "SchemaTablesDatasetMetadataInputConfigOrDict",
+ "SchemaTablesDatasetMetadata",
+ "SchemaTablesDatasetMetadataDict",
+ "SchemaTablesDatasetMetadataOrDict",
+ "CreateMultimodalDatasetConfig",
+ "CreateMultimodalDatasetConfigDict",
+ "CreateMultimodalDatasetConfigOrDict",
+ "MultimodalDataset",
+ "MultimodalDatasetDict",
+ "MultimodalDatasetOrDict",
+ "GetMultimodalDatasetOperationConfig",
+ "GetMultimodalDatasetOperationConfigDict",
+ "GetMultimodalDatasetOperationConfigOrDict",
+ "ListMultimodalDatasetsConfig",
+ "ListMultimodalDatasetsConfigDict",
+ "ListMultimodalDatasetsConfigOrDict",
+ "ListMultimodalDatasetsResponse",
+ "ListMultimodalDatasetsResponseDict",
+ "ListMultimodalDatasetsResponseOrDict",
+ "SchemaPredictParamsGroundingConfigSourceEntry",
+ "SchemaPredictParamsGroundingConfigSourceEntryDict",
+ "SchemaPredictParamsGroundingConfigSourceEntryOrDict",
+ "SchemaPredictParamsGroundingConfig",
+ "SchemaPredictParamsGroundingConfigDict",
+ "SchemaPredictParamsGroundingConfigOrDict",
+ "SchemaPromptInstancePromptExecution",
+ "SchemaPromptInstancePromptExecutionDict",
+ "SchemaPromptInstancePromptExecutionOrDict",
+ "SchemaPromptSpecPromptMessage",
+ "SchemaPromptSpecPromptMessageDict",
+ "SchemaPromptSpecPromptMessageOrDict",
+ "SchemaPromptSpecMultimodalPrompt",
+ "SchemaPromptSpecMultimodalPromptDict",
+ "SchemaPromptSpecMultimodalPromptOrDict",
+ "SchemaPromptSpecAppBuilderDataLinkedResource",
+ "SchemaPromptSpecAppBuilderDataLinkedResourceDict",
+ "SchemaPromptSpecAppBuilderDataLinkedResourceOrDict",
+ "SchemaPromptSpecAppBuilderData",
+ "SchemaPromptSpecAppBuilderDataDict",
+ "SchemaPromptSpecAppBuilderDataOrDict",
+ "SchemaPromptSpecPartList",
+ "SchemaPromptSpecPartListDict",
+ "SchemaPromptSpecPartListOrDict",
+ "SchemaPromptSpecStructuredPrompt",
+ "SchemaPromptSpecStructuredPromptDict",
+ "SchemaPromptSpecStructuredPromptOrDict",
+ "SchemaPromptSpecReferenceSentencePair",
+ "SchemaPromptSpecReferenceSentencePairDict",
+ "SchemaPromptSpecReferenceSentencePairOrDict",
+ "SchemaPromptSpecReferenceSentencePairList",
+ "SchemaPromptSpecReferenceSentencePairListDict",
+ "SchemaPromptSpecReferenceSentencePairListOrDict",
+ "SchemaPromptSpecTranslationFileInputSource",
+ "SchemaPromptSpecTranslationFileInputSourceDict",
+ "SchemaPromptSpecTranslationFileInputSourceOrDict",
+ "SchemaPromptSpecTranslationGcsInputSource",
+ "SchemaPromptSpecTranslationGcsInputSourceDict",
+ "SchemaPromptSpecTranslationGcsInputSourceOrDict",
+ "SchemaPromptSpecTranslationSentenceFileInput",
+ "SchemaPromptSpecTranslationSentenceFileInputDict",
+ "SchemaPromptSpecTranslationSentenceFileInputOrDict",
+ "SchemaPromptSpecTranslationExample",
+ "SchemaPromptSpecTranslationExampleDict",
+ "SchemaPromptSpecTranslationExampleOrDict",
+ "SchemaPromptSpecTranslationOption",
+ "SchemaPromptSpecTranslationOptionDict",
+ "SchemaPromptSpecTranslationOptionOrDict",
+ "SchemaPromptSpecTranslationPrompt",
+ "SchemaPromptSpecTranslationPromptDict",
+ "SchemaPromptSpecTranslationPromptOrDict",
+ "SchemaPromptApiSchema",
+ "SchemaPromptApiSchemaDict",
+ "SchemaPromptApiSchemaOrDict",
+ "SchemaTextPromptDatasetMetadata",
+ "SchemaTextPromptDatasetMetadataDict",
+ "SchemaTextPromptDatasetMetadataOrDict",
+ "CreateDatasetConfig",
+ "CreateDatasetConfigDict",
+ "CreateDatasetConfigOrDict",
+ "DatasetOperation",
+ "DatasetOperationDict",
+ "DatasetOperationOrDict",
+ "CreateDatasetVersionConfig",
+ "CreateDatasetVersionConfigDict",
+ "CreateDatasetVersionConfigOrDict",
+ "SavedQuery",
+ "SavedQueryDict",
+ "SavedQueryOrDict",
+ "Dataset",
+ "DatasetDict",
+ "DatasetOrDict",
+ "DatasetVersion",
+ "DatasetVersionDict",
+ "DatasetVersionOrDict",
+ "GetDatasetOperationConfig",
+ "GetDatasetOperationConfigDict",
+ "GetDatasetOperationConfigOrDict",
+ "ListPromptsConfig",
+ "ListPromptsConfigDict",
+ "ListPromptsConfigOrDict",
+ "ListDatasetsResponse",
+ "ListDatasetsResponseDict",
+ "ListDatasetsResponseOrDict",
+ "ListDatasetVersionsResponse",
+ "ListDatasetVersionsResponseDict",
+ "ListDatasetVersionsResponseOrDict",
+ "DeletePromptConfig",
+ "DeletePromptConfigDict",
+ "DeletePromptConfigOrDict",
+ "DeletePromptOperation",
+ "DeletePromptOperationDict",
+ "DeletePromptOperationOrDict",
+ "DeletePromptVersionOperation",
+ "DeletePromptVersionOperationDict",
+ "DeletePromptVersionOperationOrDict",
+ "RestoreVersionConfig",
+ "RestoreVersionConfigDict",
+ "RestoreVersionConfigOrDict",
+ "RestoreVersionOperation",
+ "RestoreVersionOperationDict",
+ "RestoreVersionOperationOrDict",
+ "UpdatePromptConfig",
+ "UpdatePromptConfigDict",
+ "UpdatePromptConfigOrDict",
+ "GetSkillConfig",
+ "GetSkillConfigDict",
+ "GetSkillConfigOrDict",
+ "Skill",
+ "SkillDict",
+ "SkillOrDict",
+ "RetrieveSkillsConfig",
+ "RetrieveSkillsConfigDict",
+ "RetrieveSkillsConfigOrDict",
+ "RetrievedSkill",
+ "RetrievedSkillDict",
+ "RetrievedSkillOrDict",
+ "RetrieveSkillsResponse",
+ "RetrieveSkillsResponseDict",
+ "RetrieveSkillsResponseOrDict",
+ "CreateSkillConfig",
+ "CreateSkillConfigDict",
+ "CreateSkillConfigOrDict",
+ "SkillOperation",
+ "SkillOperationDict",
+ "SkillOperationOrDict",
+ "UpdateSkillConfig",
+ "UpdateSkillConfigDict",
+ "UpdateSkillConfigOrDict",
+ "ListSkillsConfig",
+ "ListSkillsConfigDict",
+ "ListSkillsConfigOrDict",
+ "ListSkillsResponse",
+ "ListSkillsResponseDict",
+ "ListSkillsResponseOrDict",
+ "DeleteSkillConfig",
+ "DeleteSkillConfigDict",
+ "DeleteSkillConfigOrDict",
+ "DeleteSkillOperation",
+ "DeleteSkillOperationDict",
+ "DeleteSkillOperationOrDict",
+ "GetSkillOperationConfig",
+ "GetSkillOperationConfigDict",
+ "GetSkillOperationConfigOrDict",
+ "GetSkillRevisionConfig",
+ "GetSkillRevisionConfigDict",
+ "GetSkillRevisionConfigOrDict",
+ "SkillRevision",
+ "SkillRevisionDict",
+ "SkillRevisionOrDict",
+ "ListSkillRevisionsConfig",
+ "ListSkillRevisionsConfigDict",
+ "ListSkillRevisionsConfigOrDict",
+ "ListSkillRevisionsResponse",
+ "ListSkillRevisionsResponseDict",
+ "ListSkillRevisionsResponseOrDict",
+ "PromptOptimizerConfig",
+ "PromptOptimizerConfigDict",
+ "PromptOptimizerConfigOrDict",
+ "OptimizeResponse",
+ "OptimizeResponseDict",
+ "OptimizeResponseOrDict",
+ "ContentMapContents",
+ "ContentMapContentsDict",
+ "ContentMapContentsOrDict",
+ "EvaluateMethodConfig",
+ "EvaluateMethodConfigDict",
+ "EvaluateMethodConfigOrDict",
+ "EvaluateDatasetConfig",
+ "EvaluateDatasetConfigDict",
+ "EvaluateDatasetConfigOrDict",
+ "EvaluateDatasetOperation",
+ "EvaluateDatasetOperationDict",
+ "EvaluateDatasetOperationOrDict",
+ "EvaluateDatasetRequestParameters",
+ "EvaluateDatasetRequestParametersDict",
+ "EvaluateDatasetRequestParametersOrDict",
+ "ObservabilityEvalCase",
+ "ObservabilityEvalCaseDict",
+ "ObservabilityEvalCaseOrDict",
+ "RubricGroup",
+ "RubricGroupDict",
+ "RubricGroupOrDict",
+ "PromptTemplate",
+ "PromptTemplateDict",
+ "PromptTemplateOrDict",
+ "EvalRunInferenceConfig",
+ "EvalRunInferenceConfigDict",
+ "EvalRunInferenceConfigOrDict",
+ "AgentEngine",
+ "AgentEngineDict",
+ "AgentEngineOrDict",
+ "AgentEngineConfig",
+ "AgentEngineConfigDict",
+ "AgentEngineConfigOrDict",
+ "RunQueryJobAgentEngineConfig",
+ "RunQueryJobAgentEngineConfigDict",
+ "RunQueryJobAgentEngineConfigOrDict",
+ "RunQueryJobResult",
+ "RunQueryJobResultDict",
+ "RunQueryJobResultOrDict",
+ "CheckQueryJobResponse",
+ "CheckQueryJobResponseDict",
+ "CheckQueryJobResponseOrDict",
+ "AssembleDataset",
+ "AssembleDatasetDict",
+ "AssembleDatasetOrDict",
+ "BatchPredictionResourceUsageAssessmentResult",
+ "BatchPredictionResourceUsageAssessmentResultDict",
+ "BatchPredictionResourceUsageAssessmentResultOrDict",
+ "BatchPredictionValidationAssessmentResult",
+ "BatchPredictionValidationAssessmentResultDict",
+ "BatchPredictionValidationAssessmentResultOrDict",
+ "TuningResourceUsageAssessmentResult",
+ "TuningResourceUsageAssessmentResultDict",
+ "TuningResourceUsageAssessmentResultOrDict",
+ "TuningValidationAssessmentResult",
+ "TuningValidationAssessmentResultDict",
+ "TuningValidationAssessmentResultOrDict",
+ "Prompt",
+ "PromptDict",
+ "PromptOrDict",
+ "SchemaPromptInstanceVariableValue",
+ "SchemaPromptInstanceVariableValueDict",
+ "SchemaPromptInstanceVariableValueOrDict",
+ "CreatePromptConfig",
+ "CreatePromptConfigDict",
+ "CreatePromptConfigOrDict",
+ "CreatePromptVersionConfig",
+ "CreatePromptVersionConfigDict",
+ "CreatePromptVersionConfigOrDict",
+ "GetPromptConfig",
+ "GetPromptConfigDict",
+ "GetPromptConfigOrDict",
+ "PromptRef",
+ "PromptRefDict",
+ "PromptRefOrDict",
+ "PromptVersionRef",
+ "PromptVersionRefDict",
+ "PromptVersionRefOrDict",
+ "OptimizeJobConfig",
+ "OptimizeJobConfigDict",
+ "OptimizeJobConfigOrDict",
+ "AgentEngineRuntimeRevision",
+ "AgentEngineRuntimeRevisionDict",
+ "AgentEngineRuntimeRevisionOrDict",
+ "A2aTaskState",
+ "State",
+ "Strategy",
+ "AcceleratorType",
+ "Type",
+ "JobState",
+ "ManagedTopicEnum",
+ "IdentityType",
+ "AgentServerMode",
+ "MemoryType",
+ "Operator",
+ "Language",
+ "MachineConfig",
+ "SandboxState",
+ "Protocol",
+ "DefaultContainerCategory",
+ "PostSnapshotAction",
+ "Framework",
+ "EvaluationItemType",
+ "SamplingMethod",
+ "EvaluationRunState",
+ "OptimizeTarget",
+ "MemoryMetadataMergeStrategy",
+ "GenerateMemoriesResponseGeneratedMemoryAction",
+ "SkillState",
+ "PromptOptimizerMethod",
+ "OptimizationMethod",
+ "PromptData",
+ "PromptDataDict",
+ "PromptDataOrDict",
+ "LLMMetric",
+ "CodeExecutionMetric",
+ "MetricPromptBuilder",
+ "RubricContentProperty",
+ "RubricContentPropertyDict",
+ "RubricContent",
+ "RubricContentDict",
+ "Rubric",
+ "RubricDict",
+ "RubricVerdict",
+ "RubricVerdictDict",
+ "CandidateResult",
+ "CandidateResultDict",
+ "Event",
+ "EventDict",
+ "Message",
+ "MessageDict",
+ "Importance",
+ "ParsedResponseUnion",
+ "_DeleteAgentEngineTaskRequestParameters",
+ "_GetAgentEngineTaskRequestParameters",
+ "_ListAgentEngineTasksRequestParameters",
+ "_CreateAgentEngineTaskRequestParameters",
+ "_AppendAgentEngineTaskEventRequestParameters",
+ "_ListAgentEngineTaskEventsRequestParameters",
+ "_CreateEvaluationItemParameters",
+ "_CreateEvaluationMetricParameters",
+ "_CreateEvaluationRunParameters",
+ "_CreateEvaluationSetParameters",
+ "_DeleteEvaluationMetricParameters",
+ "_EvaluateInstancesRequestParameters",
+ "_GenerateUserScenariosParameters",
+ "_GenerateLossClustersParameters",
+ "_GenerateInstanceRubricsRequest",
+ "_GetEvaluationMetricParameters",
+ "_GetEvaluationRunParameters",
+ "_GetEvaluationSetParameters",
+ "_GetEvaluationItemParameters",
+ "_ListEvaluationMetricsParameters",
+ "_OptimizeRequestParameters",
+ "_CustomJobParameters",
+ "_GetCustomJobParameters",
+ "_CancelQueryJobAgentEngineRequestParameters",
+ "_CheckQueryJobAgentEngineRequestParameters",
+ "_RunQueryJobAgentEngineRequestParameters",
+ "_CreateAgentEngineRequestParameters",
+ "_DeleteAgentEngineRequestParameters",
+ "_GetAgentEngineRequestParameters",
+ "_ListAgentEngineRequestParameters",
+ "_GetAgentEngineOperationParameters",
+ "_QueryAgentEngineRequestParameters",
+ "_UpdateAgentEngineRequestParameters",
+ "_CreateAgentEngineMemoryRequestParameters",
+ "_DeleteAgentEngineMemoryRequestParameters",
+ "_GenerateAgentEngineMemoriesRequestParameters",
+ "_GetAgentEngineMemoryRequestParameters",
+ "_IngestEventsRequestParameters",
+ "_ListAgentEngineMemoryRequestParameters",
+ "_GetAgentEngineMemoryOperationParameters",
+ "_GetAgentEngineGenerateMemoriesOperationParameters",
+ "_RetrieveAgentEngineMemoriesRequestParameters",
+ "_RetrieveMemoryProfilesRequestParameters",
+ "_RollbackAgentEngineMemoryRequestParameters",
+ "_UpdateAgentEngineMemoryRequestParameters",
+ "_PurgeAgentEngineMemoriesRequestParameters",
+ "_GetAgentEngineMemoryRevisionRequestParameters",
+ "_ListAgentEngineMemoryRevisionsRequestParameters",
+ "_GetAgentEngineRuntimeRevisionRequestParameters",
+ "_ListAgentEngineRuntimeRevisionsRequestParameters",
+ "_DeleteAgentEngineRuntimeRevisionRequestParameters",
+ "_GetDeleteAgentEngineRuntimeRevisionOperationParameters",
+ "_QueryAgentEngineRuntimeRevisionRequestParameters",
+ "_CreateAgentEngineSandboxRequestParameters",
+ "_DeleteAgentEngineSandboxRequestParameters",
+ "_ExecuteCodeAgentEngineSandboxRequestParameters",
+ "_GetAgentEngineSandboxRequestParameters",
+ "_ListAgentEngineSandboxesRequestParameters",
+ "_GetAgentEngineSandboxOperationParameters",
+ "_CreateSandboxEnvironmentTemplateRequestParameters",
+ "_DeleteSandboxEnvironmentTemplateRequestParameters",
+ "_GetSandboxEnvironmentTemplateRequestParameters",
+ "_ListSandboxEnvironmentTemplatesRequestParameters",
+ "_GetSandboxEnvironmentTemplateOperationParameters",
+ "_CreateSandboxEnvironmentSnapshotRequestParameters",
+ "_DeleteSandboxEnvironmentSnapshotRequestParameters",
+ "_GetSandboxEnvironmentSnapshotRequestParameters",
+ "_ListSandboxEnvironmentSnapshotsRequestParameters",
+ "_GetAgentEngineSandboxSnapshotOperationParameters",
+ "_CreateAgentEngineSessionRequestParameters",
+ "_DeleteAgentEngineSessionRequestParameters",
+ "_GetAgentEngineSessionRequestParameters",
+ "_ListAgentEngineSessionsRequestParameters",
+ "_GetAgentEngineSessionOperationParameters",
+ "_UpdateAgentEngineSessionRequestParameters",
+ "_AppendAgentEngineSessionEventRequestParameters",
+ "_ListAgentEngineSessionEventsRequestParameters",
+ "_AssembleDatasetParameters",
+ "_AssessDatasetParameters",
+ "_CreateMultimodalDatasetParameters",
+ "_DeleteMultimodalDatasetRequestParameters",
+ "_GetMultimodalDatasetParameters",
+ "_GetMultimodalDatasetOperationParameters",
+ "_ListMultimodalDatasetsRequestParameters",
+ "_UpdateMultimodalDatasetParameters",
+ "_CreateDatasetParameters",
+ "_CreateDatasetVersionParameters",
+ "_GetDatasetParameters",
+ "_GetDatasetVersionParameters",
+ "_GetDatasetOperationParameters",
+ "_ListDatasetsRequestParameters",
+ "_ListDatasetVersionsRequestParameters",
+ "_DeleteDatasetRequestParameters",
+ "_DeletePromptVersionRequestParameters",
+ "_RestoreVersionRequestParameters",
+ "_UpdateDatasetParameters",
+ "_CustomJobParameters",
+ "_GetCustomJobParameters",
+ "_OptimizeRequestParameters",
+ "_GetSkillRequestParameters",
+ "_RetrieveSkillsRequestParameters",
+ "_CreateSkillRequestParameters",
+ "_UpdateSkillRequestParameters",
+ "_ListSkillsRequestParameters",
+ "_DeleteSkillRequestParameters",
+ "_GetSkillOperationParameters",
+ "_GetSkillRevisionRequestParameters",
+ "_ListSkillRevisionsRequestParameters",
+ "evals",
+ "agent_engines",
+ "prompts",
+ "PrebuiltMetric",
+ "RubricMetric",
+]
+
+
+def __getattr__(name: str) -> typing.Any:
+ if name == "PrebuiltMetric" or name == "RubricMetric":
+ module = importlib.import_module(".._evals_metric_loaders", __package__)
+ prebuilt_metric_obj = getattr(module, name)
+ globals()[name] = prebuilt_metric_obj
+ return prebuilt_metric_obj
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/agent_engines.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/agent_engines.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21a43b353abd1aed449155a57a91c401cfcec512
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/agent_engines.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/evals.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/evals.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53ae6158e5a7bad812f8c75ec8a659f6486bdfd5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/evals.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/prompt_optimizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/prompt_optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ff98ce7830fb27f479ecf233da114217c98c068
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/prompt_optimizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/prompts.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/prompts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bac172d71c705a5c6b0bf23f62fb323df2fb94c5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/__pycache__/prompts.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/agent_engines.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/agent_engines.py
new file mode 100644
index 0000000000000000000000000000000000000000..c47a08a11eca4cfe304ad47d9ec057f93b192d76
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/agent_engines.py
@@ -0,0 +1,16 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..55e841d9739c804cb430e2ee9f8f6c6c8efe1632
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/common.py
@@ -0,0 +1,20752 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import datetime
+import json
+import logging
+import os
+import re
+import typing
+from typing import (
+ Any,
+ Callable,
+ ClassVar,
+ Dict,
+ List,
+ Literal,
+ Optional,
+ Tuple,
+ TypeVar,
+ Union,
+)
+from google.genai import _common
+from google.genai import types as genai_types
+from pydantic import (
+ ConfigDict,
+ Field,
+ PrivateAttr,
+ computed_field,
+ field_validator,
+ model_validator,
+)
+from typing_extensions import TypeAlias, TypedDict
+from . import evals as evals_types
+from . import prompts as prompts_types
+
+
+def camel_to_snake(camel_case_string: str) -> str:
+ snake_case_string = re.sub(r"(? Any:
+ """Converts all camelCase keys to snake_case in a dict or list."""
+ if isinstance(message, dict):
+ return {
+ camel_to_snake(key): _camel_key_to_snake(value)
+ for key, value in message.items()
+ }
+ elif isinstance(message, list):
+ return [_camel_key_to_snake(value) for value in message]
+ else:
+ return message
+
+
+if typing.TYPE_CHECKING:
+ import pandas as pd
+
+ PandasDataFrame: TypeAlias = pd.DataFrame
+else:
+ try:
+ import pandas as pd
+
+ PandasDataFrame = pd.DataFrame
+ except ImportError:
+ pd = None
+ PandasDataFrame = Any
+if typing.TYPE_CHECKING:
+ import yaml
+else:
+ try:
+ import yaml
+ except ImportError:
+ yaml = None
+
+logger = logging.getLogger("agentplatform_genai.types")
+
+MetricSubclass = TypeVar("MetricSubclass", bound="Metric")
+
+
+class A2aTaskState(_common.CaseInSensitiveEnum):
+ """Output only. The state of the task. The state of a new task is SUBMITTED by default. The state of a task can only be updated via AppendA2aTaskEvents API."""
+
+ STATE_UNSPECIFIED = "STATE_UNSPECIFIED"
+ """Task state unspecified. Default value if not set."""
+ SUBMITTED = "SUBMITTED"
+ """Task is submitted and waiting to be processed."""
+ WORKING = "WORKING"
+ """Task is actively being processed."""
+ COMPLETED = "COMPLETED"
+ """Task is finished."""
+ CANCELLED = "CANCELLED"
+ """Task is cancelled."""
+ FAILED = "FAILED"
+ """Task has failed."""
+ REJECTED = "REJECTED"
+ """Task is rejected by the system."""
+ INPUT_REQUIRED = "INPUT_REQUIRED"
+ """Task requires input from the user."""
+ AUTH_REQUIRED = "AUTH_REQUIRED"
+ """Task requires auth (e.g. OAuth) from the user."""
+ PAUSED = "PAUSED"
+ """Task is paused."""
+
+
+class State(_common.CaseInSensitiveEnum):
+ """The new state of the task."""
+
+ STATE_UNSPECIFIED = "STATE_UNSPECIFIED"
+ """Task state unspecified. Default value if not set."""
+ SUBMITTED = "SUBMITTED"
+ """Task is submitted and waiting to be processed."""
+ WORKING = "WORKING"
+ """Task is actively being processed."""
+ COMPLETED = "COMPLETED"
+ """Task is finished."""
+ CANCELLED = "CANCELLED"
+ """Task is cancelled."""
+ FAILED = "FAILED"
+ """Task has failed."""
+ REJECTED = "REJECTED"
+ """Task is rejected by the system."""
+ INPUT_REQUIRED = "INPUT_REQUIRED"
+ """Task requires input from the user."""
+ AUTH_REQUIRED = "AUTH_REQUIRED"
+ """Task requires auth (e.g. OAuth) from the user."""
+ PAUSED = "PAUSED"
+ """Task is paused."""
+
+
+class Strategy(_common.CaseInSensitiveEnum):
+ """This determines which type of scheduling strategy to use."""
+
+ STRATEGY_UNSPECIFIED = "STRATEGY_UNSPECIFIED"
+ """Strategy will default to STANDARD."""
+ ON_DEMAND = "ON_DEMAND"
+ """Deprecated. Regular on-demand provisioning strategy."""
+ LOW_COST = "LOW_COST"
+ """Deprecated. Low cost by making potential use of spot resources."""
+ STANDARD = "STANDARD"
+ """Standard provisioning strategy uses regular on-demand resources."""
+ SPOT = "SPOT"
+ """Spot provisioning strategy uses spot resources."""
+ FLEX_START = "FLEX_START"
+ """Flex Start strategy uses DWS to queue for resources."""
+
+
+class AcceleratorType(_common.CaseInSensitiveEnum):
+ """Immutable. The type of accelerator(s) that may be attached to the machine as per accelerator_count."""
+
+ ACCELERATOR_TYPE_UNSPECIFIED = "ACCELERATOR_TYPE_UNSPECIFIED"
+ """Unspecified accelerator type, which means no accelerator."""
+ NVIDIA_TESLA_K80 = "NVIDIA_TESLA_K80"
+ """Deprecated: Nvidia Tesla K80 GPU has reached end of support, see https://cloud.google.com/compute/docs/eol/k80-eol."""
+ NVIDIA_TESLA_P100 = "NVIDIA_TESLA_P100"
+ """Nvidia Tesla P100 GPU."""
+ NVIDIA_TESLA_V100 = "NVIDIA_TESLA_V100"
+ """Nvidia Tesla V100 GPU."""
+ NVIDIA_TESLA_P4 = "NVIDIA_TESLA_P4"
+ """Nvidia Tesla P4 GPU."""
+ NVIDIA_TESLA_T4 = "NVIDIA_TESLA_T4"
+ """Nvidia Tesla T4 GPU."""
+ NVIDIA_TESLA_A100 = "NVIDIA_TESLA_A100"
+ """Nvidia Tesla A100 GPU."""
+ NVIDIA_A100_80GB = "NVIDIA_A100_80GB"
+ """Nvidia A100 80GB GPU."""
+ NVIDIA_L4 = "NVIDIA_L4"
+ """Nvidia L4 GPU."""
+ NVIDIA_H100_80GB = "NVIDIA_H100_80GB"
+ """Nvidia H100 80Gb GPU."""
+ NVIDIA_H100_MEGA_80GB = "NVIDIA_H100_MEGA_80GB"
+ """Nvidia H100 Mega 80Gb GPU."""
+ NVIDIA_H200_141GB = "NVIDIA_H200_141GB"
+ """Nvidia H200 141Gb GPU."""
+ NVIDIA_B200 = "NVIDIA_B200"
+ """Nvidia B200 GPU."""
+ NVIDIA_GB200 = "NVIDIA_GB200"
+ """Nvidia GB200 GPU."""
+ NVIDIA_RTX_PRO_6000 = "NVIDIA_RTX_PRO_6000"
+ """Nvidia RTX Pro 6000 GPU."""
+ TPU_V2 = "TPU_V2"
+ """TPU v2."""
+ TPU_V3 = "TPU_V3"
+ """TPU v3."""
+ TPU_V4_POD = "TPU_V4_POD"
+ """TPU v4."""
+ TPU_V5_LITEPOD = "TPU_V5_LITEPOD"
+ """TPU v5."""
+
+
+class Type(_common.CaseInSensitiveEnum):
+ """Specifies the reservation affinity type."""
+
+ TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED"
+ """Default value. This should not be used."""
+ NO_RESERVATION = "NO_RESERVATION"
+ """Do not consume from any reserved capacity, only use on-demand."""
+ ANY_RESERVATION = "ANY_RESERVATION"
+ """Consume any reservation available, falling back to on-demand."""
+ SPECIFIC_RESERVATION = "SPECIFIC_RESERVATION"
+ """Consume from a specific reservation. When chosen, the reservation must be identified via the `key` and `values` fields."""
+
+
+class JobState(_common.CaseInSensitiveEnum):
+ """Output only. The detailed state of the job."""
+
+ JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED"
+ """The job state is unspecified."""
+ JOB_STATE_QUEUED = "JOB_STATE_QUEUED"
+ """The job has been just created or resumed and processing has not yet begun."""
+ JOB_STATE_PENDING = "JOB_STATE_PENDING"
+ """The service is preparing to run the job."""
+ JOB_STATE_RUNNING = "JOB_STATE_RUNNING"
+ """The job is in progress."""
+ JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED"
+ """The job completed successfully."""
+ JOB_STATE_FAILED = "JOB_STATE_FAILED"
+ """The job failed."""
+ JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING"
+ """The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`."""
+ JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED"
+ """The job has been cancelled."""
+ JOB_STATE_PAUSED = "JOB_STATE_PAUSED"
+ """The job has been stopped, and can be resumed."""
+ JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED"
+ """The job has expired."""
+ JOB_STATE_UPDATING = "JOB_STATE_UPDATING"
+ """The job is being updated. Only jobs in the `RUNNING` state can be updated. After updating, the job goes back to the `RUNNING` state."""
+ JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED"
+ """The job is partially succeeded, some results may be missing due to errors."""
+
+
+class ManagedTopicEnum(_common.CaseInSensitiveEnum):
+ """Represents the managed memory topic."""
+
+ MANAGED_TOPIC_ENUM_UNSPECIFIED = "MANAGED_TOPIC_ENUM_UNSPECIFIED"
+ """Represents an unspecified topic. This value should not be used."""
+ USER_PERSONAL_INFO = "USER_PERSONAL_INFO"
+ """Represents significant personal information about the User like first names, relationships, hobbies, important dates."""
+ USER_PREFERENCES = "USER_PREFERENCES"
+ """Represents stated or implied likes, dislikes, preferred styles, or patterns."""
+ KEY_CONVERSATION_DETAILS = "KEY_CONVERSATION_DETAILS"
+ """Represents important milestones or conclusions within the dialogue."""
+ EXPLICIT_INSTRUCTIONS = "EXPLICIT_INSTRUCTIONS"
+ """Represents information that the user explicitly requested to remember or forget."""
+
+
+class IdentityType(_common.CaseInSensitiveEnum):
+ """The identity type to use for the Reasoning Engine. If not specified, the `service_account` field will be used if set, otherwise the default Vertex AI Reasoning Engine Service Agent in the project will be used."""
+
+ IDENTITY_TYPE_UNSPECIFIED = "IDENTITY_TYPE_UNSPECIFIED"
+ """Default value. Use a custom service account if the `service_account` field is set, otherwise use the default Vertex AI Reasoning Engine Service Agent in the project. Same behavior as SERVICE_ACCOUNT."""
+ SERVICE_ACCOUNT = "SERVICE_ACCOUNT"
+ """Use a custom service account if the `service_account` field is set, otherwise use the default Vertex AI Reasoning Engine Service Agent in the project."""
+ AGENT_IDENTITY = "AGENT_IDENTITY"
+ """Use Agent Identity. The `service_account` field must not be set."""
+
+
+class AgentServerMode(_common.CaseInSensitiveEnum):
+ """The agent server mode."""
+
+ AGENT_SERVER_MODE_UNSPECIFIED = "AGENT_SERVER_MODE_UNSPECIFIED"
+ """Unspecified agent server mode. Do not use."""
+ STABLE = "STABLE"
+ """Stable agent server mode. This mode has everything stable and well-tested features agent engine offers."""
+ EXPERIMENTAL = "EXPERIMENTAL"
+ """Experimental agent server mode. This mode contains experimental features."""
+
+
+class MemoryType(_common.CaseInSensitiveEnum):
+ """The type of the memory."""
+
+ MEMORY_TYPE_UNSPECIFIED = "MEMORY_TYPE_UNSPECIFIED"
+ """Represents an unspecified memory type. This value should not be used."""
+ NATURAL_LANGUAGE_COLLECTION = "NATURAL_LANGUAGE_COLLECTION"
+ """Indicates belonging to a collection of natural language memories."""
+ STRUCTURED_PROFILE = "STRUCTURED_PROFILE"
+ """Indicates belonging to a structured profile."""
+
+
+class Operator(_common.CaseInSensitiveEnum):
+ """Represents the operator to apply to the filter. If not set, then EQUAL will be used."""
+
+ OPERATOR_UNSPECIFIED = "OPERATOR_UNSPECIFIED"
+ """Represents an unspecified operator. Defaults to EQUAL."""
+ EQUAL = "EQUAL"
+ """Equal to."""
+ GREATER_THAN = "GREATER_THAN"
+ """Greater than."""
+ LESS_THAN = "LESS_THAN"
+ """Less than."""
+
+
+class Language(_common.CaseInSensitiveEnum):
+ """The coding language supported in this environment."""
+
+ LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED"
+ """The default value. This value is unused."""
+ LANGUAGE_PYTHON = "LANGUAGE_PYTHON"
+ """The coding language is Python."""
+ LANGUAGE_JAVASCRIPT = "LANGUAGE_JAVASCRIPT"
+ """The coding language is JavaScript."""
+
+
+class MachineConfig(_common.CaseInSensitiveEnum):
+ """The machine config of the code execution environment."""
+
+ MACHINE_CONFIG_UNSPECIFIED = "MACHINE_CONFIG_UNSPECIFIED"
+ """The default value: milligcu 2000, memory 1.5Gib"""
+ MACHINE_CONFIG_VCPU4_RAM4GIB = "MACHINE_CONFIG_VCPU4_RAM4GIB"
+ """The default value: milligcu 4000, memory 4 Gib"""
+
+
+class SandboxState(_common.CaseInSensitiveEnum):
+ """Output only. The runtime state of the SandboxEnvironment."""
+
+ STATE_UNSPECIFIED = "STATE_UNSPECIFIED"
+ """The default value. This value is unused."""
+ STATE_PROVISIONING = "STATE_PROVISIONING"
+ """Runtime resources are being allocated for the sandbox environment."""
+ STATE_RUNNING = "STATE_RUNNING"
+ """Sandbox runtime is ready for serving."""
+ STATE_DEPROVISIONING = "STATE_DEPROVISIONING"
+ """Sandbox runtime is halted, performing tear down tasks."""
+ STATE_TERMINATED = "STATE_TERMINATED"
+ """Sandbox has terminated with underlying runtime failure."""
+ STATE_DELETED = "STATE_DELETED"
+ """Sandbox runtime has been deleted."""
+
+
+class Protocol(_common.CaseInSensitiveEnum):
+ """Protocol for port. Defaults to TCP if not specified."""
+
+ PROTOCOL_UNSPECIFIED = "PROTOCOL_UNSPECIFIED"
+ """Unspecified protocol. Defaults to TCP."""
+ TCP = "TCP"
+ """TCP protocol."""
+ UDP = "UDP"
+ """UDP protocol."""
+
+
+class DefaultContainerCategory(_common.CaseInSensitiveEnum):
+ """The category of the default container image."""
+
+ DEFAULT_CONTAINER_CATEGORY_UNSPECIFIED = "DEFAULT_CONTAINER_CATEGORY_UNSPECIFIED"
+ """The default value. This value is unused."""
+ DEFAULT_CONTAINER_CATEGORY_COMPUTER_USE = "DEFAULT_CONTAINER_CATEGORY_COMPUTER_USE"
+ """The default container image for Computer Use."""
+
+
+class PostSnapshotAction(_common.CaseInSensitiveEnum):
+ """Input only. Action to take on the source SandboxEnvironment after the snapshot is taken. This field is only used in CreateSandboxEnvironmentSnapshotRequest and it is not stored in the resource."""
+
+ POST_SNAPSHOT_ACTION_UNSPECIFIED = "POST_SNAPSHOT_ACTION_UNSPECIFIED"
+ """The default value. This value is unused."""
+ RUNNING = "RUNNING"
+ """Sandbox environment will continue to run after snapshot is taken."""
+ PAUSE = "PAUSE"
+ """Sandbox environment will be paused after snapshot is taken."""
+
+
+class Framework(_common.CaseInSensitiveEnum):
+ """Framework used to build the application."""
+
+ FRAMEWORK_UNSPECIFIED = "FRAMEWORK_UNSPECIFIED"
+ """Unspecified framework."""
+ REACT = "REACT"
+ """React framework."""
+ ANGULAR = "ANGULAR"
+ """Angular framework."""
+
+
+class EvaluationItemType(_common.CaseInSensitiveEnum):
+ """The type of the EvaluationItem."""
+
+ EVALUATION_ITEM_TYPE_UNSPECIFIED = "EVALUATION_ITEM_TYPE_UNSPECIFIED"
+ """The default value. This value is unused."""
+ REQUEST = "REQUEST"
+ """The EvaluationItem is a request to evaluate."""
+ RESULT = "RESULT"
+ """The EvaluationItem is the result of evaluation."""
+
+
+class SamplingMethod(_common.CaseInSensitiveEnum):
+ """Represents the sampling method for a BigQuery request set."""
+
+ UNSPECIFIED = "UNSPECIFIED"
+ """Sampling method is unspecified."""
+ RANDOM = "RANDOM"
+ """Sampling method is random."""
+
+
+class EvaluationRunState(_common.CaseInSensitiveEnum):
+ """Represents the state of an evaluation run."""
+
+ UNSPECIFIED = "UNSPECIFIED"
+ """Evaluation run state is unspecified."""
+ PENDING = "PENDING"
+ """Evaluation run is pending."""
+ RUNNING = "RUNNING"
+ """Evaluation run is in progress."""
+ SUCCEEDED = "SUCCEEDED"
+ """Evaluation run has succeeded."""
+ FAILED = "FAILED"
+ """Evaluation run failed."""
+ CANCELLED = "CANCELLED"
+ """Evaluation run was cancelled."""
+ INFERENCE = "INFERENCE"
+ """Evaluation run is performing inference."""
+ GENERATING_RUBRICS = "GENERATING_RUBRICS"
+ """Evaluation run is performing rubric generation."""
+
+
+class OptimizeTarget(_common.CaseInSensitiveEnum):
+ """Specifies the method for calling the optimize_prompt."""
+
+ OPTIMIZATION_TARGET_GEMINI_NANO = "OPTIMIZATION_TARGET_GEMINI_NANO"
+ """The data driven prompt optimizer designer for prompts from Android core API."""
+ OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS = "OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS"
+ """The prompt optimizer based on user provided examples with rubrics."""
+ OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE = (
+ "OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE"
+ )
+ """The prompt optimizer based on user provided examples with target responses."""
+
+
+class MemoryMetadataMergeStrategy(_common.CaseInSensitiveEnum):
+ """The strategy to use when applying metadata to existing memories during consolidation."""
+
+ METADATA_MERGE_STRATEGY_UNSPECIFIED = "METADATA_MERGE_STRATEGY_UNSPECIFIED"
+ """The metadata merge strategy is unspecified."""
+ OVERWRITE = "OVERWRITE"
+ """Replace the metadata of the updated memories with the new metadata."""
+ MERGE = "MERGE"
+ """Append new metadata to the existing metadata. If there are duplicate keys, the existing values will be overwritten."""
+ REQUIRE_EXACT_MATCH = "REQUIRE_EXACT_MATCH"
+ """Restrict consolidation to memories that have exactly the same metadata as the request. If a memory doesn't have the same metadata, it is not eligible for consolidation."""
+
+
+class GenerateMemoriesResponseGeneratedMemoryAction(_common.CaseInSensitiveEnum):
+ """The action to take."""
+
+ ACTION_UNSPECIFIED = "ACTION_UNSPECIFIED"
+ """The action is unspecified."""
+ CREATED = "CREATED"
+ """The memory was created."""
+ UPDATED = "UPDATED"
+ """The memory was updated. The `fact` field may not be updated if the existing fact is still accurate."""
+ DELETED = "DELETED"
+ """The memory was deleted."""
+
+
+class SkillState(_common.CaseInSensitiveEnum):
+ """State of the Skill."""
+
+ STATE_UNSPECIFIED = "STATE_UNSPECIFIED"
+ """The state of the Skill is unspecified."""
+ ACTIVE = "ACTIVE"
+ """The Skill is active."""
+ CREATING = "CREATING"
+ """The Skill is being created."""
+ FAILED = "FAILED"
+ """The Skill was created, but failed to process."""
+ DELETING = "DELETING"
+ """The Skill is being deleted."""
+
+
+class PromptOptimizerMethod(_common.CaseInSensitiveEnum):
+ """The method for data driven prompt optimization."""
+
+ VAPO = "VAPO"
+ """The default data driven Vertex AI Prompt Optimizer."""
+ OPTIMIZATION_TARGET_GEMINI_NANO = "OPTIMIZATION_TARGET_GEMINI_NANO"
+ """The data driven prompt optimizer designer for prompts from Android core API."""
+
+
+class OptimizationMethod(_common.CaseInSensitiveEnum):
+ """The method for data driven prompt optimization."""
+
+ VAPO = "VAPO"
+ """The default data driven Vertex AI Prompt Optimizer."""
+ OPTIMIZATION_TARGET_GEMINI_NANO = "OPTIMIZATION_TARGET_GEMINI_NANO"
+ """The data driven prompt optimizer designer for prompts from Android core API."""
+
+
+class DeleteAgentEngineTaskConfig(_common.BaseModel):
+ """Config for deleting an Agent Engine Task."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteAgentEngineTaskConfigDict(TypedDict, total=False):
+ """Config for deleting an Agent Engine Task."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteAgentEngineTaskConfigOrDict = Union[
+ DeleteAgentEngineTaskConfig, DeleteAgentEngineTaskConfigDict
+]
+
+
+class _DeleteAgentEngineTaskRequestParameters(_common.BaseModel):
+ """Parameters for deleting an agent engine task."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine task."""
+ )
+ config: Optional[DeleteAgentEngineTaskConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteAgentEngineTaskRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting an agent engine task."""
+
+ name: Optional[str]
+ """Name of the agent engine task."""
+
+ config: Optional[DeleteAgentEngineTaskConfigDict]
+ """"""
+
+
+_DeleteAgentEngineTaskRequestParametersOrDict = Union[
+ _DeleteAgentEngineTaskRequestParameters, _DeleteAgentEngineTaskRequestParametersDict
+]
+
+
+class GetAgentEngineTaskConfig(_common.BaseModel):
+ """Config for getting an Agent Engine Task."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineTaskConfigDict(TypedDict, total=False):
+ """Config for getting an Agent Engine Task."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineTaskConfigOrDict = Union[
+ GetAgentEngineTaskConfig, GetAgentEngineTaskConfigDict
+]
+
+
+class _GetAgentEngineTaskRequestParameters(_common.BaseModel):
+ """Parameters for getting an agent engine task."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine task."""
+ )
+ config: Optional[GetAgentEngineTaskConfig] = Field(default=None, description="""""")
+
+
+class _GetAgentEngineTaskRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting an agent engine task."""
+
+ name: Optional[str]
+ """Name of the agent engine task."""
+
+ config: Optional[GetAgentEngineTaskConfigDict]
+ """"""
+
+
+_GetAgentEngineTaskRequestParametersOrDict = Union[
+ _GetAgentEngineTaskRequestParameters, _GetAgentEngineTaskRequestParametersDict
+]
+
+
+class TaskArtifact(_common.BaseModel):
+ """The artifact of the task event."""
+
+ artifact_id: Optional[str] = Field(
+ default=None,
+ description="""Required. The unique identifier of the artifact within the task. This id is provided by the creator of the artifact.""",
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="""Optional. A human readable description of the artifact.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Optional. The human-readable name of the artifact provided by the creator.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional. Additional metadata for the artifact. For A2A, the URIs of the extensions that were used to produce this artifact will be stored here.""",
+ )
+ parts: Optional[list[genai_types.Part]] = Field(
+ default=None, description="""The parts of the artifact."""
+ )
+
+
+class TaskArtifactDict(TypedDict, total=False):
+ """The artifact of the task event."""
+
+ artifact_id: Optional[str]
+ """Required. The unique identifier of the artifact within the task. This id is provided by the creator of the artifact."""
+
+ description: Optional[str]
+ """Optional. A human readable description of the artifact."""
+
+ display_name: Optional[str]
+ """Optional. The human-readable name of the artifact provided by the creator."""
+
+ metadata: Optional[dict[str, Any]]
+ """Optional. Additional metadata for the artifact. For A2A, the URIs of the extensions that were used to produce this artifact will be stored here."""
+
+ parts: Optional[list[genai_types.PartDict]]
+ """The parts of the artifact."""
+
+
+TaskArtifactOrDict = Union[TaskArtifact, TaskArtifactDict]
+
+
+class TaskOutput(_common.BaseModel):
+ """The output of the task event."""
+
+ artifacts: Optional[list[TaskArtifact]] = Field(
+ default=None, description="""The artifacts of the task event."""
+ )
+
+
+class TaskOutputDict(TypedDict, total=False):
+ """The output of the task event."""
+
+ artifacts: Optional[list[TaskArtifactDict]]
+ """The artifacts of the task event."""
+
+
+TaskOutputOrDict = Union[TaskOutput, TaskOutputDict]
+
+
+class TaskMessage(_common.BaseModel):
+ """The message of the task event."""
+
+ message_id: Optional[str] = Field(
+ default=None, description="""Required. The unique identifier of the message."""
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional. A2A message may have extension_uris or reference_task_ids. They will be stored under metadata.""",
+ )
+ parts: Optional[list[genai_types.Part]] = Field(
+ default=None, description="""The parts of the message."""
+ )
+ role: Optional[str] = Field(
+ default=None,
+ description="""Required. The role of the sender of the message. e.g. "user", "agent".""",
+ )
+
+
+class TaskMessageDict(TypedDict, total=False):
+ """The message of the task event."""
+
+ message_id: Optional[str]
+ """Required. The unique identifier of the message."""
+
+ metadata: Optional[dict[str, Any]]
+ """Optional. A2A message may have extension_uris or reference_task_ids. They will be stored under metadata."""
+
+ parts: Optional[list[genai_types.PartDict]]
+ """The parts of the message."""
+
+ role: Optional[str]
+ """Required. The role of the sender of the message. e.g. "user", "agent"."""
+
+
+TaskMessageOrDict = Union[TaskMessage, TaskMessageDict]
+
+
+class TaskStatusDetails(_common.BaseModel):
+ """The status details of the task event."""
+
+ task_message: Optional[TaskMessage] = Field(
+ default=None, description="""The status of the task event."""
+ )
+
+
+class TaskStatusDetailsDict(TypedDict, total=False):
+ """The status details of the task event."""
+
+ task_message: Optional[TaskMessageDict]
+ """The status of the task event."""
+
+
+TaskStatusDetailsOrDict = Union[TaskStatusDetails, TaskStatusDetailsDict]
+
+
+class A2aTask(_common.BaseModel):
+ """A task."""
+
+ context_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. A generic identifier for grouping related tasks (e.g., session_id, workflow_id).""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None, description="""Output only. The creation timestamp of the task."""
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None, description="""Optional. Arbitrary, user-defined metadata."""
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the task. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/a2aTasks/{a2a_task}`""",
+ )
+ next_event_sequence_number: Optional[int] = Field(
+ default=None,
+ description="""Output only. The next event sequence number to be appended to the task. This value starts at 1 and is guaranteed to be monotonically increasing.""",
+ )
+ output: Optional[TaskOutput] = Field(
+ default=None, description="""Optional. The final output of the task."""
+ )
+ state: Optional[A2aTaskState] = Field(
+ default=None,
+ description="""Output only. The state of the task. The state of a new task is SUBMITTED by default. The state of a task can only be updated via AppendA2aTaskEvents API.""",
+ )
+ status_details: Optional[TaskStatusDetails] = Field(
+ default=None, description="""Optional. The status details of the task."""
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. The last update timestamp of the task.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Timestamp of when this task is considered expired. This is *always* provided on output, and is calculated based on the `ttl` if set on the request""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL (Time To Live) for the task. If not set, the task will expire in 24 hours by default. Valid range: (0 seconds, 1000 days]""",
+ )
+
+
+class A2aTaskDict(TypedDict, total=False):
+ """A task."""
+
+ context_id: Optional[str]
+ """Optional. A generic identifier for grouping related tasks (e.g., session_id, workflow_id)."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. The creation timestamp of the task."""
+
+ metadata: Optional[dict[str, Any]]
+ """Optional. Arbitrary, user-defined metadata."""
+
+ name: Optional[str]
+ """Identifier. The resource name of the task. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/a2aTasks/{a2a_task}`"""
+
+ next_event_sequence_number: Optional[int]
+ """Output only. The next event sequence number to be appended to the task. This value starts at 1 and is guaranteed to be monotonically increasing."""
+
+ output: Optional[TaskOutputDict]
+ """Optional. The final output of the task."""
+
+ state: Optional[A2aTaskState]
+ """Output only. The state of the task. The state of a new task is SUBMITTED by default. The state of a task can only be updated via AppendA2aTaskEvents API."""
+
+ status_details: Optional[TaskStatusDetailsDict]
+ """Optional. The status details of the task."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. The last update timestamp of the task."""
+
+ expire_time: Optional[datetime.datetime]
+ """Optional. Timestamp of when this task is considered expired. This is *always* provided on output, and is calculated based on the `ttl` if set on the request"""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL (Time To Live) for the task. If not set, the task will expire in 24 hours by default. Valid range: (0 seconds, 1000 days]"""
+
+
+A2aTaskOrDict = Union[A2aTask, A2aTaskDict]
+
+
+class ListAgentEngineTasksConfig(_common.BaseModel):
+ """Config for listing agent engine tasks."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+ order_by: Optional[str] = Field(
+ default=None,
+ description="""A comma-separated list of fields to order by, sorted in ascending order.
+ Use "desc" after a field name for descending.
+ If this field is omitted, the default ordering is `create_time` descending.
+ More detail in [AIP-132](https://google.aip.dev/132).
+
+ Supported fields:
+ * `create_time`
+ * `update_time`
+
+ Example: `create_time desc`.""",
+ )
+
+
+class ListAgentEngineTasksConfigDict(TypedDict, total=False):
+ """Config for listing agent engine tasks."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+ order_by: Optional[str]
+ """A comma-separated list of fields to order by, sorted in ascending order.
+ Use "desc" after a field name for descending.
+ If this field is omitted, the default ordering is `create_time` descending.
+ More detail in [AIP-132](https://google.aip.dev/132).
+
+ Supported fields:
+ * `create_time`
+ * `update_time`
+
+ Example: `create_time desc`."""
+
+
+ListAgentEngineTasksConfigOrDict = Union[
+ ListAgentEngineTasksConfig, ListAgentEngineTasksConfigDict
+]
+
+
+class _ListAgentEngineTasksRequestParameters(_common.BaseModel):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[ListAgentEngineTasksConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineTasksRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[ListAgentEngineTasksConfigDict]
+ """"""
+
+
+_ListAgentEngineTasksRequestParametersOrDict = Union[
+ _ListAgentEngineTasksRequestParameters, _ListAgentEngineTasksRequestParametersDict
+]
+
+
+class ListAgentEngineTasksResponse(_common.BaseModel):
+ """Response for listing agent engine tasks."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ a2aTasks: Optional[list[A2aTask]] = Field(
+ default=None, description="""List of agent engine tasks."""
+ )
+
+
+class ListAgentEngineTasksResponseDict(TypedDict, total=False):
+ """Response for listing agent engine tasks."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ a2aTasks: Optional[list[A2aTaskDict]]
+ """List of agent engine tasks."""
+
+
+ListAgentEngineTasksResponseOrDict = Union[
+ ListAgentEngineTasksResponse, ListAgentEngineTasksResponseDict
+]
+
+
+class CreateAgentEngineTaskConfig(_common.BaseModel):
+ """Config for creating a Session."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ context_id: Optional[str] = Field(
+ default=None, description="""The context id of the task to create."""
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None, description="""The metadata of the task to create."""
+ )
+ status_details: Optional[TaskStatusDetails] = Field(
+ default=None, description="""The status details of the task to create."""
+ )
+ output: Optional[TaskOutput] = Field(
+ default=None, description="""The output of the task to create."""
+ )
+
+
+class CreateAgentEngineTaskConfigDict(TypedDict, total=False):
+ """Config for creating a Session."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ context_id: Optional[str]
+ """The context id of the task to create."""
+
+ metadata: Optional[dict[str, Any]]
+ """The metadata of the task to create."""
+
+ status_details: Optional[TaskStatusDetailsDict]
+ """The status details of the task to create."""
+
+ output: Optional[TaskOutputDict]
+ """The output of the task to create."""
+
+
+CreateAgentEngineTaskConfigOrDict = Union[
+ CreateAgentEngineTaskConfig, CreateAgentEngineTaskConfigDict
+]
+
+
+class _CreateAgentEngineTaskRequestParameters(_common.BaseModel):
+ """Parameters for creating Agent Engine Tasks."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to create the task under.""",
+ )
+ a2a_task_id: Optional[str] = Field(
+ default=None, description="""The ID of the task."""
+ )
+ config: Optional[CreateAgentEngineTaskConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateAgentEngineTaskRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating Agent Engine Tasks."""
+
+ name: Optional[str]
+ """Name of the agent engine to create the task under."""
+
+ a2a_task_id: Optional[str]
+ """The ID of the task."""
+
+ config: Optional[CreateAgentEngineTaskConfigDict]
+ """"""
+
+
+_CreateAgentEngineTaskRequestParametersOrDict = Union[
+ _CreateAgentEngineTaskRequestParameters, _CreateAgentEngineTaskRequestParametersDict
+]
+
+
+class TaskMetadataChange(_common.BaseModel):
+ """An event representing a change to the task's top-level metadata. example: metadata_change: { new_metadata: { "name": "My task", } update_mask: { paths: "name" } }"""
+
+ new_metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Required. The complete state of the metadata object *after* the change.""",
+ )
+ update_mask: Optional[str] = Field(
+ default=None,
+ description="""Optional. A field mask indicating which paths in the Struct were changed. If not set, all fields will be updated. go/aip-internal/cloud-standard/2412""",
+ )
+
+
+class TaskMetadataChangeDict(TypedDict, total=False):
+ """An event representing a change to the task's top-level metadata. example: metadata_change: { new_metadata: { "name": "My task", } update_mask: { paths: "name" } }"""
+
+ new_metadata: Optional[dict[str, Any]]
+ """Required. The complete state of the metadata object *after* the change."""
+
+ update_mask: Optional[str]
+ """Optional. A field mask indicating which paths in the Struct were changed. If not set, all fields will be updated. go/aip-internal/cloud-standard/2412"""
+
+
+TaskMetadataChangeOrDict = Union[TaskMetadataChange, TaskMetadataChangeDict]
+
+
+class TaskArtifactChange(_common.BaseModel):
+ """Describes changes to the artifact list."""
+
+ added_artifacts: Optional[list[TaskArtifact]] = Field(
+ default=None,
+ description="""Optional. A list of brand-new artifacts created in this event.""",
+ )
+ deleted_artifact_ids: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. A list of artifact IDs that were removed in this event.""",
+ )
+ updated_artifacts: Optional[list[TaskArtifact]] = Field(
+ default=None,
+ description="""Optional. A list of existing artifacts that were modified in this event.""",
+ )
+
+
+class TaskArtifactChangeDict(TypedDict, total=False):
+ """Describes changes to the artifact list."""
+
+ added_artifacts: Optional[list[TaskArtifactDict]]
+ """Optional. A list of brand-new artifacts created in this event."""
+
+ deleted_artifact_ids: Optional[list[str]]
+ """Optional. A list of artifact IDs that were removed in this event."""
+
+ updated_artifacts: Optional[list[TaskArtifactDict]]
+ """Optional. A list of existing artifacts that were modified in this event."""
+
+
+TaskArtifactChangeOrDict = Union[TaskArtifactChange, TaskArtifactChangeDict]
+
+
+class TaskOutputChange(_common.BaseModel):
+ """An event representing a change to the task's outputs."""
+
+ task_artifact_change: Optional[TaskArtifactChange] = Field(
+ default=None,
+ description="""Required. A granular change to the list of artifacts.""",
+ )
+
+
+class TaskOutputChangeDict(TypedDict, total=False):
+ """An event representing a change to the task's outputs."""
+
+ task_artifact_change: Optional[TaskArtifactChangeDict]
+ """Required. A granular change to the list of artifacts."""
+
+
+TaskOutputChangeOrDict = Union[TaskOutputChange, TaskOutputChangeDict]
+
+
+class TaskStateChange(_common.BaseModel):
+ """A message representing a change in a task's state."""
+
+ new_state: Optional[State] = Field(
+ default=None, description="""Required. The new state of the task."""
+ )
+
+
+class TaskStateChangeDict(TypedDict, total=False):
+ """A message representing a change in a task's state."""
+
+ new_state: Optional[State]
+ """Required. The new state of the task."""
+
+
+TaskStateChangeOrDict = Union[TaskStateChange, TaskStateChangeDict]
+
+
+class TaskStatusDetailsChange(_common.BaseModel):
+ """Represents a change to the task's status details."""
+
+ new_task_status: Optional[TaskStatusDetails] = Field(
+ default=None,
+ description="""Required. The complete state of the task's status *after* the change.""",
+ )
+
+
+class TaskStatusDetailsChangeDict(TypedDict, total=False):
+ """Represents a change to the task's status details."""
+
+ new_task_status: Optional[TaskStatusDetailsDict]
+ """Required. The complete state of the task's status *after* the change."""
+
+
+TaskStatusDetailsChangeOrDict = Union[
+ TaskStatusDetailsChange, TaskStatusDetailsChangeDict
+]
+
+
+class TaskEventData(_common.BaseModel):
+ """Data for a TaskEvent."""
+
+ metadata_change: Optional[TaskMetadataChange] = Field(
+ default=None, description="""Optional. A change to the task's metadata."""
+ )
+ output_change: Optional[TaskOutputChange] = Field(
+ default=None, description="""Optional. A change to the task's final outputs."""
+ )
+ state_change: Optional[TaskStateChange] = Field(
+ default=None, description="""Optional. A change in the task's state."""
+ )
+ status_details_change: Optional[TaskStatusDetailsChange] = Field(
+ default=None,
+ description="""Optional. A change to the framework-specific status details.""",
+ )
+
+
+class TaskEventDataDict(TypedDict, total=False):
+ """Data for a TaskEvent."""
+
+ metadata_change: Optional[TaskMetadataChangeDict]
+ """Optional. A change to the task's metadata."""
+
+ output_change: Optional[TaskOutputChangeDict]
+ """Optional. A change to the task's final outputs."""
+
+ state_change: Optional[TaskStateChangeDict]
+ """Optional. A change in the task's state."""
+
+ status_details_change: Optional[TaskStatusDetailsChangeDict]
+ """Optional. A change to the framework-specific status details."""
+
+
+TaskEventDataOrDict = Union[TaskEventData, TaskEventDataDict]
+
+
+class TaskEvent(_common.BaseModel):
+ """A task event."""
+
+ create_time: Optional[datetime.datetime] = Field(
+ default=None, description="""Output only. The create time of the event."""
+ )
+ event_data: Optional[TaskEventData] = Field(
+ default=None, description="""Required. The delta associated with the event."""
+ )
+ event_sequence_number: Optional[int] = Field(
+ default=None,
+ description="""Required. The sequence number of the event. This is used to uniquely identify the event within the task and order events chronologically. This is a id generated by the SDK.""",
+ )
+
+
+class TaskEventDict(TypedDict, total=False):
+ """A task event."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. The create time of the event."""
+
+ event_data: Optional[TaskEventDataDict]
+ """Required. The delta associated with the event."""
+
+ event_sequence_number: Optional[int]
+ """Required. The sequence number of the event. This is used to uniquely identify the event within the task and order events chronologically. This is a id generated by the SDK."""
+
+
+TaskEventOrDict = Union[TaskEvent, TaskEventDict]
+
+
+class AppendAgentEngineTaskEventConfig(_common.BaseModel):
+ """Config for appending Agent Engine task events."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class AppendAgentEngineTaskEventConfigDict(TypedDict, total=False):
+ """Config for appending Agent Engine task events."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+AppendAgentEngineTaskEventConfigOrDict = Union[
+ AppendAgentEngineTaskEventConfig, AppendAgentEngineTaskEventConfigDict
+]
+
+
+class _AppendAgentEngineTaskEventRequestParameters(_common.BaseModel):
+ """Parameters for appending Agent Engine task events."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the Agent Engine task to append the events to.""",
+ )
+ task_events: Optional[list[TaskEvent]] = Field(
+ default=None, description="""The events to append to the task."""
+ )
+ config: Optional[AppendAgentEngineTaskEventConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _AppendAgentEngineTaskEventRequestParametersDict(TypedDict, total=False):
+ """Parameters for appending Agent Engine task events."""
+
+ name: Optional[str]
+ """Name of the Agent Engine task to append the events to."""
+
+ task_events: Optional[list[TaskEventDict]]
+ """The events to append to the task."""
+
+ config: Optional[AppendAgentEngineTaskEventConfigDict]
+ """"""
+
+
+_AppendAgentEngineTaskEventRequestParametersOrDict = Union[
+ _AppendAgentEngineTaskEventRequestParameters,
+ _AppendAgentEngineTaskEventRequestParametersDict,
+]
+
+
+class AppendAgentEngineTaskEventResponse(_common.BaseModel):
+ """Response for appending Agent Engine task events."""
+
+ pass
+
+
+class AppendAgentEngineTaskEventResponseDict(TypedDict, total=False):
+ """Response for appending Agent Engine task events."""
+
+ pass
+
+
+AppendAgentEngineTaskEventResponseOrDict = Union[
+ AppendAgentEngineTaskEventResponse, AppendAgentEngineTaskEventResponseDict
+]
+
+
+class ListAgentEngineTaskEventsConfig(_common.BaseModel):
+ """Config for listing agent engine tasks."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+ order_by: Optional[str] = Field(
+ default=None,
+ description="""A comma-separated list of fields to order by, sorted in ascending order.
+ Use "desc" after a field name for descending.
+ If this field is omitted, the default ordering is `create_time` descending.
+ More detail in [AIP-132](https://google.aip.dev/132).
+
+ Supported fields:
+ * `create_time`
+ * `update_time`
+
+ Example: `create_time desc`.""",
+ )
+
+
+class ListAgentEngineTaskEventsConfigDict(TypedDict, total=False):
+ """Config for listing agent engine tasks."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+ order_by: Optional[str]
+ """A comma-separated list of fields to order by, sorted in ascending order.
+ Use "desc" after a field name for descending.
+ If this field is omitted, the default ordering is `create_time` descending.
+ More detail in [AIP-132](https://google.aip.dev/132).
+
+ Supported fields:
+ * `create_time`
+ * `update_time`
+
+ Example: `create_time desc`."""
+
+
+ListAgentEngineTaskEventsConfigOrDict = Union[
+ ListAgentEngineTaskEventsConfig, ListAgentEngineTaskEventsConfigDict
+]
+
+
+class _ListAgentEngineTaskEventsRequestParameters(_common.BaseModel):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the Agent Engine task."""
+ )
+ config: Optional[ListAgentEngineTaskEventsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineTaskEventsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str]
+ """Name of the Agent Engine task."""
+
+ config: Optional[ListAgentEngineTaskEventsConfigDict]
+ """"""
+
+
+_ListAgentEngineTaskEventsRequestParametersOrDict = Union[
+ _ListAgentEngineTaskEventsRequestParameters,
+ _ListAgentEngineTaskEventsRequestParametersDict,
+]
+
+
+class ListAgentEngineTaskEventsResponse(_common.BaseModel):
+ """Response for listing Agent Engine tasks events."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ taskEvents: Optional[list[TaskEvent]] = Field(
+ default=None, description="""List of Agent Engine task events."""
+ )
+
+
+class ListAgentEngineTaskEventsResponseDict(TypedDict, total=False):
+ """Response for listing Agent Engine tasks events."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ taskEvents: Optional[list[TaskEventDict]]
+ """List of Agent Engine task events."""
+
+
+ListAgentEngineTaskEventsResponseOrDict = Union[
+ ListAgentEngineTaskEventsResponse, ListAgentEngineTaskEventsResponseDict
+]
+
+
+class CreateEvaluationItemConfig(_common.BaseModel):
+ """Config to create an evaluation item."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class CreateEvaluationItemConfigDict(TypedDict, total=False):
+ """Config to create an evaluation item."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+CreateEvaluationItemConfigOrDict = Union[
+ CreateEvaluationItemConfig, CreateEvaluationItemConfigDict
+]
+
+
+class _CreateEvaluationItemParameters(_common.BaseModel):
+ """Represents a job that creates an evaluation item."""
+
+ evaluation_item_type: Optional[str] = Field(default=None, description="""""")
+ gcs_uri: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[CreateEvaluationItemConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateEvaluationItemParametersDict(TypedDict, total=False):
+ """Represents a job that creates an evaluation item."""
+
+ evaluation_item_type: Optional[str]
+ """"""
+
+ gcs_uri: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ config: Optional[CreateEvaluationItemConfigDict]
+ """"""
+
+
+_CreateEvaluationItemParametersOrDict = Union[
+ _CreateEvaluationItemParameters, _CreateEvaluationItemParametersDict
+]
+
+
+class PromptTemplateData(_common.BaseModel):
+ """Holds data for a prompt template.
+
+ Message to hold a prompt template and the values to populate the template.
+ """
+
+ values: Optional[dict[str, genai_types.Content]] = Field(
+ default=None, description="""The values for fields in the prompt template."""
+ )
+
+
+class PromptTemplateDataDict(TypedDict, total=False):
+ """Holds data for a prompt template.
+
+ Message to hold a prompt template and the values to populate the template.
+ """
+
+ values: Optional[dict[str, genai_types.ContentDict]]
+ """The values for fields in the prompt template."""
+
+
+PromptTemplateDataOrDict = Union[PromptTemplateData, PromptTemplateDataDict]
+
+
+class EvaluationPrompt(_common.BaseModel):
+ """Represents the prompt to be evaluated."""
+
+ text: Optional[str] = Field(default=None, description="""Text prompt.""")
+ value: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Fields and values that can be used to populate the prompt template.""",
+ )
+ prompt_template_data: Optional[PromptTemplateData] = Field(
+ default=None, description="""Prompt template data."""
+ )
+ user_scenario: Optional[evals_types.UserScenario] = Field(
+ default=None,
+ description="""User scenario to help simulate multi-turn agent run results.""",
+ )
+
+
+class EvaluationPromptDict(TypedDict, total=False):
+ """Represents the prompt to be evaluated."""
+
+ text: Optional[str]
+ """Text prompt."""
+
+ value: Optional[dict[str, Any]]
+ """Fields and values that can be used to populate the prompt template."""
+
+ prompt_template_data: Optional[PromptTemplateDataDict]
+ """Prompt template data."""
+
+ user_scenario: Optional[evals_types.UserScenario]
+ """User scenario to help simulate multi-turn agent run results."""
+
+
+EvaluationPromptOrDict = Union[EvaluationPrompt, EvaluationPromptDict]
+
+
+class CandidateResponse(_common.BaseModel):
+ """Responses from model or agent."""
+
+ candidate: Optional[str] = Field(
+ default=None,
+ description="""The name of the candidate that produced the response.""",
+ )
+ text: Optional[str] = Field(default=None, description="""The text response.""")
+ value: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Fields and values that can be used to populate the response template.""",
+ )
+ events: Optional[list[genai_types.Content]] = Field(
+ default=None,
+ description="""Intermediate events (such as tool calls and responses) that led to the final response.""",
+ )
+ agent_data: Optional[evals_types.AgentData] = Field(
+ default=None,
+ description="""Represents the complete execution trace of an anget conversation,
+ which can involve single or multiple agents. This field is used to
+ provide the full output of an agent's run, including all turns and
+ events, for direct evaluation.""",
+ )
+
+
+class CandidateResponseDict(TypedDict, total=False):
+ """Responses from model or agent."""
+
+ candidate: Optional[str]
+ """The name of the candidate that produced the response."""
+
+ text: Optional[str]
+ """The text response."""
+
+ value: Optional[dict[str, Any]]
+ """Fields and values that can be used to populate the response template."""
+
+ events: Optional[list[genai_types.ContentDict]]
+ """Intermediate events (such as tool calls and responses) that led to the final response."""
+
+ agent_data: Optional[evals_types.AgentData]
+ """Represents the complete execution trace of an anget conversation,
+ which can involve single or multiple agents. This field is used to
+ provide the full output of an agent's run, including all turns and
+ events, for direct evaluation."""
+
+
+CandidateResponseOrDict = Union[CandidateResponse, CandidateResponseDict]
+
+
+class EvaluationItemRequest(_common.BaseModel):
+ """Single evaluation request."""
+
+ prompt: Optional[EvaluationPrompt] = Field(
+ default=None, description="""The request/prompt to evaluate."""
+ )
+ golden_response: Optional[CandidateResponse] = Field(
+ default=None, description="""The ideal response or ground truth."""
+ )
+ rubrics: Optional[dict[str, "RubricGroup"]] = Field(
+ default=None,
+ description="""Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group.""",
+ )
+ candidate_responses: Optional[list[CandidateResponse]] = Field(
+ default=None,
+ description="""Responses from model under test and other baseline models for comparison.""",
+ )
+
+
+class EvaluationItemRequestDict(TypedDict, total=False):
+ """Single evaluation request."""
+
+ prompt: Optional[EvaluationPromptDict]
+ """The request/prompt to evaluate."""
+
+ golden_response: Optional[CandidateResponseDict]
+ """The ideal response or ground truth."""
+
+ rubrics: Optional[dict[str, "RubricGroupDict"]]
+ """Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group."""
+
+ candidate_responses: Optional[list[CandidateResponseDict]]
+ """Responses from model under test and other baseline models for comparison."""
+
+
+EvaluationItemRequestOrDict = Union[EvaluationItemRequest, EvaluationItemRequestDict]
+
+
+class EvaluationItemResult(_common.BaseModel):
+ """Represents the result of an evaluation item."""
+
+ evaluation_request: Optional[str] = Field(
+ default=None, description="""The request item that was evaluated."""
+ )
+ evaluation_run: Optional[str] = Field(
+ default=None,
+ description="""The evaluation run that was used to generate the result.""",
+ )
+ request: Optional[EvaluationItemRequest] = Field(
+ default=None, description="""The request that was evaluated."""
+ )
+ metric: Optional[str] = Field(
+ default=None, description="""The metric that was evaluated."""
+ )
+ candidate_results: Optional[list[evals_types.CandidateResult]] = Field(
+ default=None, description="""TThe results for the metric."""
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None, description="""Metadata about the evaluation result."""
+ )
+
+
+class EvaluationItemResultDict(TypedDict, total=False):
+ """Represents the result of an evaluation item."""
+
+ evaluation_request: Optional[str]
+ """The request item that was evaluated."""
+
+ evaluation_run: Optional[str]
+ """The evaluation run that was used to generate the result."""
+
+ request: Optional[EvaluationItemRequestDict]
+ """The request that was evaluated."""
+
+ metric: Optional[str]
+ """The metric that was evaluated."""
+
+ candidate_results: Optional[list[evals_types.CandidateResult]]
+ """TThe results for the metric."""
+
+ metadata: Optional[dict[str, Any]]
+ """Metadata about the evaluation result."""
+
+
+EvaluationItemResultOrDict = Union[EvaluationItemResult, EvaluationItemResultDict]
+
+
+class EvaluationItem(_common.BaseModel):
+ """EvaluationItem is a single evaluation request or result.
+
+ The content of an EvaluationItem is immutable - it cannot be updated once
+ created. EvaluationItems can be deleted when no longer needed.
+ """
+
+ name: Optional[str] = Field(
+ default=None, description="""The resource name of the EvaluationItem."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the EvaluationItem."""
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None, description="""Metadata for the EvaluationItem."""
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None, description="""Labels for the EvaluationItem."""
+ )
+ evaluation_item_type: Optional[EvaluationItemType] = Field(
+ default=None, description="""The type of the EvaluationItem."""
+ )
+ evaluation_request: Optional[EvaluationItemRequest] = Field(
+ default=None, description="""The request to evaluate."""
+ )
+ evaluation_response: Optional[EvaluationItemResult] = Field(
+ default=None, description="""The response from evaluation."""
+ )
+ gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""The Cloud Storage object where the request or response is stored.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None, description="""Timestamp when this item was created."""
+ )
+ error: Optional[genai_types.GoogleRpcStatus] = Field(
+ default=None, description="""Error for the evaluation item."""
+ )
+
+ # TODO(b/448806531): Remove all the overridden _from_response methods once the
+ # ticket is resolved and published.
+ @classmethod
+ def _from_response(
+ cls: typing.Type["EvaluationItem"],
+ *,
+ response: dict[str, object],
+ kwargs: dict[str, object],
+ ) -> "EvaluationItem":
+ """Converts a dictionary response into a EvaluationItem object."""
+
+ response = _camel_key_to_snake(response)
+ result = super()._from_response(response=response, kwargs=kwargs)
+ return result
+
+
+class EvaluationItemDict(TypedDict, total=False):
+ """EvaluationItem is a single evaluation request or result.
+
+ The content of an EvaluationItem is immutable - it cannot be updated once
+ created. EvaluationItems can be deleted when no longer needed.
+ """
+
+ name: Optional[str]
+ """The resource name of the EvaluationItem."""
+
+ display_name: Optional[str]
+ """The display name of the EvaluationItem."""
+
+ metadata: Optional[dict[str, Any]]
+ """Metadata for the EvaluationItem."""
+
+ labels: Optional[dict[str, str]]
+ """Labels for the EvaluationItem."""
+
+ evaluation_item_type: Optional[EvaluationItemType]
+ """The type of the EvaluationItem."""
+
+ evaluation_request: Optional[EvaluationItemRequestDict]
+ """The request to evaluate."""
+
+ evaluation_response: Optional[EvaluationItemResultDict]
+ """The response from evaluation."""
+
+ gcs_uri: Optional[str]
+ """The Cloud Storage object where the request or response is stored."""
+
+ create_time: Optional[datetime.datetime]
+ """Timestamp when this item was created."""
+
+ error: Optional[genai_types.GoogleRpcStatusDict]
+ """Error for the evaluation item."""
+
+
+EvaluationItemOrDict = Union[EvaluationItem, EvaluationItemDict]
+
+
+class Metric(_common.BaseModel):
+ """The metric used for evaluation."""
+
+ name: Optional[str] = Field(default=None, description="""The name of the metric.""")
+ custom_function: Optional[Union[str, Callable[..., Any]]] = Field(
+ default=None,
+ description="""The custom function that defines the end-to-end logic for metric computation.""",
+ )
+ prompt_template: Optional[str] = Field(
+ default=None, description="""The prompt template for the metric."""
+ )
+ judge_model_system_instruction: Optional[str] = Field(
+ default=None, description="""The system instruction for the judge model."""
+ )
+ return_raw_output: Optional[bool] = Field(
+ default=None,
+ description="""Whether to return the raw output from the judge model.""",
+ )
+ parse_and_reduce_fn: Optional[Callable[..., Any]] = Field(
+ default=None,
+ description="""The parse and reduce function for the judge model.""",
+ )
+ aggregate_summary_fn: Optional[Callable[..., Any]] = Field(
+ default=None,
+ description="""The aggregate summary function for the judge model.""",
+ )
+ remote_custom_function: Optional[str] = Field(
+ default=None,
+ description="""The evaluation function for the custom code execution metric. This custom code is run remotely in the evaluation service.""",
+ )
+ judge_model: Optional[str] = Field(
+ default=None, description="""The judge model for the metric."""
+ )
+ judge_model_generation_config: Optional[genai_types.GenerationConfig] = Field(
+ default=None,
+ description="""The generation config for the judge LLM (temperature, top_k, top_p, etc).""",
+ )
+ judge_model_sampling_count: Optional[int] = Field(
+ default=None, description="""The sampling count for the judge model."""
+ )
+ rubric_group_name: Optional[str] = Field(
+ default=None,
+ description="""The rubric group name for the rubric-based metric.""",
+ )
+ metric_spec_parameters: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional steering instruction parameters for the automated predefined metric.""",
+ )
+ metric_resource_name: Optional[str] = Field(
+ default=None,
+ description="""The resource name of the metric definition. Example: projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric_id}""",
+ )
+
+ # Allow extra fields to support metric-specific config fields.
+ model_config = ConfigDict(extra="allow")
+
+ _is_predefined: bool = PrivateAttr(default=False)
+ """A boolean indicating whether the metric is predefined."""
+
+ _config_source: Optional[str] = PrivateAttr(default=None)
+ """An optional string indicating the source of the metric configuration."""
+
+ _version: Optional[str] = PrivateAttr(default=None)
+ """An optional string indicating the version of the metric."""
+
+ @model_validator(mode="after")
+ @classmethod
+ def validate_name(cls, model: "Metric") -> "Metric":
+ if not model.name:
+ raise ValueError("Metric name cannot be empty.")
+ model.name = model.name.lower()
+ return model
+
+ def to_yaml_file(self, file_path: str, version: Optional[str] = None) -> None:
+ """Dumps the metric object to a YAML file.
+
+ Args:
+ file_path: The path to the YAML file.
+ version: Optional version string to include in the YAML output.
+
+ Raises:
+ ImportError: If the pyyaml library is not installed.
+ """
+ if yaml is None:
+ raise ImportError(
+ "YAML serialization requires the pyyaml library. Please install"
+ " it using 'pip install google-cloud-aiplatform[evaluation]'."
+ )
+
+ fields_to_exclude = {
+ field_name
+ for field_name, field_info in self.model_fields.items()
+ if self.__getattribute__(field_name) is not None
+ and isinstance(self.__getattribute__(field_name), Callable)
+ }
+
+ data_to_dump = self.model_dump(
+ exclude_unset=True,
+ exclude_none=True,
+ mode="json",
+ exclude=fields_to_exclude if fields_to_exclude else None,
+ )
+
+ if version:
+ data_to_dump["version"] = version
+
+ with open(file_path, "w", encoding="utf-8") as f:
+ yaml.dump(data_to_dump, f, sort_keys=False, allow_unicode=True)
+
+
+class CodeExecutionMetric(Metric):
+ """A metric that executes custom Python code for evaluation."""
+
+ # You can use standard Pydantic Field syntax here because this is raw Python code
+ custom_function: Optional[str] = Field(
+ default=None,
+ description="""The Python function code to be executed on the server side.""",
+ )
+
+ # You can also add hand-written validators or methods here
+ @field_validator("custom_function")
+ @classmethod
+ def validate_code(cls, value: Optional[str]) -> Optional[str]:
+ if value and "def evaluate" not in value:
+ raise ValueError(
+ "custom_function must contain a 'def evaluate(instance):' signature."
+ )
+ return value
+
+
+class LLMMetric(Metric):
+ """A metric that uses LLM-as-a-judge for evaluation."""
+
+ rubric_group_name: Optional[str] = Field(
+ default=None,
+ description="""Optional. The name of the column in the EvaluationDataset containing the list of rubrics to use for this metric.""",
+ )
+
+ @field_validator("prompt_template", mode="before")
+ @classmethod
+ def validate_prompt_template(cls, value: Union[str, "MetricPromptBuilder"]) -> str:
+ """Validates prompt template to be a non-empty string."""
+ if value is None:
+ raise ValueError("Prompt template cannot be empty.")
+ if isinstance(value, MetricPromptBuilder):
+ value = str(value)
+ if not value.strip():
+ raise ValueError("Prompt template cannot be an empty string.")
+ return value
+
+ @field_validator("judge_model_sampling_count")
+ @classmethod
+ def validate_judge_model_sampling_count(cls, value: Optional[int]) -> Optional[int]:
+ """Validates judge_model_sampling_count to be between 1 and 32."""
+ if value is not None and (value < 1 or value > 32):
+ raise ValueError("judge_model_sampling_count must be between 1 and 32.")
+ return value
+
+ @classmethod
+ def load(cls, config_path: str, client: Optional[Any] = None) -> "LLMMetric":
+ """Loads a metric configuration from a YAML or JSON file.
+
+ This method allows for the creation of an LLMMetric instance from a
+ local file path or a Google Cloud Storage (GCS) URI. It will automatically
+ detect the file type (.yaml, .yml, or .json) and parse it accordingly.
+
+ Args:
+ config_path: The local path or GCS URI (e.g., 'gs://bucket/metric.yaml')
+ to the metric configuration file.
+ client: Optional. The Vertex AI client instance to use for authentication.
+ If not provided, Application Default Credentials (ADC) will be used.
+
+ Returns:
+ An instance of LLMMetric configured with the loaded data.
+
+ Raises:
+ ValueError: If the file path is invalid or the file content cannot be parsed.
+ ImportError: If a required library like 'PyYAML' or 'google-cloud-storage' is not installed.
+ IOError: If the file cannot be read from the specified path.
+ """
+ file_extension = os.path.splitext(config_path)[1].lower()
+ if file_extension not in [".yaml", ".yml", ".json"]:
+ raise ValueError(
+ "Unsupported file extension for metric config. Must be .yaml, .yml, or .json"
+ )
+
+ content_str: str
+ if config_path.startswith("gs://"):
+ try:
+ from google.cloud import storage # type: ignore[attr-defined]
+
+ storage_client = storage.Client(
+ credentials=client._api_client._credentials if client else None
+ )
+ path_without_prefix = config_path[len("gs://") :]
+ bucket_name, blob_path = path_without_prefix.split("/", 1)
+
+ bucket = storage_client.bucket(bucket_name)
+ blob = bucket.blob(blob_path)
+ content_str = blob.download_as_bytes().decode("utf-8")
+ except ImportError as e:
+ raise ImportError(
+ "Reading from GCS requires the 'google-cloud-storage' library. Please install it with 'pip install google-cloud-aiplatform[evaluation]'."
+ ) from e
+ except Exception as e:
+ raise IOError(f"Failed to read from GCS path {config_path}: {e}") from e
+ else:
+ try:
+ with open(config_path, "r", encoding="utf-8") as f:
+ content_str = f.read()
+ except FileNotFoundError:
+ raise FileNotFoundError(
+ f"Local configuration file not found at: {config_path}"
+ )
+ except Exception as e:
+ raise IOError(f"Failed to read local file {config_path}: {e}") from e
+
+ data: Dict[str, Any]
+
+ if file_extension in [".yaml", ".yml"]:
+ if yaml is None:
+ raise ImportError(
+ "YAML parsing requires the pyyaml library. Please install it with 'pip install google-cloud-aiplatform[evaluation]'."
+ )
+ data = yaml.safe_load(content_str)
+ elif file_extension == ".json":
+ data = json.loads(content_str)
+
+ if not isinstance(data, dict):
+ raise ValueError("Metric config content did not parse into a dictionary.")
+
+ return cls.model_validate(data)
+
+
+class MetricDict(TypedDict, total=False):
+ """The metric used for evaluation."""
+
+ name: Optional[str]
+ """The name of the metric."""
+
+ custom_function: Optional[Union[str, Callable[..., Any]]]
+ """The custom function that defines the end-to-end logic for metric computation."""
+
+ prompt_template: Optional[str]
+ """The prompt template for the metric."""
+
+ judge_model_system_instruction: Optional[str]
+ """The system instruction for the judge model."""
+
+ return_raw_output: Optional[bool]
+ """Whether to return the raw output from the judge model."""
+
+ parse_and_reduce_fn: Optional[Callable[..., Any]]
+ """The parse and reduce function for the judge model."""
+
+ aggregate_summary_fn: Optional[Callable[..., Any]]
+ """The aggregate summary function for the judge model."""
+
+ remote_custom_function: Optional[str]
+ """The evaluation function for the custom code execution metric. This custom code is run remotely in the evaluation service."""
+
+ judge_model: Optional[str]
+ """The judge model for the metric."""
+
+ judge_model_generation_config: Optional[genai_types.GenerationConfigDict]
+ """The generation config for the judge LLM (temperature, top_k, top_p, etc)."""
+
+ judge_model_sampling_count: Optional[int]
+ """The sampling count for the judge model."""
+
+ rubric_group_name: Optional[str]
+ """The rubric group name for the rubric-based metric."""
+
+ metric_spec_parameters: Optional[dict[str, Any]]
+ """Optional steering instruction parameters for the automated predefined metric."""
+
+ metric_resource_name: Optional[str]
+ """The resource name of the metric definition. Example: projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric_id}"""
+
+
+MetricOrDict = Union[Metric, MetricDict]
+
+
+class CreateEvaluationMetricConfig(_common.BaseModel):
+ """Config for creating an evaluation metric."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class CreateEvaluationMetricConfigDict(TypedDict, total=False):
+ """Config for creating an evaluation metric."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+CreateEvaluationMetricConfigOrDict = Union[
+ CreateEvaluationMetricConfig, CreateEvaluationMetricConfigDict
+]
+
+
+class _CreateEvaluationMetricParameters(_common.BaseModel):
+ """Parameters for creating an evaluation metric."""
+
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""The user-defined name of the evaluation metric.
+
+ The display name can be up to 128 characters long and can comprise any
+ UTF-8 characters.
+ """,
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the evaluation metric."""
+ )
+ metric: Optional[Metric] = Field(
+ default=None,
+ description="""The metric configuration of the evaluation metric.""",
+ )
+ config: Optional[CreateEvaluationMetricConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateEvaluationMetricParametersDict(TypedDict, total=False):
+ """Parameters for creating an evaluation metric."""
+
+ display_name: Optional[str]
+ """The user-defined name of the evaluation metric.
+
+ The display name can be up to 128 characters long and can comprise any
+ UTF-8 characters.
+ """
+
+ description: Optional[str]
+ """The description of the evaluation metric."""
+
+ metric: Optional[MetricDict]
+ """The metric configuration of the evaluation metric."""
+
+ config: Optional[CreateEvaluationMetricConfigDict]
+ """"""
+
+
+_CreateEvaluationMetricParametersOrDict = Union[
+ _CreateEvaluationMetricParameters, _CreateEvaluationMetricParametersDict
+]
+
+
+class CustomCodeExecutionSpec(_common.BaseModel):
+ """Specifies a metric using remote Python function execution.
+
+ This metric is computed by running user-defined Python functions remotely.
+ """
+
+ evaluation_function: Optional[str] = Field(
+ default=None,
+ description="""Required. Python function. Expected user to define the following function, e.g.: def evaluate(instance: dict[str, Any]) -> float: Please include this function signature in the code snippet. Instance is the evaluation instance, any fields populated in the instance are available to the function as instance[field_name]. Example: Example input: ``` instance= EvaluationInstance( response=EvaluationInstance.InstanceData(text="The answer is 4."), reference=EvaluationInstance.InstanceData(text="4") ) ``` Example converted input: ``` { 'response': {'text': 'The answer is 4.'}, 'reference': {'text': '4'} } ``` Example python function: ``` def evaluate(instance: dict[str, Any]) -> float: if instance'response' == instance'reference': return 1.0 return 0.0 ``` CustomCodeExecutionSpec is also supported in Batch Evaluation (EvalDataset RPC) and Tuning Evaluation. Each line in the input jsonl file will be converted to dict[str, Any] and passed to the evaluation function.""",
+ )
+ remote_custom_function: Optional[str] = Field(
+ default=None,
+ description="""A string representing a user-defined function for evaluation.
+ Expected user to define the following function, e.g.:
+ def evaluate(instance: dict[str, Any]) -> float:
+ Please include this function signature in the code snippet.
+ Instance is the evaluation instance, any fields populated in the instance
+ are available to the function as instance[field_name].""",
+ )
+
+
+class CustomCodeExecutionSpecDict(TypedDict, total=False):
+ """Specifies a metric using remote Python function execution.
+
+ This metric is computed by running user-defined Python functions remotely.
+ """
+
+ evaluation_function: Optional[str]
+ """Required. Python function. Expected user to define the following function, e.g.: def evaluate(instance: dict[str, Any]) -> float: Please include this function signature in the code snippet. Instance is the evaluation instance, any fields populated in the instance are available to the function as instance[field_name]. Example: Example input: ``` instance= EvaluationInstance( response=EvaluationInstance.InstanceData(text="The answer is 4."), reference=EvaluationInstance.InstanceData(text="4") ) ``` Example converted input: ``` { 'response': {'text': 'The answer is 4.'}, 'reference': {'text': '4'} } ``` Example python function: ``` def evaluate(instance: dict[str, Any]) -> float: if instance'response' == instance'reference': return 1.0 return 0.0 ``` CustomCodeExecutionSpec is also supported in Batch Evaluation (EvalDataset RPC) and Tuning Evaluation. Each line in the input jsonl file will be converted to dict[str, Any] and passed to the evaluation function."""
+
+ remote_custom_function: Optional[str]
+ """A string representing a user-defined function for evaluation.
+ Expected user to define the following function, e.g.:
+ def evaluate(instance: dict[str, Any]) -> float:
+ Please include this function signature in the code snippet.
+ Instance is the evaluation instance, any fields populated in the instance
+ are available to the function as instance[field_name]."""
+
+
+CustomCodeExecutionSpecOrDict = Union[
+ CustomCodeExecutionSpec, CustomCodeExecutionSpecDict
+]
+
+
+class UnifiedMetric(_common.BaseModel):
+ """The unified metric used for evaluation."""
+
+ bleu_spec: Optional[genai_types.BleuSpec] = Field(
+ default=None, description="""The Bleu metric spec."""
+ )
+ rouge_spec: Optional[genai_types.RougeSpec] = Field(
+ default=None, description="""The rouge metric spec."""
+ )
+ pointwise_metric_spec: Optional[genai_types.PointwiseMetricSpec] = Field(
+ default=None, description="""The pointwise metric spec."""
+ )
+ llm_based_metric_spec: Optional[genai_types.LLMBasedMetricSpec] = Field(
+ default=None, description="""The spec for an LLM based metric."""
+ )
+ custom_code_execution_spec: Optional[CustomCodeExecutionSpec] = Field(
+ default=None, description="""The spec for a custom code execution metric."""
+ )
+ predefined_metric_spec: Optional[genai_types.PredefinedMetricSpec] = Field(
+ default=None, description="""The spec for a pre-defined metric."""
+ )
+ computation_based_metric_spec: Optional[genai_types.ComputationBasedMetricSpec] = (
+ Field(default=None, description="""The spec for a computation based metric.""")
+ )
+
+
+class UnifiedMetricDict(TypedDict, total=False):
+ """The unified metric used for evaluation."""
+
+ bleu_spec: Optional[genai_types.BleuSpecDict]
+ """The Bleu metric spec."""
+
+ rouge_spec: Optional[genai_types.RougeSpecDict]
+ """The rouge metric spec."""
+
+ pointwise_metric_spec: Optional[genai_types.PointwiseMetricSpecDict]
+ """The pointwise metric spec."""
+
+ llm_based_metric_spec: Optional[genai_types.LLMBasedMetricSpecDict]
+ """The spec for an LLM based metric."""
+
+ custom_code_execution_spec: Optional[CustomCodeExecutionSpecDict]
+ """The spec for a custom code execution metric."""
+
+ predefined_metric_spec: Optional[genai_types.PredefinedMetricSpecDict]
+ """The spec for a pre-defined metric."""
+
+ computation_based_metric_spec: Optional[genai_types.ComputationBasedMetricSpecDict]
+ """The spec for a computation based metric."""
+
+
+UnifiedMetricOrDict = Union[UnifiedMetric, UnifiedMetricDict]
+
+
+class EvaluationMetric(_common.BaseModel):
+ """Represents an evaluation metric."""
+
+ name: Optional[str] = Field(
+ default=None, description="""The resource name of the evaluation metric."""
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""The user-friendly display name for the EvaluationMetric.""",
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the EvaluationMetric."""
+ )
+ metric: Optional[UnifiedMetric] = Field(
+ default=None,
+ description="""The metric configuration of the evaluation metric.""",
+ )
+
+
+class EvaluationMetricDict(TypedDict, total=False):
+ """Represents an evaluation metric."""
+
+ name: Optional[str]
+ """The resource name of the evaluation metric."""
+
+ display_name: Optional[str]
+ """The user-friendly display name for the EvaluationMetric."""
+
+ description: Optional[str]
+ """The description of the EvaluationMetric."""
+
+ metric: Optional[UnifiedMetricDict]
+ """The metric configuration of the evaluation metric."""
+
+
+EvaluationMetricOrDict = Union[EvaluationMetric, EvaluationMetricDict]
+
+
+class SamplingConfig(_common.BaseModel):
+ """Sampling config for a BigQuery request set."""
+
+ sampling_count: Optional[int] = Field(default=None, description="""""")
+ sampling_method: Optional[SamplingMethod] = Field(default=None, description="""""")
+ sampling_duration: Optional[str] = Field(default=None, description="""""")
+
+
+class SamplingConfigDict(TypedDict, total=False):
+ """Sampling config for a BigQuery request set."""
+
+ sampling_count: Optional[int]
+ """"""
+
+ sampling_method: Optional[SamplingMethod]
+ """"""
+
+ sampling_duration: Optional[str]
+ """"""
+
+
+SamplingConfigOrDict = Union[SamplingConfig, SamplingConfigDict]
+
+
+class BigQueryRequestSet(_common.BaseModel):
+ """Represents a BigQuery request set."""
+
+ uri: Optional[str] = Field(default=None, description="""""")
+ prompt_column: Optional[str] = Field(
+ default=None,
+ description="""The column name of the prompt in the BigQuery table. Used for EvaluationRun only.""",
+ )
+ rubrics_column: Optional[str] = Field(
+ default=None,
+ description="""The column name of the rubrics in the BigQuery table. Used for EvaluationRun only.""",
+ )
+ candidate_response_columns: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The column name of the response candidates in the BigQuery table. Used for EvaluationRun only.""",
+ )
+ sampling_config: Optional[SamplingConfig] = Field(
+ default=None,
+ description="""The sampling config for the BigQuery request set. Used for EvaluationRun only.""",
+ )
+
+
+class BigQueryRequestSetDict(TypedDict, total=False):
+ """Represents a BigQuery request set."""
+
+ uri: Optional[str]
+ """"""
+
+ prompt_column: Optional[str]
+ """The column name of the prompt in the BigQuery table. Used for EvaluationRun only."""
+
+ rubrics_column: Optional[str]
+ """The column name of the rubrics in the BigQuery table. Used for EvaluationRun only."""
+
+ candidate_response_columns: Optional[dict[str, str]]
+ """The column name of the response candidates in the BigQuery table. Used for EvaluationRun only."""
+
+ sampling_config: Optional[SamplingConfigDict]
+ """The sampling config for the BigQuery request set. Used for EvaluationRun only."""
+
+
+BigQueryRequestSetOrDict = Union[BigQueryRequestSet, BigQueryRequestSetDict]
+
+
+class EvaluationRunDataSource(_common.BaseModel):
+ """Represents an evaluation run data source."""
+
+ evaluation_set: Optional[str] = Field(default=None, description="""""")
+ bigquery_request_set: Optional[BigQueryRequestSet] = Field(
+ default=None, description=""""""
+ )
+
+
+class EvaluationRunDataSourceDict(TypedDict, total=False):
+ """Represents an evaluation run data source."""
+
+ evaluation_set: Optional[str]
+ """"""
+
+ bigquery_request_set: Optional[BigQueryRequestSetDict]
+ """"""
+
+
+EvaluationRunDataSourceOrDict = Union[
+ EvaluationRunDataSource, EvaluationRunDataSourceDict
+]
+
+
+class EvaluationRunMetric(_common.BaseModel):
+ """The metric used for evaluation run."""
+
+ metric: Optional[str] = Field(
+ default=None, description="""The name of the metric."""
+ )
+ metric_resource_name: Optional[str] = Field(
+ default=None,
+ description="""The resource name of the metric definition. Example: projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric_id}""",
+ )
+ metric_config: Optional[UnifiedMetric] = Field(
+ default=None, description="""The unified metric used for evaluation run."""
+ )
+
+
+class EvaluationRunMetricDict(TypedDict, total=False):
+ """The metric used for evaluation run."""
+
+ metric: Optional[str]
+ """The name of the metric."""
+
+ metric_resource_name: Optional[str]
+ """The resource name of the metric definition. Example: projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric_id}"""
+
+ metric_config: Optional[UnifiedMetricDict]
+ """The unified metric used for evaluation run."""
+
+
+EvaluationRunMetricOrDict = Union[EvaluationRunMetric, EvaluationRunMetricDict]
+
+
+class EvaluationRunPromptTemplate(_common.BaseModel):
+ """Prompt template used for inference.
+
+ Only one of `prompt_template` or `gcs_uri` should be set. If both are
+ provided, an error will be raised.
+ """
+
+ prompt_template: Optional[str] = Field(
+ default=None,
+ description="""Inline prompt template. Template variables should be in the format
+ "{var_name}". Only one of `prompt_template` or `gcs_uri` should be set.""",
+ )
+ gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""Prompt template stored in Cloud Storage. Format:
+ "gs://my-bucket/file-name.txt". Only one of `prompt_template` or `gcs_uri`
+ should be set.""",
+ )
+
+
+class EvaluationRunPromptTemplateDict(TypedDict, total=False):
+ """Prompt template used for inference.
+
+ Only one of `prompt_template` or `gcs_uri` should be set. If both are
+ provided, an error will be raised.
+ """
+
+ prompt_template: Optional[str]
+ """Inline prompt template. Template variables should be in the format
+ "{var_name}". Only one of `prompt_template` or `gcs_uri` should be set."""
+
+ gcs_uri: Optional[str]
+ """Prompt template stored in Cloud Storage. Format:
+ "gs://my-bucket/file-name.txt". Only one of `prompt_template` or `gcs_uri`
+ should be set."""
+
+
+EvaluationRunPromptTemplateOrDict = Union[
+ EvaluationRunPromptTemplate, EvaluationRunPromptTemplateDict
+]
+
+
+class LossAnalysisConfig(_common.BaseModel):
+ """Configuration for the loss analysis job."""
+
+ metric: Optional[str] = Field(
+ default=None,
+ description="""Required. The metric to analyze (e.g., "multi_turn_tool_use_quality_v1").""",
+ )
+ candidate: Optional[str] = Field(
+ default=None,
+ description="""Required. The candidate model/agent to analyze (e.g., "gemini-3.1-pro-preview"). This targets the specific CandidateResult within the EvaluationResult.""",
+ )
+ predefined_taxonomy: Optional[str] = Field(
+ default=None,
+ description="""Optional. The identifier for the pre-defined taxonomy to use (e.g., "agent_taxonomy_v1", "tool_use_v2"). If not specified, the service may select a default based on the metric.""",
+ )
+ max_top_cluster_count: Optional[int] = Field(
+ default=None,
+ description="""Optional. Limits the analysis to the top N clusters. If not specified or set to 0, all clusters are returned.""",
+ )
+
+
+class LossAnalysisConfigDict(TypedDict, total=False):
+ """Configuration for the loss analysis job."""
+
+ metric: Optional[str]
+ """Required. The metric to analyze (e.g., "multi_turn_tool_use_quality_v1")."""
+
+ candidate: Optional[str]
+ """Required. The candidate model/agent to analyze (e.g., "gemini-3.1-pro-preview"). This targets the specific CandidateResult within the EvaluationResult."""
+
+ predefined_taxonomy: Optional[str]
+ """Optional. The identifier for the pre-defined taxonomy to use (e.g., "agent_taxonomy_v1", "tool_use_v2"). If not specified, the service may select a default based on the metric."""
+
+ max_top_cluster_count: Optional[int]
+ """Optional. Limits the analysis to the top N clusters. If not specified or set to 0, all clusters are returned."""
+
+
+LossAnalysisConfigOrDict = Union[LossAnalysisConfig, LossAnalysisConfigDict]
+
+
+class EvaluationRunConfig(_common.BaseModel):
+ """The evaluation configuration used for the evaluation run."""
+
+ metrics: Optional[list[EvaluationRunMetric]] = Field(
+ default=None,
+ description="""The metrics to be calculated in the evaluation run.""",
+ )
+ output_config: Optional[genai_types.OutputConfig] = Field(
+ default=None, description="""The output config for the evaluation run."""
+ )
+ autorater_config: Optional[genai_types.AutoraterConfig] = Field(
+ default=None, description="""The autorater config for the evaluation run."""
+ )
+ prompt_template: Optional[EvaluationRunPromptTemplate] = Field(
+ default=None, description="""The prompt template used for inference."""
+ )
+ loss_analysis_config: Optional[list[LossAnalysisConfig]] = Field(
+ default=None,
+ description="""Specifications for loss analysis. Each config specifies a metric and candidate to analyze for loss patterns.""",
+ )
+ allow_cross_region_model: Optional[bool] = Field(
+ default=None,
+ description="""Allows the evaluation run to use cross region models. When this
+ flag is set, the service may route traffic to other regions if a model is
+ unavailable in the current region (e.g., to a `global`endpoint). If a
+ fully-qualified model endpoint resource name with a different region than
+ the run location is provided elsewhere in the run config, this flag must
+ be set to true or the request will fail.""",
+ )
+
+
+class EvaluationRunConfigDict(TypedDict, total=False):
+ """The evaluation configuration used for the evaluation run."""
+
+ metrics: Optional[list[EvaluationRunMetricDict]]
+ """The metrics to be calculated in the evaluation run."""
+
+ output_config: Optional[genai_types.OutputConfigDict]
+ """The output config for the evaluation run."""
+
+ autorater_config: Optional[genai_types.AutoraterConfigDict]
+ """The autorater config for the evaluation run."""
+
+ prompt_template: Optional[EvaluationRunPromptTemplateDict]
+ """The prompt template used for inference."""
+
+ loss_analysis_config: Optional[list[LossAnalysisConfigDict]]
+ """Specifications for loss analysis. Each config specifies a metric and candidate to analyze for loss patterns."""
+
+ allow_cross_region_model: Optional[bool]
+ """Allows the evaluation run to use cross region models. When this
+ flag is set, the service may route traffic to other regions if a model is
+ unavailable in the current region (e.g., to a `global`endpoint). If a
+ fully-qualified model endpoint resource name with a different region than
+ the run location is provided elsewhere in the run config, this flag must
+ be set to true or the request will fail."""
+
+
+EvaluationRunConfigOrDict = Union[EvaluationRunConfig, EvaluationRunConfigDict]
+
+
+class EvaluationRunAgentConfig(_common.BaseModel):
+ """This field is experimental and may change in future versions.
+
+ Agent config for an evaluation run.
+ """
+
+ developer_instruction: Optional[genai_types.Content] = Field(
+ default=None, description="""The developer instruction for the agent."""
+ )
+ tools: Optional[list[genai_types.Tool]] = Field(
+ default=None, description="""The tools available to the agent."""
+ )
+
+
+class EvaluationRunAgentConfigDict(TypedDict, total=False):
+ """This field is experimental and may change in future versions.
+
+ Agent config for an evaluation run.
+ """
+
+ developer_instruction: Optional[genai_types.ContentDict]
+ """The developer instruction for the agent."""
+
+ tools: Optional[list[genai_types.ToolDict]]
+ """The tools available to the agent."""
+
+
+EvaluationRunAgentConfigOrDict = Union[
+ EvaluationRunAgentConfig, EvaluationRunAgentConfigDict
+]
+
+
+class AgentRunConfig(_common.BaseModel):
+ """Configuration for an Agent Run."""
+
+ session_input: Optional[evals_types.SessionInput] = Field(
+ default=None, description="""The session input to get agent running results."""
+ )
+ agent_engine: Optional[str] = Field(
+ default=None, description="""The resource name of the Agent Engine."""
+ )
+ user_simulator_config: Optional[evals_types.UserSimulatorConfig] = Field(
+ default=None,
+ description="""Used for multi-turn agent run.
+ Contains configuration for a user simulator that
+ uses an LLM to generate messages on behalf of the user.""",
+ )
+
+
+class AgentRunConfigDict(TypedDict, total=False):
+ """Configuration for an Agent Run."""
+
+ session_input: Optional[evals_types.SessionInput]
+ """The session input to get agent running results."""
+
+ agent_engine: Optional[str]
+ """The resource name of the Agent Engine."""
+
+ user_simulator_config: Optional[evals_types.UserSimulatorConfig]
+ """Used for multi-turn agent run.
+ Contains configuration for a user simulator that
+ uses an LLM to generate messages on behalf of the user."""
+
+
+AgentRunConfigOrDict = Union[AgentRunConfig, AgentRunConfigDict]
+
+
+class EvaluationRunInferenceConfig(_common.BaseModel):
+ """This field is experimental and may change in future versions.
+
+ Configuration that describes an agent.
+ """
+
+ agent_config: Optional[EvaluationRunAgentConfig] = Field(
+ default=None, description="""The agent config."""
+ )
+ model: Optional[str] = Field(
+ default=None,
+ description="""The fully qualified name of the publisher model or endpoint to use for inference.""",
+ )
+ prompt_template: Optional[EvaluationRunPromptTemplate] = Field(
+ default=None, description="""The prompt template used for inference."""
+ )
+ agent_run_config: Optional[AgentRunConfig] = Field(
+ default=None,
+ description="""Configuration for Agent Run in evaluation management service.""",
+ )
+ agent_configs: Optional[dict[str, evals_types.AgentConfig]] = Field(
+ default=None,
+ description="""A map of agent IDs to their respective agent config.""",
+ )
+
+
+class EvaluationRunInferenceConfigDict(TypedDict, total=False):
+ """This field is experimental and may change in future versions.
+
+ Configuration that describes an agent.
+ """
+
+ agent_config: Optional[EvaluationRunAgentConfigDict]
+ """The agent config."""
+
+ model: Optional[str]
+ """The fully qualified name of the publisher model or endpoint to use for inference."""
+
+ prompt_template: Optional[EvaluationRunPromptTemplateDict]
+ """The prompt template used for inference."""
+
+ agent_run_config: Optional[AgentRunConfigDict]
+ """Configuration for Agent Run in evaluation management service."""
+
+ agent_configs: Optional[dict[str, evals_types.AgentConfig]]
+ """A map of agent IDs to their respective agent config."""
+
+
+EvaluationRunInferenceConfigOrDict = Union[
+ EvaluationRunInferenceConfig, EvaluationRunInferenceConfigDict
+]
+
+
+class VulnerableTool(_common.BaseModel):
+ """A tool considered high risk for prompt injection."""
+
+ tool_name: Optional[str] = Field(
+ default=None,
+ description="""Optional. The name of the vulnerable function/tool (e.g., "search_flights").""",
+ )
+ json_paths: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. JSON Paths within the tool's FunctionResponse where malicious content could be injected.""",
+ )
+
+
+class VulnerableToolDict(TypedDict, total=False):
+ """A tool considered high risk for prompt injection."""
+
+ tool_name: Optional[str]
+ """Optional. The name of the vulnerable function/tool (e.g., "search_flights")."""
+
+ json_paths: Optional[list[str]]
+ """Optional. JSON Paths within the tool's FunctionResponse where malicious content could be injected."""
+
+
+VulnerableToolOrDict = Union[VulnerableTool, VulnerableToolDict]
+
+
+class RedTeamingAnalysisConfig(_common.BaseModel):
+ """Configuration for the automated Agent Red Teaming analysis."""
+
+ attack_categories: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. Specific attack categories to test against.""",
+ )
+ vulnerable_tools: Optional[list[VulnerableTool]] = Field(
+ default=None,
+ description="""Optional. Manually defined vulnerable tools and their injection paths.""",
+ )
+
+
+class RedTeamingAnalysisConfigDict(TypedDict, total=False):
+ """Configuration for the automated Agent Red Teaming analysis."""
+
+ attack_categories: Optional[list[str]]
+ """Optional. Specific attack categories to test against."""
+
+ vulnerable_tools: Optional[list[VulnerableToolDict]]
+ """Optional. Manually defined vulnerable tools and their injection paths."""
+
+
+RedTeamingAnalysisConfigOrDict = Union[
+ RedTeamingAnalysisConfig, RedTeamingAnalysisConfigDict
+]
+
+
+class AnalysisConfig(_common.BaseModel):
+ """Configuration for an analysis to be performed on an evaluation run."""
+
+ analysis_name: Optional[str] = Field(
+ default=None, description="""Optional. A name for this analysis."""
+ )
+ red_teaming_analysis_config: Optional[RedTeamingAnalysisConfig] = Field(
+ default=None,
+ description="""Configuration for the automated Agent Red Teaming analysis.""",
+ )
+
+
+class AnalysisConfigDict(TypedDict, total=False):
+ """Configuration for an analysis to be performed on an evaluation run."""
+
+ analysis_name: Optional[str]
+ """Optional. A name for this analysis."""
+
+ red_teaming_analysis_config: Optional[RedTeamingAnalysisConfigDict]
+ """Configuration for the automated Agent Red Teaming analysis."""
+
+
+AnalysisConfigOrDict = Union[AnalysisConfig, AnalysisConfigDict]
+
+
+class CreateEvaluationRunConfig(_common.BaseModel):
+ """Config to create an evaluation run."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ allow_cross_region_model: Optional[bool] = Field(
+ default=None,
+ description="""Allows the evaluation run to use cross region models. When this
+ flag is set, the service may route traffic to other regions if a model is
+ unavailable in the current region (e.g., to a `global`endpoint). If a
+ fully-qualified model endpoint resource name with a different region than
+ the run location is provided elsewhere in the run config, this flag must
+ be set to true or the request will fail.""",
+ )
+
+
+class CreateEvaluationRunConfigDict(TypedDict, total=False):
+ """Config to create an evaluation run."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ allow_cross_region_model: Optional[bool]
+ """Allows the evaluation run to use cross region models. When this
+ flag is set, the service may route traffic to other regions if a model is
+ unavailable in the current region (e.g., to a `global`endpoint). If a
+ fully-qualified model endpoint resource name with a different region than
+ the run location is provided elsewhere in the run config, this flag must
+ be set to true or the request will fail."""
+
+
+CreateEvaluationRunConfigOrDict = Union[
+ CreateEvaluationRunConfig, CreateEvaluationRunConfigDict
+]
+
+
+class _CreateEvaluationRunParameters(_common.BaseModel):
+ """Represents a job that creates an evaluation run."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ data_source: Optional[EvaluationRunDataSource] = Field(
+ default=None, description=""""""
+ )
+ evaluation_config: Optional[EvaluationRunConfig] = Field(
+ default=None, description=""""""
+ )
+ labels: Optional[dict[str, str]] = Field(default=None, description="""""")
+ inference_configs: Optional[dict[str, EvaluationRunInferenceConfig]] = Field(
+ default=None, description=""""""
+ )
+ config: Optional[CreateEvaluationRunConfig] = Field(
+ default=None, description=""""""
+ )
+ analysis_configs: Optional[list[AnalysisConfig]] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateEvaluationRunParametersDict(TypedDict, total=False):
+ """Represents a job that creates an evaluation run."""
+
+ name: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ data_source: Optional[EvaluationRunDataSourceDict]
+ """"""
+
+ evaluation_config: Optional[EvaluationRunConfigDict]
+ """"""
+
+ labels: Optional[dict[str, str]]
+ """"""
+
+ inference_configs: Optional[dict[str, EvaluationRunInferenceConfigDict]]
+ """"""
+
+ config: Optional[CreateEvaluationRunConfigDict]
+ """"""
+
+ analysis_configs: Optional[list[AnalysisConfigDict]]
+ """"""
+
+
+_CreateEvaluationRunParametersOrDict = Union[
+ _CreateEvaluationRunParameters, _CreateEvaluationRunParametersDict
+]
+
+
+class SummaryMetric(_common.BaseModel):
+ """Represents a summary metric for an evaluation run."""
+
+ metrics: Optional[dict[str, Any]] = Field(
+ default=None, description="""Map of metric name to metric value."""
+ )
+ total_items: Optional[int] = Field(
+ default=None, description="""The total number of items that were evaluated."""
+ )
+ failed_items: Optional[int] = Field(
+ default=None, description="""The number of items that failed to be evaluated."""
+ )
+
+
+class SummaryMetricDict(TypedDict, total=False):
+ """Represents a summary metric for an evaluation run."""
+
+ metrics: Optional[dict[str, Any]]
+ """Map of metric name to metric value."""
+
+ total_items: Optional[int]
+ """The total number of items that were evaluated."""
+
+ failed_items: Optional[int]
+ """The number of items that failed to be evaluated."""
+
+
+SummaryMetricOrDict = Union[SummaryMetric, SummaryMetricDict]
+
+
+class AttackCategoryResult(_common.BaseModel):
+ """The red teaming outcome for a specific attack category."""
+
+ attack_category: Optional[str] = Field(
+ default=None, description="""The category of the attack evaluated."""
+ )
+ attack_success_rate: Optional[float] = Field(
+ default=None,
+ description="""The ratio of successful attacks given a fixed budget.""",
+ )
+ vulnerability_insight: Optional[str] = Field(
+ default=None, description="""Insights into why an attack succeeded or failed."""
+ )
+
+
+class AttackCategoryResultDict(TypedDict, total=False):
+ """The red teaming outcome for a specific attack category."""
+
+ attack_category: Optional[str]
+ """The category of the attack evaluated."""
+
+ attack_success_rate: Optional[float]
+ """The ratio of successful attacks given a fixed budget."""
+
+ vulnerability_insight: Optional[str]
+ """Insights into why an attack succeeded or failed."""
+
+
+AttackCategoryResultOrDict = Union[AttackCategoryResult, AttackCategoryResultDict]
+
+
+class RedTeamingAnalysisResult(_common.BaseModel):
+ """The top-level result for Red Teaming analysis."""
+
+ config: Optional[RedTeamingAnalysisConfig] = Field(
+ default=None,
+ description="""The configuration used to generate this analysis.""",
+ )
+ analysis_time: Optional[str] = Field(
+ default=None, description="""The timestamp when this analysis was performed."""
+ )
+ category_results: Optional[list[AttackCategoryResult]] = Field(
+ default=None, description="""Detailed results by attack category."""
+ )
+
+
+class RedTeamingAnalysisResultDict(TypedDict, total=False):
+ """The top-level result for Red Teaming analysis."""
+
+ config: Optional[RedTeamingAnalysisConfigDict]
+ """The configuration used to generate this analysis."""
+
+ analysis_time: Optional[str]
+ """The timestamp when this analysis was performed."""
+
+ category_results: Optional[list[AttackCategoryResultDict]]
+ """Detailed results by attack category."""
+
+
+RedTeamingAnalysisResultOrDict = Union[
+ RedTeamingAnalysisResult, RedTeamingAnalysisResultDict
+]
+
+
+class LossTaxonomyEntry(_common.BaseModel):
+ """A specific entry in the loss pattern taxonomy."""
+
+ l1_category: Optional[str] = Field(
+ default=None,
+ description="""The primary category of the loss (e.g., "Hallucination", "Tool Calling").""",
+ )
+ l2_category: Optional[str] = Field(
+ default=None,
+ description="""The secondary category of the loss (e.g., "Hallucination of Action", "Incorrect Tool Selection").""",
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="""A detailed description of this loss pattern. Example: "The agent verbally confirms an action without executing the tool." """,
+ )
+
+
+class LossTaxonomyEntryDict(TypedDict, total=False):
+ """A specific entry in the loss pattern taxonomy."""
+
+ l1_category: Optional[str]
+ """The primary category of the loss (e.g., "Hallucination", "Tool Calling")."""
+
+ l2_category: Optional[str]
+ """The secondary category of the loss (e.g., "Hallucination of Action", "Incorrect Tool Selection")."""
+
+ description: Optional[str]
+ """A detailed description of this loss pattern. Example: "The agent verbally confirms an action without executing the tool." """
+
+
+LossTaxonomyEntryOrDict = Union[LossTaxonomyEntry, LossTaxonomyEntryDict]
+
+
+class FailedRubric(_common.BaseModel):
+ """A specific failed rubric and the associated analysis."""
+
+ rubric_id: Optional[str] = Field(
+ default=None,
+ description="""The unique ID of the rubric (if available from the metric source).""",
+ )
+ classification_rationale: Optional[str] = Field(
+ default=None,
+ description="""The rationale provided by the Loss Analysis Classifier for why this failure maps to this specific Loss Cluster.""",
+ )
+
+
+class FailedRubricDict(TypedDict, total=False):
+ """A specific failed rubric and the associated analysis."""
+
+ rubric_id: Optional[str]
+ """The unique ID of the rubric (if available from the metric source)."""
+
+ classification_rationale: Optional[str]
+ """The rationale provided by the Loss Analysis Classifier for why this failure maps to this specific Loss Cluster."""
+
+
+FailedRubricOrDict = Union[FailedRubric, FailedRubricDict]
+
+
+class LossExample(_common.BaseModel):
+ """A specific example of a loss pattern."""
+
+ evaluation_item: Optional[str] = Field(
+ default=None,
+ description="""Reference to the persisted EvalItem resource name. Format: projects/.../locations/.../evaluationItems/{item_id}.""",
+ )
+ evaluation_result: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The full evaluation result object provided inline. Used when the analysis is performed on ephemeral data.""",
+ )
+ failed_rubrics: Optional[list[FailedRubric]] = Field(
+ default=None,
+ description="""The specific rubric(s) that failed and caused this example to be classified here. An example might fail multiple rubrics, but only specific ones trigger this loss pattern.""",
+ )
+
+
+class LossExampleDict(TypedDict, total=False):
+ """A specific example of a loss pattern."""
+
+ evaluation_item: Optional[str]
+ """Reference to the persisted EvalItem resource name. Format: projects/.../locations/.../evaluationItems/{item_id}."""
+
+ evaluation_result: Optional[dict[str, Any]]
+ """The full evaluation result object provided inline. Used when the analysis is performed on ephemeral data."""
+
+ failed_rubrics: Optional[list[FailedRubricDict]]
+ """The specific rubric(s) that failed and caused this example to be classified here. An example might fail multiple rubrics, but only specific ones trigger this loss pattern."""
+
+
+LossExampleOrDict = Union[LossExample, LossExampleDict]
+
+
+class LossCluster(_common.BaseModel):
+ """A semantic grouping of failures (e.g., "Hallucination of Action")."""
+
+ cluster_id: Optional[str] = Field(
+ default=None,
+ description="""Unique identifier for the loss cluster within the scope of the analysis result.""",
+ )
+ taxonomy_entry: Optional[LossTaxonomyEntry] = Field(
+ default=None,
+ description="""The structured definition of the loss taxonomy for this cluster.""",
+ )
+ item_count: Optional[int] = Field(
+ default=None,
+ description="""The total number of EvaluationItems falling into this cluster.""",
+ )
+ examples: Optional[list[LossExample]] = Field(
+ default=None,
+ description="""A list of examples that belong to this cluster. This links the cluster back to the specific EvaluationItems and Rubrics.""",
+ )
+
+
+class LossClusterDict(TypedDict, total=False):
+ """A semantic grouping of failures (e.g., "Hallucination of Action")."""
+
+ cluster_id: Optional[str]
+ """Unique identifier for the loss cluster within the scope of the analysis result."""
+
+ taxonomy_entry: Optional[LossTaxonomyEntryDict]
+ """The structured definition of the loss taxonomy for this cluster."""
+
+ item_count: Optional[int]
+ """The total number of EvaluationItems falling into this cluster."""
+
+ examples: Optional[list[LossExampleDict]]
+ """A list of examples that belong to this cluster. This links the cluster back to the specific EvaluationItems and Rubrics."""
+
+
+LossClusterOrDict = Union[LossCluster, LossClusterDict]
+
+
+class LossAnalysisResult(_common.BaseModel):
+ """The top-level result for loss analysis."""
+
+ config: Optional[LossAnalysisConfig] = Field(
+ default=None,
+ description="""The configuration used to generate this analysis.""",
+ )
+ analysis_time: Optional[str] = Field(
+ default=None, description="""The timestamp when this analysis was performed."""
+ )
+ clusters: Optional[list[LossCluster]] = Field(
+ default=None, description="""The list of identified loss clusters."""
+ )
+
+ def show(self) -> None:
+ """Shows the loss analysis result with rich HTML visualization."""
+ from .. import _evals_visualization
+
+ _evals_visualization.display_loss_analysis_result(self)
+
+
+class LossAnalysisResultDict(TypedDict, total=False):
+ """The top-level result for loss analysis."""
+
+ config: Optional[LossAnalysisConfigDict]
+ """The configuration used to generate this analysis."""
+
+ analysis_time: Optional[str]
+ """The timestamp when this analysis was performed."""
+
+ clusters: Optional[list[LossClusterDict]]
+ """The list of identified loss clusters."""
+
+
+LossAnalysisResultOrDict = Union[LossAnalysisResult, LossAnalysisResultDict]
+
+
+class EvaluationRunResults(_common.BaseModel):
+ """Represents the results of an evaluation run."""
+
+ evaluation_set: Optional[str] = Field(
+ default=None,
+ description="""The evaluation set where item level results are stored.""",
+ )
+ summary_metrics: Optional[SummaryMetric] = Field(
+ default=None, description="""The summary metrics for the evaluation run."""
+ )
+ loss_analysis_results: Optional[list[LossAnalysisResult]] = Field(
+ default=None,
+ description="""The loss analysis results for the evaluation run.""",
+ )
+ red_teaming_analysis_results: Optional[list[RedTeamingAnalysisResult]] = Field(
+ default=None, description="""The Red Teaming analysis results."""
+ )
+
+
+class EvaluationRunResultsDict(TypedDict, total=False):
+ """Represents the results of an evaluation run."""
+
+ evaluation_set: Optional[str]
+ """The evaluation set where item level results are stored."""
+
+ summary_metrics: Optional[SummaryMetricDict]
+ """The summary metrics for the evaluation run."""
+
+ loss_analysis_results: Optional[list[LossAnalysisResultDict]]
+ """The loss analysis results for the evaluation run."""
+
+ red_teaming_analysis_results: Optional[list[RedTeamingAnalysisResultDict]]
+ """The Red Teaming analysis results."""
+
+
+EvaluationRunResultsOrDict = Union[EvaluationRunResults, EvaluationRunResultsDict]
+
+
+class EvalCaseMetricResult(_common.BaseModel):
+ """Evaluation result for a single evaluation case for a single metric."""
+
+ metric_name: Optional[str] = Field(
+ default=None, description="""Name of the metric."""
+ )
+ score: Optional[float] = Field(default=None, description="""Score of the metric.""")
+ explanation: Optional[str] = Field(
+ default=None, description="""Explanation of the metric."""
+ )
+ rubric_verdicts: Optional[list[evals_types.RubricVerdict]] = Field(
+ default=None,
+ description="""The details of all the rubrics and their verdicts for rubric-based metrics.""",
+ )
+ raw_output: Optional[list[str]] = Field(
+ default=None, description="""Raw output of the metric."""
+ )
+ error_message: Optional[str] = Field(
+ default=None, description="""Error message for the metric."""
+ )
+
+
+class EvalCaseMetricResultDict(TypedDict, total=False):
+ """Evaluation result for a single evaluation case for a single metric."""
+
+ metric_name: Optional[str]
+ """Name of the metric."""
+
+ score: Optional[float]
+ """Score of the metric."""
+
+ explanation: Optional[str]
+ """Explanation of the metric."""
+
+ rubric_verdicts: Optional[list[evals_types.RubricVerdict]]
+ """The details of all the rubrics and their verdicts for rubric-based metrics."""
+
+ raw_output: Optional[list[str]]
+ """Raw output of the metric."""
+
+ error_message: Optional[str]
+ """Error message for the metric."""
+
+
+EvalCaseMetricResultOrDict = Union[EvalCaseMetricResult, EvalCaseMetricResultDict]
+
+
+class ResponseCandidateResult(_common.BaseModel):
+ """Aggregated metric results for a single response candidate."""
+
+ response_index: Optional[int] = Field(
+ default=None,
+ description="""Index of the response candidate this result pertains to.""",
+ )
+ metric_results: Optional[dict[str, EvalCaseMetricResult]] = Field(
+ default=None,
+ description="""A dictionary of metric results for this response candidate, keyed by metric name.""",
+ )
+
+
+class ResponseCandidateResultDict(TypedDict, total=False):
+ """Aggregated metric results for a single response candidate."""
+
+ response_index: Optional[int]
+ """Index of the response candidate this result pertains to."""
+
+ metric_results: Optional[dict[str, EvalCaseMetricResultDict]]
+ """A dictionary of metric results for this response candidate, keyed by metric name."""
+
+
+ResponseCandidateResultOrDict = Union[
+ ResponseCandidateResult, ResponseCandidateResultDict
+]
+
+
+class EvalCaseResult(_common.BaseModel):
+ """Eval result for a single evaluation case."""
+
+ eval_case_index: Optional[int] = Field(
+ default=None, description="""Index of the evaluation case."""
+ )
+ response_candidate_results: Optional[list[ResponseCandidateResult]] = Field(
+ default=None,
+ description="""A list of results, one for each response candidate of the EvalCase.""",
+ )
+
+
+class EvalCaseResultDict(TypedDict, total=False):
+ """Eval result for a single evaluation case."""
+
+ eval_case_index: Optional[int]
+ """Index of the evaluation case."""
+
+ response_candidate_results: Optional[list[ResponseCandidateResultDict]]
+ """A list of results, one for each response candidate of the EvalCase."""
+
+
+EvalCaseResultOrDict = Union[EvalCaseResult, EvalCaseResultDict]
+
+
+class AggregatedMetricResult(_common.BaseModel):
+ """Evaluation result for a single metric for an evaluation dataset."""
+
+ metric_name: Optional[str] = Field(
+ default=None, description="""Name of the metric."""
+ )
+ num_cases_total: Optional[int] = Field(
+ default=None, description="""Total number of cases in the dataset."""
+ )
+ num_cases_valid: Optional[int] = Field(
+ default=None, description="""Number of valid cases in the dataset."""
+ )
+ num_cases_error: Optional[int] = Field(
+ default=None, description="""Number of cases with errors in the dataset."""
+ )
+ mean_score: Optional[float] = Field(
+ default=None, description="""Mean score of the metric."""
+ )
+ stdev_score: Optional[float] = Field(
+ default=None, description="""Standard deviation of the metric."""
+ )
+ pass_rate: Optional[float] = Field(
+ default=None,
+ description="""Pass rate of the adaptive rubric metric. Calculated as the number of cases where all criteria passed divided by the total number of valid cases. A case is passing if it has a score of 1.0.""",
+ )
+
+ # Allow extra fields to support custom aggregation stats.
+ model_config = ConfigDict(extra="allow")
+
+
+class AggregatedMetricResultDict(TypedDict, total=False):
+ """Evaluation result for a single metric for an evaluation dataset."""
+
+ metric_name: Optional[str]
+ """Name of the metric."""
+
+ num_cases_total: Optional[int]
+ """Total number of cases in the dataset."""
+
+ num_cases_valid: Optional[int]
+ """Number of valid cases in the dataset."""
+
+ num_cases_error: Optional[int]
+ """Number of cases with errors in the dataset."""
+
+ mean_score: Optional[float]
+ """Mean score of the metric."""
+
+ stdev_score: Optional[float]
+ """Standard deviation of the metric."""
+
+ pass_rate: Optional[float]
+ """Pass rate of the adaptive rubric metric. Calculated as the number of cases where all criteria passed divided by the total number of valid cases. A case is passing if it has a score of 1.0."""
+
+
+AggregatedMetricResultOrDict = Union[AggregatedMetricResult, AggregatedMetricResultDict]
+
+
+class WinRateStats(_common.BaseModel):
+ """Statistics for win rates for a single metric."""
+
+ win_rates: Optional[list[float]] = Field(
+ default=None,
+ description="""Win rates for the metric, one for each candidate.""",
+ )
+ tie_rate: Optional[float] = Field(
+ default=None, description="""Tie rate for the metric."""
+ )
+
+
+class WinRateStatsDict(TypedDict, total=False):
+ """Statistics for win rates for a single metric."""
+
+ win_rates: Optional[list[float]]
+ """Win rates for the metric, one for each candidate."""
+
+ tie_rate: Optional[float]
+ """Tie rate for the metric."""
+
+
+WinRateStatsOrDict = Union[WinRateStats, WinRateStatsDict]
+
+
+class ResponseCandidate(_common.BaseModel):
+ """A model-generated content to the prompt."""
+
+ response: Optional[genai_types.Content] = Field(
+ default=None,
+ description="""The final model-generated response to the `prompt`.""",
+ )
+
+
+class ResponseCandidateDict(TypedDict, total=False):
+ """A model-generated content to the prompt."""
+
+ response: Optional[genai_types.ContentDict]
+ """The final model-generated response to the `prompt`."""
+
+
+ResponseCandidateOrDict = Union[ResponseCandidate, ResponseCandidateDict]
+
+
+class EvalCase(_common.BaseModel):
+ """A comprehensive representation of a GenAI interaction for evaluation."""
+
+ prompt: Optional[genai_types.Content] = Field(
+ default=None, description="""The most recent user message (current input)."""
+ )
+ responses: Optional[list[ResponseCandidate]] = Field(
+ default=None,
+ description="""Model-generated replies to the last user message in a conversation. Multiple responses are allowed to support use cases such as comparing different model outputs.""",
+ )
+ reference: Optional[ResponseCandidate] = Field(
+ default=None,
+ description="""User-provided, golden reference model reply to prompt in context of chat history; Reference for last response in a conversation.""",
+ )
+ system_instruction: Optional[genai_types.Content] = Field(
+ default=None, description="""System instruction for the model."""
+ )
+ conversation_history: Optional[list[evals_types.Message]] = Field(
+ default=None,
+ description="""List of all prior messages in the conversation (chat history).""",
+ )
+ rubric_groups: Optional[dict[str, "RubricGroup"]] = Field(
+ default=None,
+ description="""Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group.""",
+ )
+ eval_case_id: Optional[str] = Field(
+ default=None, description="""Unique identifier for the evaluation case."""
+ )
+ intermediate_events: Optional[list[evals_types.Event]] = Field(
+ default=None,
+ description="""This field is experimental and may change in future versions. Intermediate events of a single turn in an agent run or intermediate events of the last turn for multi-turn an agent run.""",
+ )
+ agent_info: Optional[evals_types.AgentInfo] = Field(
+ default=None,
+ description="""This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation.""",
+ )
+ agent_data: Optional[evals_types.AgentData] = Field(
+ default=None,
+ description="""This field is experimental and may change in future versions. The agent data of the agent under evaluation.""",
+ )
+ user_scenario: Optional[evals_types.UserScenario] = Field(
+ default=None,
+ description="""This field is experimental and may change in future versions. The user scenario for the evaluation case.""",
+ )
+ # Allow extra fields to support custom metric prompts and stay backward compatible.
+ model_config = ConfigDict(frozen=True, extra="allow")
+
+
+class EvalCaseDict(TypedDict, total=False):
+ """A comprehensive representation of a GenAI interaction for evaluation."""
+
+ prompt: Optional[genai_types.ContentDict]
+ """The most recent user message (current input)."""
+
+ responses: Optional[list[ResponseCandidateDict]]
+ """Model-generated replies to the last user message in a conversation. Multiple responses are allowed to support use cases such as comparing different model outputs."""
+
+ reference: Optional[ResponseCandidateDict]
+ """User-provided, golden reference model reply to prompt in context of chat history; Reference for last response in a conversation."""
+
+ system_instruction: Optional[genai_types.ContentDict]
+ """System instruction for the model."""
+
+ conversation_history: Optional[list[evals_types.Message]]
+ """List of all prior messages in the conversation (chat history)."""
+
+ rubric_groups: Optional[dict[str, "RubricGroupDict"]]
+ """Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group."""
+
+ eval_case_id: Optional[str]
+ """Unique identifier for the evaluation case."""
+
+ intermediate_events: Optional[list[evals_types.Event]]
+ """This field is experimental and may change in future versions. Intermediate events of a single turn in an agent run or intermediate events of the last turn for multi-turn an agent run."""
+
+ agent_info: Optional[evals_types.AgentInfo]
+ """This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation."""
+
+ agent_data: Optional[evals_types.AgentData]
+ """This field is experimental and may change in future versions. The agent data of the agent under evaluation."""
+
+ user_scenario: Optional[evals_types.UserScenario]
+ """This field is experimental and may change in future versions. The user scenario for the evaluation case."""
+
+
+EvalCaseOrDict = Union[EvalCase, EvalCaseDict]
+
+
+class EvaluationDataset(_common.BaseModel):
+ """The dataset used for evaluation."""
+
+ bigquery_source: Optional[genai_types.BigQuerySource] = Field(
+ default=None, description="""The BigQuery source for the evaluation dataset."""
+ )
+ gcs_source: Optional[genai_types.GcsSource] = Field(
+ default=None, description="""The GCS source for the evaluation dataset."""
+ )
+ eval_cases: Optional[list[EvalCase]] = Field(
+ default=None, description="""The evaluation cases to be evaluated."""
+ )
+ eval_dataset_df: Optional[PandasDataFrame] = Field(
+ default=None,
+ description="""The evaluation dataset in the form of a Pandas DataFrame.""",
+ )
+ candidate_name: Optional[str] = Field(
+ default=None,
+ description="""The name of the candidate model or agent for this evaluation dataset.""",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def _check_pandas_installed(cls, data: Any) -> Any:
+ if isinstance(data, dict) and data.get("eval_dataset_df") is not None:
+ if pd is None:
+ logger.warning(
+ "Pandas is not installed, some evals features are not available."
+ " Please install it with `pip install"
+ " google-cloud-aiplatform[evaluation]`."
+ )
+ return data
+
+ @classmethod
+ def load_from_observability_eval_cases(
+ cls, cases: list["ObservabilityEvalCase"]
+ ) -> "EvaluationDataset":
+ """Fetches GenAI Observability data from GCS and parses into a DataFrame."""
+ try:
+ import pandas as pd
+ from .. import _gcs_utils
+
+ formats = []
+ requests = []
+ responses = []
+ system_instructions = []
+
+ for case in cases:
+ gcs_utils = _gcs_utils.GcsUtils(
+ case.api_client._api_client if case.api_client else None
+ )
+
+ # Associate "observability" data format for given sources
+ formats.append("observability")
+
+ # Input source
+ request_data = gcs_utils.read_file_contents(case.input_src)
+ requests.append(request_data)
+
+ # Output source
+ response_data = gcs_utils.read_file_contents(case.output_src)
+ responses.append(response_data)
+
+ # System instruction source
+ system_instruction_data = ""
+ if case.system_instruction_src is not None:
+ system_instruction_data = gcs_utils.read_file_contents(
+ case.system_instruction_src
+ )
+ system_instructions.append(system_instruction_data)
+
+ eval_dataset_df = pd.DataFrame(
+ {
+ "format": formats,
+ "request": requests,
+ "response": responses,
+ "system_instruction": system_instructions,
+ }
+ )
+
+ except ImportError as e:
+ raise ImportError("Pandas DataFrame library is required.") from e
+
+ return EvaluationDataset(eval_dataset_df=eval_dataset_df)
+
+ def show(self) -> None:
+ """Shows the evaluation dataset."""
+ from .. import _evals_visualization
+
+ _evals_visualization.display_evaluation_dataset(self)
+
+
+class EvaluationDatasetDict(TypedDict, total=False):
+ """The dataset used for evaluation."""
+
+ bigquery_source: Optional[genai_types.BigQuerySourceDict]
+ """The BigQuery source for the evaluation dataset."""
+
+ gcs_source: Optional[genai_types.GcsSourceDict]
+ """The GCS source for the evaluation dataset."""
+
+ eval_cases: Optional[list[EvalCaseDict]]
+ """The evaluation cases to be evaluated."""
+
+ eval_dataset_df: Optional[PandasDataFrame]
+ """The evaluation dataset in the form of a Pandas DataFrame."""
+
+ candidate_name: Optional[str]
+ """The name of the candidate model or agent for this evaluation dataset."""
+
+
+EvaluationDatasetOrDict = Union[EvaluationDataset, EvaluationDatasetDict]
+
+
+class EvaluationRunMetadata(_common.BaseModel):
+ """Metadata for an evaluation run."""
+
+ candidate_names: Optional[list[str]] = Field(
+ default=None,
+ description="""Name of the candidate(s) being evaluated in the evaluation run.""",
+ )
+ dataset_name: Optional[str] = Field(
+ default=None,
+ description="""Name of the evaluation dataset used for the evaluation run.""",
+ )
+ dataset_id: Optional[str] = Field(
+ default=None,
+ description="""Unique identifier for the evaluation dataset used for the evaluation run.""",
+ )
+ creation_timestamp: Optional[datetime.datetime] = Field(
+ default=None, description="""Creation timestamp of the evaluation run."""
+ )
+
+
+class EvaluationRunMetadataDict(TypedDict, total=False):
+ """Metadata for an evaluation run."""
+
+ candidate_names: Optional[list[str]]
+ """Name of the candidate(s) being evaluated in the evaluation run."""
+
+ dataset_name: Optional[str]
+ """Name of the evaluation dataset used for the evaluation run."""
+
+ dataset_id: Optional[str]
+ """Unique identifier for the evaluation dataset used for the evaluation run."""
+
+ creation_timestamp: Optional[datetime.datetime]
+ """Creation timestamp of the evaluation run."""
+
+
+EvaluationRunMetadataOrDict = Union[EvaluationRunMetadata, EvaluationRunMetadataDict]
+
+
+class EvaluationResult(_common.BaseModel):
+ """Result of an evaluation run for an evaluation dataset."""
+
+ eval_case_results: Optional[list[EvalCaseResult]] = Field(
+ default=None,
+ description="""A list of evaluation results for each evaluation case.""",
+ )
+ summary_metrics: Optional[list[AggregatedMetricResult]] = Field(
+ default=None,
+ description="""A list of summary-level evaluation results for each metric.""",
+ )
+ win_rates: Optional[dict[str, WinRateStats]] = Field(
+ default=None,
+ description="""A dictionary of win rates for each metric, only populated for multi-response evaluation runs.""",
+ )
+ evaluation_dataset: Optional[list[EvaluationDataset]] = Field(
+ default=None,
+ description="""The input evaluation dataset(s) for the evaluation run.""",
+ )
+ metadata: Optional[EvaluationRunMetadata] = Field(
+ default=None, description="""Metadata for the evaluation run."""
+ )
+ agent_info: Optional[evals_types.AgentInfo] = Field(
+ default=None,
+ description="""This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation.""",
+ )
+
+ def show(self, candidate_names: Optional[List[str]] = None) -> None:
+ """Shows the evaluation result.
+
+ Args:
+ candidate_names: list of names for the evaluated candidates, used in
+ comparison reports.
+ """
+ from .. import _evals_visualization
+
+ _evals_visualization.display_evaluation_result(self, candidate_names)
+
+
+class EvaluationResultDict(TypedDict, total=False):
+ """Result of an evaluation run for an evaluation dataset."""
+
+ eval_case_results: Optional[list[EvalCaseResultDict]]
+ """A list of evaluation results for each evaluation case."""
+
+ summary_metrics: Optional[list[AggregatedMetricResultDict]]
+ """A list of summary-level evaluation results for each metric."""
+
+ win_rates: Optional[dict[str, WinRateStatsDict]]
+ """A dictionary of win rates for each metric, only populated for multi-response evaluation runs."""
+
+ evaluation_dataset: Optional[list[EvaluationDatasetDict]]
+ """The input evaluation dataset(s) for the evaluation run."""
+
+ metadata: Optional[EvaluationRunMetadataDict]
+ """Metadata for the evaluation run."""
+
+ agent_info: Optional[evals_types.AgentInfo]
+ """This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation."""
+
+
+EvaluationResultOrDict = Union[EvaluationResult, EvaluationResultDict]
+
+
+class EvaluationRun(_common.BaseModel):
+ """Represents an evaluation run."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ metadata: Optional[dict[str, Any]] = Field(default=None, description="""""")
+ create_time: Optional[datetime.datetime] = Field(default=None, description="""""")
+ completion_time: Optional[datetime.datetime] = Field(
+ default=None, description=""""""
+ )
+ state: Optional[EvaluationRunState] = Field(default=None, description="""""")
+ evaluation_set_snapshot: Optional[str] = Field(default=None, description="""""")
+ error: Optional[genai_types.GoogleRpcStatus] = Field(
+ default=None, description=""""""
+ )
+ data_source: Optional[EvaluationRunDataSource] = Field(
+ default=None, description=""""""
+ )
+ evaluation_run_results: Optional[EvaluationRunResults] = Field(
+ default=None, description="""The evaluation run formatted results."""
+ )
+ evaluation_item_results: Optional[EvaluationResult] = Field(
+ default=None,
+ description="""The parsed EvaluationItem results for the evaluation run. This is only populated when include_evaluation_items is set to True.""",
+ )
+ evaluation_config: Optional[EvaluationRunConfig] = Field(
+ default=None, description="""The evaluation config for the evaluation run."""
+ )
+ inference_configs: Optional[dict[str, EvaluationRunInferenceConfig]] = Field(
+ default=None,
+ description="""This field is experimental and may change in future versions. The inference configs for the evaluation run.""",
+ )
+ labels: Optional[dict[str, str]] = Field(default=None, description="""""")
+ analysis_configs: Optional[list[AnalysisConfig]] = Field(
+ default=None,
+ description="""The analysis configurations for the evaluation run.""",
+ )
+
+ # TODO(b/448806531): Remove all the overridden _from_response methods once the
+ # ticket is resolved and published.
+ @classmethod
+ def _from_response(
+ cls: typing.Type["EvaluationRun"],
+ *,
+ response: dict[str, object],
+ kwargs: dict[str, object],
+ ) -> "EvaluationRun":
+ """Converts a dictionary response into a EvaluationRun object."""
+
+ snaked_response = _camel_key_to_snake(response)
+
+ evaluation_run_results = response.get("evaluation_run_results")
+
+ if (
+ isinstance(evaluation_run_results, dict)
+ and "summaryMetrics" in evaluation_run_results
+ ):
+ snaked_response["evaluation_run_results"]["summary_metrics"] = (
+ evaluation_run_results["summaryMetrics"]
+ )
+ result = super()._from_response(response=snaked_response, kwargs=kwargs)
+ return result
+
+ def show(self) -> None:
+ """Shows the evaluation result."""
+ from .. import _evals_visualization
+
+ if self.state == "SUCCEEDED":
+ if self.evaluation_item_results is not None:
+ _evals_visualization.display_evaluation_result(
+ self.evaluation_item_results, None
+ )
+ else:
+ logger.warning(
+ "Evaluation Run succeeded but no evaluation item results found. To display results, please set include_evaluation_items to True when calling get_evaluation_run()."
+ )
+ # Show loss analysis results if present on the evaluation run.
+ # Pass the eval item map so the visualization can enrich
+ # loss examples with scenario/rubric data.
+ if (
+ self.evaluation_run_results
+ and self.evaluation_run_results.loss_analysis_results
+ ):
+ eval_item_map = getattr(self, "_eval_item_map", None)
+ _evals_visualization.display_loss_analysis_results(
+ self.evaluation_run_results.loss_analysis_results,
+ eval_item_map=eval_item_map,
+ )
+ else:
+ _evals_visualization.display_evaluation_run_status(self)
+
+
+class EvaluationRunDict(TypedDict, total=False):
+ """Represents an evaluation run."""
+
+ name: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ metadata: Optional[dict[str, Any]]
+ """"""
+
+ create_time: Optional[datetime.datetime]
+ """"""
+
+ completion_time: Optional[datetime.datetime]
+ """"""
+
+ state: Optional[EvaluationRunState]
+ """"""
+
+ evaluation_set_snapshot: Optional[str]
+ """"""
+
+ error: Optional[genai_types.GoogleRpcStatusDict]
+ """"""
+
+ data_source: Optional[EvaluationRunDataSourceDict]
+ """"""
+
+ evaluation_run_results: Optional[EvaluationRunResultsDict]
+ """The evaluation run formatted results."""
+
+ evaluation_item_results: Optional[EvaluationResultDict]
+ """The parsed EvaluationItem results for the evaluation run. This is only populated when include_evaluation_items is set to True."""
+
+ evaluation_config: Optional[EvaluationRunConfigDict]
+ """The evaluation config for the evaluation run."""
+
+ inference_configs: Optional[dict[str, EvaluationRunInferenceConfigDict]]
+ """This field is experimental and may change in future versions. The inference configs for the evaluation run."""
+
+ labels: Optional[dict[str, str]]
+ """"""
+
+ analysis_configs: Optional[list[AnalysisConfigDict]]
+ """The analysis configurations for the evaluation run."""
+
+
+EvaluationRunOrDict = Union[EvaluationRun, EvaluationRunDict]
+
+
+class CreateEvaluationSetConfig(_common.BaseModel):
+ """Config to create an evaluation set."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class CreateEvaluationSetConfigDict(TypedDict, total=False):
+ """Config to create an evaluation set."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+CreateEvaluationSetConfigOrDict = Union[
+ CreateEvaluationSetConfig, CreateEvaluationSetConfigDict
+]
+
+
+class _CreateEvaluationSetParameters(_common.BaseModel):
+ """Represents a job that creates an evaluation set."""
+
+ evaluation_items: Optional[list[str]] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[CreateEvaluationSetConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateEvaluationSetParametersDict(TypedDict, total=False):
+ """Represents a job that creates an evaluation set."""
+
+ evaluation_items: Optional[list[str]]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ config: Optional[CreateEvaluationSetConfigDict]
+ """"""
+
+
+_CreateEvaluationSetParametersOrDict = Union[
+ _CreateEvaluationSetParameters, _CreateEvaluationSetParametersDict
+]
+
+
+class EvaluationSet(_common.BaseModel):
+ """Represents an evaluation set."""
+
+ name: Optional[str] = Field(
+ default=None, description="""The resource name of the evaluation set."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the evaluation set."""
+ )
+ evaluation_items: Optional[list[str]] = Field(
+ default=None,
+ description="""The EvaluationItems that are part of this dataset.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None, description="""The create time of the evaluation set."""
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None, description="""The update time of the evaluation set."""
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None, description="""The metadata of the evaluation set."""
+ )
+
+
+class EvaluationSetDict(TypedDict, total=False):
+ """Represents an evaluation set."""
+
+ name: Optional[str]
+ """The resource name of the evaluation set."""
+
+ display_name: Optional[str]
+ """The display name of the evaluation set."""
+
+ evaluation_items: Optional[list[str]]
+ """The EvaluationItems that are part of this dataset."""
+
+ create_time: Optional[datetime.datetime]
+ """The create time of the evaluation set."""
+
+ update_time: Optional[datetime.datetime]
+ """The update time of the evaluation set."""
+
+ metadata: Optional[dict[str, Any]]
+ """The metadata of the evaluation set."""
+
+
+EvaluationSetOrDict = Union[EvaluationSet, EvaluationSetDict]
+
+
+class DeleteEvaluationMetricConfig(_common.BaseModel):
+ """Config for deleting an evaluation metric."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteEvaluationMetricConfigDict(TypedDict, total=False):
+ """Config for deleting an evaluation metric."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteEvaluationMetricConfigOrDict = Union[
+ DeleteEvaluationMetricConfig, DeleteEvaluationMetricConfigDict
+]
+
+
+class _DeleteEvaluationMetricParameters(_common.BaseModel):
+ """Parameters for deleting an evaluation metric."""
+
+ metric_resource_name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[DeleteEvaluationMetricConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteEvaluationMetricParametersDict(TypedDict, total=False):
+ """Parameters for deleting an evaluation metric."""
+
+ metric_resource_name: Optional[str]
+ """"""
+
+ config: Optional[DeleteEvaluationMetricConfigDict]
+ """"""
+
+
+_DeleteEvaluationMetricParametersOrDict = Union[
+ _DeleteEvaluationMetricParameters, _DeleteEvaluationMetricParametersDict
+]
+
+
+class DeleteEvaluationMetricOperation(_common.BaseModel):
+ """Operation for deleting an evaluation metric."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteEvaluationMetricOperationDict(TypedDict, total=False):
+ """Operation for deleting an evaluation metric."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteEvaluationMetricOperationOrDict = Union[
+ DeleteEvaluationMetricOperation, DeleteEvaluationMetricOperationDict
+]
+
+
+class BleuInstance(_common.BaseModel):
+ """Bleu instance."""
+
+ prediction: Optional[str] = Field(
+ default=None, description="""Required. Output of the evaluated model."""
+ )
+ reference: Optional[str] = Field(
+ default=None,
+ description="""Required. Ground truth used to compare against the prediction.""",
+ )
+
+
+class BleuInstanceDict(TypedDict, total=False):
+ """Bleu instance."""
+
+ prediction: Optional[str]
+ """Required. Output of the evaluated model."""
+
+ reference: Optional[str]
+ """Required. Ground truth used to compare against the prediction."""
+
+
+BleuInstanceOrDict = Union[BleuInstance, BleuInstanceDict]
+
+
+class BleuInput(_common.BaseModel):
+
+ instances: Optional[list[BleuInstance]] = Field(
+ default=None, description="""Required. Repeated bleu instances."""
+ )
+ metric_spec: Optional[genai_types.BleuSpec] = Field(
+ default=None, description="""Required. Spec for bleu score metric."""
+ )
+
+
+class BleuInputDict(TypedDict, total=False):
+
+ instances: Optional[list[BleuInstanceDict]]
+ """Required. Repeated bleu instances."""
+
+ metric_spec: Optional[genai_types.BleuSpecDict]
+ """Required. Spec for bleu score metric."""
+
+
+BleuInputOrDict = Union[BleuInput, BleuInputDict]
+
+
+class ExactMatchInstance(_common.BaseModel):
+ """Exact match instance."""
+
+ prediction: Optional[str] = Field(
+ default=None, description="""Required. Output of the evaluated model."""
+ )
+ reference: Optional[str] = Field(
+ default=None,
+ description="""Required. Ground truth used to compare against the prediction.""",
+ )
+
+
+class ExactMatchInstanceDict(TypedDict, total=False):
+ """Exact match instance."""
+
+ prediction: Optional[str]
+ """Required. Output of the evaluated model."""
+
+ reference: Optional[str]
+ """Required. Ground truth used to compare against the prediction."""
+
+
+ExactMatchInstanceOrDict = Union[ExactMatchInstance, ExactMatchInstanceDict]
+
+
+class ExactMatchSpec(_common.BaseModel):
+ """Spec for exact match metric."""
+
+ pass
+
+
+class ExactMatchSpecDict(TypedDict, total=False):
+ """Spec for exact match metric."""
+
+ pass
+
+
+ExactMatchSpecOrDict = Union[ExactMatchSpec, ExactMatchSpecDict]
+
+
+class ExactMatchInput(_common.BaseModel):
+
+ instances: Optional[list[ExactMatchInstance]] = Field(
+ default=None, description="""Required. Repeated exact match instances."""
+ )
+ metric_spec: Optional[ExactMatchSpec] = Field(
+ default=None, description="""Required. Spec for exact match metric."""
+ )
+
+
+class ExactMatchInputDict(TypedDict, total=False):
+
+ instances: Optional[list[ExactMatchInstanceDict]]
+ """Required. Repeated exact match instances."""
+
+ metric_spec: Optional[ExactMatchSpecDict]
+ """Required. Spec for exact match metric."""
+
+
+ExactMatchInputOrDict = Union[ExactMatchInput, ExactMatchInputDict]
+
+
+class RougeInstance(_common.BaseModel):
+ """Rouge instance."""
+
+ prediction: Optional[str] = Field(
+ default=None, description="""Required. Output of the evaluated model."""
+ )
+ reference: Optional[str] = Field(
+ default=None,
+ description="""Required. Ground truth used to compare against the prediction.""",
+ )
+
+
+class RougeInstanceDict(TypedDict, total=False):
+ """Rouge instance."""
+
+ prediction: Optional[str]
+ """Required. Output of the evaluated model."""
+
+ reference: Optional[str]
+ """Required. Ground truth used to compare against the prediction."""
+
+
+RougeInstanceOrDict = Union[RougeInstance, RougeInstanceDict]
+
+
+class RougeInput(_common.BaseModel):
+ """Rouge input."""
+
+ instances: Optional[list[RougeInstance]] = Field(
+ default=None, description="""Required. Repeated rouge instances."""
+ )
+ metric_spec: Optional[genai_types.RougeSpec] = Field(
+ default=None, description="""Required. Spec for rouge score metric."""
+ )
+
+
+class RougeInputDict(TypedDict, total=False):
+ """Rouge input."""
+
+ instances: Optional[list[RougeInstanceDict]]
+ """Required. Repeated rouge instances."""
+
+ metric_spec: Optional[genai_types.RougeSpecDict]
+ """Required. Spec for rouge score metric."""
+
+
+RougeInputOrDict = Union[RougeInput, RougeInputDict]
+
+
+class ContentMap(_common.BaseModel):
+ """Map of placeholder in metric prompt template to contents of model input."""
+
+ values: Optional[dict[str, "ContentMapContents"]] = Field(
+ default=None, description="""Map of placeholder to contents."""
+ )
+
+
+class ContentMapDict(TypedDict, total=False):
+ """Map of placeholder in metric prompt template to contents of model input."""
+
+ values: Optional[dict[str, "ContentMapContents"]]
+ """Map of placeholder to contents."""
+
+
+ContentMapOrDict = Union[ContentMap, ContentMapDict]
+
+
+class PointwiseMetricInstance(_common.BaseModel):
+ """Pointwise metric instance."""
+
+ json_instance: Optional[str] = Field(
+ default=None,
+ description="""Instance specified as a json string. String key-value pairs are expected in the json_instance to render PointwiseMetricSpec.instance_prompt_template.""",
+ )
+ content_map_instance: Optional[ContentMap] = Field(
+ default=None,
+ description="""Key-value contents for the mutlimodality input, including text, image, video, audio, and pdf, etc. The key is placeholder in metric prompt template, and the value is the multimodal content.""",
+ )
+
+
+class PointwiseMetricInstanceDict(TypedDict, total=False):
+ """Pointwise metric instance."""
+
+ json_instance: Optional[str]
+ """Instance specified as a json string. String key-value pairs are expected in the json_instance to render PointwiseMetricSpec.instance_prompt_template."""
+
+ content_map_instance: Optional[ContentMapDict]
+ """Key-value contents for the mutlimodality input, including text, image, video, audio, and pdf, etc. The key is placeholder in metric prompt template, and the value is the multimodal content."""
+
+
+PointwiseMetricInstanceOrDict = Union[
+ PointwiseMetricInstance, PointwiseMetricInstanceDict
+]
+
+
+class PointwiseMetricInput(_common.BaseModel):
+ """Pointwise metric input."""
+
+ instance: Optional[PointwiseMetricInstance] = Field(
+ default=None, description="""Required. Pointwise metric instance."""
+ )
+ metric_spec: Optional[genai_types.PointwiseMetricSpec] = Field(
+ default=None, description="""Required. Spec for pointwise metric."""
+ )
+
+
+class PointwiseMetricInputDict(TypedDict, total=False):
+ """Pointwise metric input."""
+
+ instance: Optional[PointwiseMetricInstanceDict]
+ """Required. Pointwise metric instance."""
+
+ metric_spec: Optional[genai_types.PointwiseMetricSpecDict]
+ """Required. Spec for pointwise metric."""
+
+
+PointwiseMetricInputOrDict = Union[PointwiseMetricInput, PointwiseMetricInputDict]
+
+
+class PairwiseMetricInstance(_common.BaseModel):
+ """Pairwise metric instance."""
+
+ json_instance: Optional[str] = Field(
+ default=None,
+ description="""Instance specified as a json string. String key-value pairs are expected in the json_instance to render PairwiseMetricSpec.instance_prompt_template.""",
+ )
+
+
+class PairwiseMetricInstanceDict(TypedDict, total=False):
+ """Pairwise metric instance."""
+
+ json_instance: Optional[str]
+ """Instance specified as a json string. String key-value pairs are expected in the json_instance to render PairwiseMetricSpec.instance_prompt_template."""
+
+
+PairwiseMetricInstanceOrDict = Union[PairwiseMetricInstance, PairwiseMetricInstanceDict]
+
+
+class PairwiseMetricInput(_common.BaseModel):
+ """Pairwise metric instance."""
+
+ instance: Optional[PairwiseMetricInstance] = Field(
+ default=None, description="""Required. Pairwise metric instance."""
+ )
+ metric_spec: Optional[genai_types.PairwiseMetricSpec] = Field(
+ default=None, description="""Required. Spec for pairwise metric."""
+ )
+
+
+class PairwiseMetricInputDict(TypedDict, total=False):
+ """Pairwise metric instance."""
+
+ instance: Optional[PairwiseMetricInstanceDict]
+ """Required. Pairwise metric instance."""
+
+ metric_spec: Optional[genai_types.PairwiseMetricSpecDict]
+ """Required. Spec for pairwise metric."""
+
+
+PairwiseMetricInputOrDict = Union[PairwiseMetricInput, PairwiseMetricInputDict]
+
+
+class ToolCallValidInstance(_common.BaseModel):
+ """Tool call valid instance."""
+
+ prediction: Optional[str] = Field(
+ default=None, description="""Required. Output of the evaluated model."""
+ )
+ reference: Optional[str] = Field(
+ default=None,
+ description="""Required. Ground truth used to compare against the prediction.""",
+ )
+
+
+class ToolCallValidInstanceDict(TypedDict, total=False):
+ """Tool call valid instance."""
+
+ prediction: Optional[str]
+ """Required. Output of the evaluated model."""
+
+ reference: Optional[str]
+ """Required. Ground truth used to compare against the prediction."""
+
+
+ToolCallValidInstanceOrDict = Union[ToolCallValidInstance, ToolCallValidInstanceDict]
+
+
+class ToolCallValidSpec(_common.BaseModel):
+ """Spec for tool call valid metric."""
+
+ pass
+
+
+class ToolCallValidSpecDict(TypedDict, total=False):
+ """Spec for tool call valid metric."""
+
+ pass
+
+
+ToolCallValidSpecOrDict = Union[ToolCallValidSpec, ToolCallValidSpecDict]
+
+
+class ToolCallValidInput(_common.BaseModel):
+ """Tool call valid input."""
+
+ instances: Optional[list[ToolCallValidInstance]] = Field(
+ default=None, description="""Required. Repeated tool call valid instances."""
+ )
+ metric_spec: Optional[ToolCallValidSpec] = Field(
+ default=None, description="""Required. Spec for tool call valid metric."""
+ )
+
+
+class ToolCallValidInputDict(TypedDict, total=False):
+ """Tool call valid input."""
+
+ instances: Optional[list[ToolCallValidInstanceDict]]
+ """Required. Repeated tool call valid instances."""
+
+ metric_spec: Optional[ToolCallValidSpecDict]
+ """Required. Spec for tool call valid metric."""
+
+
+ToolCallValidInputOrDict = Union[ToolCallValidInput, ToolCallValidInputDict]
+
+
+class ToolNameMatchInstance(_common.BaseModel):
+ """Tool name match instance."""
+
+ prediction: Optional[str] = Field(
+ default=None, description="""Required. Output of the evaluated model."""
+ )
+ reference: Optional[str] = Field(
+ default=None,
+ description="""Required. Ground truth used to compare against the prediction.""",
+ )
+
+
+class ToolNameMatchInstanceDict(TypedDict, total=False):
+ """Tool name match instance."""
+
+ prediction: Optional[str]
+ """Required. Output of the evaluated model."""
+
+ reference: Optional[str]
+ """Required. Ground truth used to compare against the prediction."""
+
+
+ToolNameMatchInstanceOrDict = Union[ToolNameMatchInstance, ToolNameMatchInstanceDict]
+
+
+class ToolNameMatchSpec(_common.BaseModel):
+ """Spec for tool name match metric."""
+
+ pass
+
+
+class ToolNameMatchSpecDict(TypedDict, total=False):
+ """Spec for tool name match metric."""
+
+ pass
+
+
+ToolNameMatchSpecOrDict = Union[ToolNameMatchSpec, ToolNameMatchSpecDict]
+
+
+class ToolNameMatchInput(_common.BaseModel):
+ """Tool name match input."""
+
+ instances: Optional[list[ToolNameMatchInstance]] = Field(
+ default=None, description="""Required. Repeated tool name match instances."""
+ )
+ metric_spec: Optional[ToolNameMatchSpec] = Field(
+ default=None, description="""Required. Spec for tool name match metric."""
+ )
+
+
+class ToolNameMatchInputDict(TypedDict, total=False):
+ """Tool name match input."""
+
+ instances: Optional[list[ToolNameMatchInstanceDict]]
+ """Required. Repeated tool name match instances."""
+
+ metric_spec: Optional[ToolNameMatchSpecDict]
+ """Required. Spec for tool name match metric."""
+
+
+ToolNameMatchInputOrDict = Union[ToolNameMatchInput, ToolNameMatchInputDict]
+
+
+class ToolParameterKeyMatchInstance(_common.BaseModel):
+ """Tool parameter key match instance."""
+
+ prediction: Optional[str] = Field(
+ default=None, description="""Required. Output of the evaluated model."""
+ )
+ reference: Optional[str] = Field(
+ default=None,
+ description="""Required. Ground truth used to compare against the prediction.""",
+ )
+
+
+class ToolParameterKeyMatchInstanceDict(TypedDict, total=False):
+ """Tool parameter key match instance."""
+
+ prediction: Optional[str]
+ """Required. Output of the evaluated model."""
+
+ reference: Optional[str]
+ """Required. Ground truth used to compare against the prediction."""
+
+
+ToolParameterKeyMatchInstanceOrDict = Union[
+ ToolParameterKeyMatchInstance, ToolParameterKeyMatchInstanceDict
+]
+
+
+class ToolParameterKeyMatchSpec(_common.BaseModel):
+ """Spec for tool parameter key match metric."""
+
+ pass
+
+
+class ToolParameterKeyMatchSpecDict(TypedDict, total=False):
+ """Spec for tool parameter key match metric."""
+
+ pass
+
+
+ToolParameterKeyMatchSpecOrDict = Union[
+ ToolParameterKeyMatchSpec, ToolParameterKeyMatchSpecDict
+]
+
+
+class ToolParameterKeyMatchInput(_common.BaseModel):
+ """Tool parameter key match input."""
+
+ instances: Optional[list[ToolParameterKeyMatchInstance]] = Field(
+ default=None,
+ description="""Required. Repeated tool parameter key match instances.""",
+ )
+ metric_spec: Optional[ToolParameterKeyMatchSpec] = Field(
+ default=None,
+ description="""Required. Spec for tool parameter key match metric.""",
+ )
+
+
+class ToolParameterKeyMatchInputDict(TypedDict, total=False):
+ """Tool parameter key match input."""
+
+ instances: Optional[list[ToolParameterKeyMatchInstanceDict]]
+ """Required. Repeated tool parameter key match instances."""
+
+ metric_spec: Optional[ToolParameterKeyMatchSpecDict]
+ """Required. Spec for tool parameter key match metric."""
+
+
+ToolParameterKeyMatchInputOrDict = Union[
+ ToolParameterKeyMatchInput, ToolParameterKeyMatchInputDict
+]
+
+
+class ToolParameterKVMatchInstance(_common.BaseModel):
+ """Tool parameter kv match instance."""
+
+ prediction: Optional[str] = Field(
+ default=None, description="""Required. Output of the evaluated model."""
+ )
+ reference: Optional[str] = Field(
+ default=None,
+ description="""Required. Ground truth used to compare against the prediction.""",
+ )
+
+
+class ToolParameterKVMatchInstanceDict(TypedDict, total=False):
+ """Tool parameter kv match instance."""
+
+ prediction: Optional[str]
+ """Required. Output of the evaluated model."""
+
+ reference: Optional[str]
+ """Required. Ground truth used to compare against the prediction."""
+
+
+ToolParameterKVMatchInstanceOrDict = Union[
+ ToolParameterKVMatchInstance, ToolParameterKVMatchInstanceDict
+]
+
+
+class ToolParameterKVMatchSpec(_common.BaseModel):
+ """Spec for tool parameter kv match metric."""
+
+ use_strict_string_match: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Whether to use STRICT string match on parameter values.""",
+ )
+
+
+class ToolParameterKVMatchSpecDict(TypedDict, total=False):
+ """Spec for tool parameter kv match metric."""
+
+ use_strict_string_match: Optional[bool]
+ """Optional. Whether to use STRICT string match on parameter values."""
+
+
+ToolParameterKVMatchSpecOrDict = Union[
+ ToolParameterKVMatchSpec, ToolParameterKVMatchSpecDict
+]
+
+
+class ToolParameterKVMatchInput(_common.BaseModel):
+ """Tool parameter kv match input."""
+
+ instances: Optional[list[ToolParameterKVMatchInstance]] = Field(
+ default=None,
+ description="""Required. Repeated tool parameter key value match instances.""",
+ )
+ metric_spec: Optional[ToolParameterKVMatchSpec] = Field(
+ default=None,
+ description="""Required. Spec for tool parameter key value match metric.""",
+ )
+
+
+class ToolParameterKVMatchInputDict(TypedDict, total=False):
+ """Tool parameter kv match input."""
+
+ instances: Optional[list[ToolParameterKVMatchInstanceDict]]
+ """Required. Repeated tool parameter key value match instances."""
+
+ metric_spec: Optional[ToolParameterKVMatchSpecDict]
+ """Required. Spec for tool parameter key value match metric."""
+
+
+ToolParameterKVMatchInputOrDict = Union[
+ ToolParameterKVMatchInput, ToolParameterKVMatchInputDict
+]
+
+
+class MapInstance(_common.BaseModel):
+ """Instance data specified as a map."""
+
+ map_instance: Optional[dict[str, evals_types.InstanceData]] = Field(
+ default=None, description="""Map of instance data."""
+ )
+
+
+class MapInstanceDict(TypedDict, total=False):
+ """Instance data specified as a map."""
+
+ map_instance: Optional[dict[str, evals_types.InstanceData]]
+ """Map of instance data."""
+
+
+MapInstanceOrDict = Union[MapInstance, MapInstanceDict]
+
+
+class EvaluationInstance(_common.BaseModel):
+ """A single instance to be evaluated."""
+
+ prompt: Optional[evals_types.InstanceData] = Field(
+ default=None,
+ description="""Data used to populate placeholder `prompt` in a metric prompt template.""",
+ )
+ response: Optional[evals_types.InstanceData] = Field(
+ default=None,
+ description="""Data used to populate placeholder `response` in a metric prompt template.""",
+ )
+ reference: Optional[evals_types.InstanceData] = Field(
+ default=None,
+ description="""Data used to populate placeholder `reference` in a metric prompt template.""",
+ )
+ other_data: Optional[MapInstance] = Field(
+ default=None,
+ description="""Other data used to populate placeholders based on their key.""",
+ )
+ agent_data: Optional[evals_types.AgentData] = Field(
+ default=None, description="""Data used for agent evaluation."""
+ )
+ rubric_groups: Optional[dict[str, "RubricGroup"]] = Field(
+ default=None,
+ description="""Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group.""",
+ )
+
+
+class EvaluationInstanceDict(TypedDict, total=False):
+ """A single instance to be evaluated."""
+
+ prompt: Optional[evals_types.InstanceData]
+ """Data used to populate placeholder `prompt` in a metric prompt template."""
+
+ response: Optional[evals_types.InstanceData]
+ """Data used to populate placeholder `response` in a metric prompt template."""
+
+ reference: Optional[evals_types.InstanceData]
+ """Data used to populate placeholder `reference` in a metric prompt template."""
+
+ other_data: Optional[MapInstanceDict]
+ """Other data used to populate placeholders based on their key."""
+
+ agent_data: Optional[evals_types.AgentData]
+ """Data used for agent evaluation."""
+
+ rubric_groups: Optional[dict[str, "RubricGroupDict"]]
+ """Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group."""
+
+
+EvaluationInstanceOrDict = Union[EvaluationInstance, EvaluationInstanceDict]
+
+
+class EvaluateInstancesConfig(_common.BaseModel):
+ """Config for evaluate instances."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class EvaluateInstancesConfigDict(TypedDict, total=False):
+ """Config for evaluate instances."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+EvaluateInstancesConfigOrDict = Union[
+ EvaluateInstancesConfig, EvaluateInstancesConfigDict
+]
+
+
+class RubricBasedMetricSpec(_common.BaseModel):
+ """Specification for a metric that is based on rubrics."""
+
+ metric_prompt_template: Optional[str] = Field(
+ default=None,
+ description="""Template for the prompt used by the judge model to evaluate against
+ rubrics.""",
+ )
+ judge_autorater_config: Optional[genai_types.AutoraterConfig] = Field(
+ default=None,
+ description="""Optional configuration for the judge LLM (Autorater).""",
+ )
+ inline_rubrics: Optional[list[evals_types.Rubric]] = Field(
+ default=None, description="""Use rubrics provided directly in the spec."""
+ )
+ rubric_group_key: Optional[str] = Field(
+ default=None,
+ description="""Use a pre-defined group of rubrics associated with the input content.
+ This refers to a key in the `rubric_groups` map of
+ `RubricEnhancedContents`.""",
+ )
+ rubric_generation_spec: Optional[genai_types.RubricGenerationSpec] = Field(
+ default=None,
+ description="""Dynamically generate rubrics for evaluation using this specification.""",
+ )
+
+
+class RubricBasedMetricSpecDict(TypedDict, total=False):
+ """Specification for a metric that is based on rubrics."""
+
+ metric_prompt_template: Optional[str]
+ """Template for the prompt used by the judge model to evaluate against
+ rubrics."""
+
+ judge_autorater_config: Optional[genai_types.AutoraterConfigDict]
+ """Optional configuration for the judge LLM (Autorater)."""
+
+ inline_rubrics: Optional[list[evals_types.Rubric]]
+ """Use rubrics provided directly in the spec."""
+
+ rubric_group_key: Optional[str]
+ """Use a pre-defined group of rubrics associated with the input content.
+ This refers to a key in the `rubric_groups` map of
+ `RubricEnhancedContents`."""
+
+ rubric_generation_spec: Optional[genai_types.RubricGenerationSpecDict]
+ """Dynamically generate rubrics for evaluation using this specification."""
+
+
+RubricBasedMetricSpecOrDict = Union[RubricBasedMetricSpec, RubricBasedMetricSpecDict]
+
+
+class RubricEnhancedContents(_common.BaseModel):
+ """Rubric-enhanced contents for evaluation."""
+
+ prompt: Optional[list[genai_types.Content]] = Field(
+ default=None,
+ description="""User prompt, using the standard Content type from the Gen AI SDK.""",
+ )
+ rubric_groups: Optional[dict[str, "RubricGroup"]] = Field(
+ default=None,
+ description="""Named groups of rubrics associated with this prompt.
+ The key is a user-defined name for the rubric group.""",
+ )
+ response: Optional[list[genai_types.Content]] = Field(
+ default=None,
+ description="""Response, using the standard Content type from the Gen AI SDK.""",
+ )
+ other_content: Optional[ContentMap] = Field(
+ default=None,
+ description="""Other contents needed for the metric.
+ For example, if `reference` is needed for the metric, it can be provided
+ here.""",
+ )
+
+
+class RubricEnhancedContentsDict(TypedDict, total=False):
+ """Rubric-enhanced contents for evaluation."""
+
+ prompt: Optional[list[genai_types.ContentDict]]
+ """User prompt, using the standard Content type from the Gen AI SDK."""
+
+ rubric_groups: Optional[dict[str, "RubricGroup"]]
+ """Named groups of rubrics associated with this prompt.
+ The key is a user-defined name for the rubric group."""
+
+ response: Optional[list[genai_types.ContentDict]]
+ """Response, using the standard Content type from the Gen AI SDK."""
+
+ other_content: Optional[ContentMapDict]
+ """Other contents needed for the metric.
+ For example, if `reference` is needed for the metric, it can be provided
+ here."""
+
+
+RubricEnhancedContentsOrDict = Union[RubricEnhancedContents, RubricEnhancedContentsDict]
+
+
+class RubricBasedMetricInstance(_common.BaseModel):
+ """Defines an instance for Rubric-based metrics.
+
+ This class allows various input formats.
+ """
+
+ json_instance: Optional[str] = Field(
+ default=None,
+ description="""Specify evaluation fields and their string values in JSON format.""",
+ )
+ content_map_instance: Optional[ContentMap] = Field(
+ default=None,
+ description="""Specify evaluation fields and their content values using a ContentMap.""",
+ )
+ rubric_enhanced_contents: Optional[RubricEnhancedContents] = Field(
+ default=None,
+ description="""Provide input as Gemini Content along with one or more
+ associated rubric groups.""",
+ )
+
+
+class RubricBasedMetricInstanceDict(TypedDict, total=False):
+ """Defines an instance for Rubric-based metrics.
+
+ This class allows various input formats.
+ """
+
+ json_instance: Optional[str]
+ """Specify evaluation fields and their string values in JSON format."""
+
+ content_map_instance: Optional[ContentMapDict]
+ """Specify evaluation fields and their content values using a ContentMap."""
+
+ rubric_enhanced_contents: Optional[RubricEnhancedContentsDict]
+ """Provide input as Gemini Content along with one or more
+ associated rubric groups."""
+
+
+RubricBasedMetricInstanceOrDict = Union[
+ RubricBasedMetricInstance, RubricBasedMetricInstanceDict
+]
+
+
+class RubricBasedMetricInput(_common.BaseModel):
+ """Input for a rubric-based metrics."""
+
+ metric_spec: Optional[RubricBasedMetricSpec] = Field(
+ default=None, description="""Specification for the rubric-based metric."""
+ )
+ instance: Optional[RubricBasedMetricInstance] = Field(
+ default=None, description="""The instance to be evaluated."""
+ )
+
+
+class RubricBasedMetricInputDict(TypedDict, total=False):
+ """Input for a rubric-based metrics."""
+
+ metric_spec: Optional[RubricBasedMetricSpecDict]
+ """Specification for the rubric-based metric."""
+
+ instance: Optional[RubricBasedMetricInstanceDict]
+ """The instance to be evaluated."""
+
+
+RubricBasedMetricInputOrDict = Union[RubricBasedMetricInput, RubricBasedMetricInputDict]
+
+
+class MetricSource(_common.BaseModel):
+ """The metric source used for evaluation."""
+
+ metric: Optional[Metric] = Field(
+ default=None, description="""Inline metric config."""
+ )
+ metric_resource_name: Optional[str] = Field(
+ default=None,
+ description="""Resource name for registered metric. Example:
+ projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric_id}""",
+ )
+
+
+class MetricSourceDict(TypedDict, total=False):
+ """The metric source used for evaluation."""
+
+ metric: Optional[MetricDict]
+ """Inline metric config."""
+
+ metric_resource_name: Optional[str]
+ """Resource name for registered metric. Example:
+ projects/{project}/locations/{location}/evaluationMetrics/{evaluation_metric_id}"""
+
+
+MetricSourceOrDict = Union[MetricSource, MetricSourceDict]
+
+
+class _EvaluateInstancesRequestParameters(_common.BaseModel):
+ """Parameters for evaluating instances."""
+
+ bleu_input: Optional[BleuInput] = Field(default=None, description="""""")
+ exact_match_input: Optional[ExactMatchInput] = Field(
+ default=None, description=""""""
+ )
+ rouge_input: Optional[RougeInput] = Field(default=None, description="""""")
+ pointwise_metric_input: Optional[PointwiseMetricInput] = Field(
+ default=None, description=""""""
+ )
+ pairwise_metric_input: Optional[PairwiseMetricInput] = Field(
+ default=None, description=""""""
+ )
+ tool_call_valid_input: Optional[ToolCallValidInput] = Field(
+ default=None, description=""""""
+ )
+ tool_name_match_input: Optional[ToolNameMatchInput] = Field(
+ default=None, description=""""""
+ )
+ tool_parameter_key_match_input: Optional[ToolParameterKeyMatchInput] = Field(
+ default=None, description=""""""
+ )
+ tool_parameter_kv_match_input: Optional[ToolParameterKVMatchInput] = Field(
+ default=None, description=""""""
+ )
+ rubric_based_metric_input: Optional[RubricBasedMetricInput] = Field(
+ default=None, description=""""""
+ )
+ autorater_config: Optional[genai_types.AutoraterConfig] = Field(
+ default=None, description=""""""
+ )
+ metrics: Optional[list[Metric]] = Field(
+ default=None,
+ description="""The metrics used for evaluation.
+ Currently, we only support evaluating a single metric. If multiple metrics
+ are provided, only the first one will be evaluated.""",
+ )
+ instance: Optional[EvaluationInstance] = Field(
+ default=None, description="""The instance to be evaluated."""
+ )
+ metric_sources: Optional[list[MetricSource]] = Field(
+ default=None, description="""The metrics used for evaluation."""
+ )
+ config: Optional[EvaluateInstancesConfig] = Field(default=None, description="""""")
+
+
+class _EvaluateInstancesRequestParametersDict(TypedDict, total=False):
+ """Parameters for evaluating instances."""
+
+ bleu_input: Optional[BleuInputDict]
+ """"""
+
+ exact_match_input: Optional[ExactMatchInputDict]
+ """"""
+
+ rouge_input: Optional[RougeInputDict]
+ """"""
+
+ pointwise_metric_input: Optional[PointwiseMetricInputDict]
+ """"""
+
+ pairwise_metric_input: Optional[PairwiseMetricInputDict]
+ """"""
+
+ tool_call_valid_input: Optional[ToolCallValidInputDict]
+ """"""
+
+ tool_name_match_input: Optional[ToolNameMatchInputDict]
+ """"""
+
+ tool_parameter_key_match_input: Optional[ToolParameterKeyMatchInputDict]
+ """"""
+
+ tool_parameter_kv_match_input: Optional[ToolParameterKVMatchInputDict]
+ """"""
+
+ rubric_based_metric_input: Optional[RubricBasedMetricInputDict]
+ """"""
+
+ autorater_config: Optional[genai_types.AutoraterConfigDict]
+ """"""
+
+ metrics: Optional[list[MetricDict]]
+ """The metrics used for evaluation.
+ Currently, we only support evaluating a single metric. If multiple metrics
+ are provided, only the first one will be evaluated."""
+
+ instance: Optional[EvaluationInstanceDict]
+ """The instance to be evaluated."""
+
+ metric_sources: Optional[list[MetricSourceDict]]
+ """The metrics used for evaluation."""
+
+ config: Optional[EvaluateInstancesConfigDict]
+ """"""
+
+
+_EvaluateInstancesRequestParametersOrDict = Union[
+ _EvaluateInstancesRequestParameters, _EvaluateInstancesRequestParametersDict
+]
+
+
+class MetricResult(_common.BaseModel):
+ """Result for a single metric on a single instance."""
+
+ score: Optional[float] = Field(
+ default=None,
+ description="""The score for the metric. Please refer to each metric's documentation for the meaning of the score.""",
+ )
+ rubric_verdicts: Optional[list[evals_types.RubricVerdict]] = Field(
+ default=None,
+ description="""For rubric-based metrics, the verdicts for each rubric.""",
+ )
+ explanation: Optional[str] = Field(
+ default=None, description="""The explanation for the metric result."""
+ )
+ error: Optional[genai_types.GoogleRpcStatus] = Field(
+ default=None, description="""The error status for the metric result."""
+ )
+
+
+class MetricResultDict(TypedDict, total=False):
+ """Result for a single metric on a single instance."""
+
+ score: Optional[float]
+ """The score for the metric. Please refer to each metric's documentation for the meaning of the score."""
+
+ rubric_verdicts: Optional[list[evals_types.RubricVerdict]]
+ """For rubric-based metrics, the verdicts for each rubric."""
+
+ explanation: Optional[str]
+ """The explanation for the metric result."""
+
+ error: Optional[genai_types.GoogleRpcStatusDict]
+ """The error status for the metric result."""
+
+
+MetricResultOrDict = Union[MetricResult, MetricResultDict]
+
+
+class BleuResults(_common.BaseModel):
+ """Result of evaluating a bleu metric."""
+
+ bleu_metric_values: Optional[list[genai_types.BleuMetricValue]] = Field(
+ default=None, description="""Output only. Bleu metric values."""
+ )
+
+
+class BleuResultsDict(TypedDict, total=False):
+ """Result of evaluating a bleu metric."""
+
+ bleu_metric_values: Optional[list[genai_types.BleuMetricValueDict]]
+ """Output only. Bleu metric values."""
+
+
+BleuResultsOrDict = Union[BleuResults, BleuResultsDict]
+
+
+class ExactMatchResults(_common.BaseModel):
+ """Result of evaluating an exact match metric."""
+
+ exact_match_metric_values: Optional[list[genai_types.ExactMatchMetricValue]] = (
+ Field(default=None, description="""Output only. Exact match metric values.""")
+ )
+
+
+class ExactMatchResultsDict(TypedDict, total=False):
+ """Result of evaluating an exact match metric."""
+
+ exact_match_metric_values: Optional[list[genai_types.ExactMatchMetricValueDict]]
+ """Output only. Exact match metric values."""
+
+
+ExactMatchResultsOrDict = Union[ExactMatchResults, ExactMatchResultsDict]
+
+
+class RougeResults(_common.BaseModel):
+ """Result of evaluating a rouge metric."""
+
+ rouge_metric_values: Optional[list[genai_types.RougeMetricValue]] = Field(
+ default=None, description="""Output only. Rouge metric values."""
+ )
+
+
+class RougeResultsDict(TypedDict, total=False):
+ """Result of evaluating a rouge metric."""
+
+ rouge_metric_values: Optional[list[genai_types.RougeMetricValueDict]]
+ """Output only. Rouge metric values."""
+
+
+RougeResultsOrDict = Union[RougeResults, RougeResultsDict]
+
+
+class RubricBasedMetricResult(_common.BaseModel):
+ """Result for a rubric-based metric."""
+
+ score: Optional[float] = Field(
+ default=None, description="""Passing rate of all the rubrics."""
+ )
+ rubric_verdicts: Optional[list[evals_types.RubricVerdict]] = Field(
+ default=None,
+ description="""The details of all the rubrics and their verdicts.""",
+ )
+
+
+class RubricBasedMetricResultDict(TypedDict, total=False):
+ """Result for a rubric-based metric."""
+
+ score: Optional[float]
+ """Passing rate of all the rubrics."""
+
+ rubric_verdicts: Optional[list[evals_types.RubricVerdict]]
+ """The details of all the rubrics and their verdicts."""
+
+
+RubricBasedMetricResultOrDict = Union[
+ RubricBasedMetricResult, RubricBasedMetricResultDict
+]
+
+
+class CometResult(_common.BaseModel):
+ """Spec for Comet result - calculates the comet score for the given instance using the version specified in the spec."""
+
+ score: Optional[float] = Field(
+ default=None,
+ description="""Output only. Comet score. Range depends on version.""",
+ )
+
+
+class CometResultDict(TypedDict, total=False):
+ """Spec for Comet result - calculates the comet score for the given instance using the version specified in the spec."""
+
+ score: Optional[float]
+ """Output only. Comet score. Range depends on version."""
+
+
+CometResultOrDict = Union[CometResult, CometResultDict]
+
+
+class MetricxResult(_common.BaseModel):
+ """Spec for MetricX result - calculates the MetricX score for the given instance using the version specified in the spec."""
+
+ score: Optional[float] = Field(
+ default=None,
+ description="""Output only. MetricX score. Range depends on version.""",
+ )
+
+
+class MetricxResultDict(TypedDict, total=False):
+ """Spec for MetricX result - calculates the MetricX score for the given instance using the version specified in the spec."""
+
+ score: Optional[float]
+ """Output only. MetricX score. Range depends on version."""
+
+
+MetricxResultOrDict = Union[MetricxResult, MetricxResultDict]
+
+
+class ToolCallValidMetricValue(_common.BaseModel):
+ """Tool call valid metric value for an instance."""
+
+ score: Optional[float] = Field(
+ default=None, description="""Output only. Tool call valid score."""
+ )
+
+
+class ToolCallValidMetricValueDict(TypedDict, total=False):
+ """Tool call valid metric value for an instance."""
+
+ score: Optional[float]
+ """Output only. Tool call valid score."""
+
+
+ToolCallValidMetricValueOrDict = Union[
+ ToolCallValidMetricValue, ToolCallValidMetricValueDict
+]
+
+
+class ToolCallValidResults(_common.BaseModel):
+ """Results for tool call valid metric."""
+
+ tool_call_valid_metric_values: Optional[list[ToolCallValidMetricValue]] = Field(
+ default=None, description="""Output only. Tool call valid metric values."""
+ )
+
+
+class ToolCallValidResultsDict(TypedDict, total=False):
+ """Results for tool call valid metric."""
+
+ tool_call_valid_metric_values: Optional[list[ToolCallValidMetricValueDict]]
+ """Output only. Tool call valid metric values."""
+
+
+ToolCallValidResultsOrDict = Union[ToolCallValidResults, ToolCallValidResultsDict]
+
+
+class ToolNameMatchMetricValue(_common.BaseModel):
+ """Tool name match metric value for an instance."""
+
+ score: Optional[float] = Field(
+ default=None, description="""Output only. Tool name match score."""
+ )
+
+
+class ToolNameMatchMetricValueDict(TypedDict, total=False):
+ """Tool name match metric value for an instance."""
+
+ score: Optional[float]
+ """Output only. Tool name match score."""
+
+
+ToolNameMatchMetricValueOrDict = Union[
+ ToolNameMatchMetricValue, ToolNameMatchMetricValueDict
+]
+
+
+class ToolNameMatchResults(_common.BaseModel):
+ """Results for tool name match metric."""
+
+ tool_name_match_metric_values: Optional[list[ToolNameMatchMetricValue]] = Field(
+ default=None, description="""Output only. Tool name match metric values."""
+ )
+
+
+class ToolNameMatchResultsDict(TypedDict, total=False):
+ """Results for tool name match metric."""
+
+ tool_name_match_metric_values: Optional[list[ToolNameMatchMetricValueDict]]
+ """Output only. Tool name match metric values."""
+
+
+ToolNameMatchResultsOrDict = Union[ToolNameMatchResults, ToolNameMatchResultsDict]
+
+
+class ToolParameterKeyMatchMetricValue(_common.BaseModel):
+ """Tool parameter key match metric value for an instance."""
+
+ score: Optional[float] = Field(
+ default=None, description="""Output only. Tool parameter key match score."""
+ )
+
+
+class ToolParameterKeyMatchMetricValueDict(TypedDict, total=False):
+ """Tool parameter key match metric value for an instance."""
+
+ score: Optional[float]
+ """Output only. Tool parameter key match score."""
+
+
+ToolParameterKeyMatchMetricValueOrDict = Union[
+ ToolParameterKeyMatchMetricValue, ToolParameterKeyMatchMetricValueDict
+]
+
+
+class ToolParameterKeyMatchResults(_common.BaseModel):
+ """Results for tool parameter key match metric."""
+
+ tool_parameter_key_match_metric_values: Optional[
+ list[ToolParameterKeyMatchMetricValue]
+ ] = Field(
+ default=None,
+ description="""Output only. Tool parameter key match metric values.""",
+ )
+
+
+class ToolParameterKeyMatchResultsDict(TypedDict, total=False):
+ """Results for tool parameter key match metric."""
+
+ tool_parameter_key_match_metric_values: Optional[
+ list[ToolParameterKeyMatchMetricValueDict]
+ ]
+ """Output only. Tool parameter key match metric values."""
+
+
+ToolParameterKeyMatchResultsOrDict = Union[
+ ToolParameterKeyMatchResults, ToolParameterKeyMatchResultsDict
+]
+
+
+class ToolParameterKVMatchMetricValue(_common.BaseModel):
+ """Tool parameter key value match metric value for an instance."""
+
+ score: Optional[float] = Field(
+ default=None,
+ description="""Output only. Tool parameter key value match score.""",
+ )
+
+
+class ToolParameterKVMatchMetricValueDict(TypedDict, total=False):
+ """Tool parameter key value match metric value for an instance."""
+
+ score: Optional[float]
+ """Output only. Tool parameter key value match score."""
+
+
+ToolParameterKVMatchMetricValueOrDict = Union[
+ ToolParameterKVMatchMetricValue, ToolParameterKVMatchMetricValueDict
+]
+
+
+class ToolParameterKVMatchResults(_common.BaseModel):
+ """Results for tool parameter key value match metric."""
+
+ tool_parameter_kv_match_metric_values: Optional[
+ list[ToolParameterKVMatchMetricValue]
+ ] = Field(
+ default=None,
+ description="""Output only. Tool parameter key value match metric values.""",
+ )
+
+
+class ToolParameterKVMatchResultsDict(TypedDict, total=False):
+ """Results for tool parameter key value match metric."""
+
+ tool_parameter_kv_match_metric_values: Optional[
+ list[ToolParameterKVMatchMetricValueDict]
+ ]
+ """Output only. Tool parameter key value match metric values."""
+
+
+ToolParameterKVMatchResultsOrDict = Union[
+ ToolParameterKVMatchResults, ToolParameterKVMatchResultsDict
+]
+
+
+class EvaluateInstancesResponse(_common.BaseModel):
+ """Result of evaluating an LLM metric."""
+
+ rubric_based_metric_result: Optional[RubricBasedMetricResult] = Field(
+ default=None, description="""Result for rubric based metric."""
+ )
+ metric_results: Optional[list[MetricResult]] = Field(
+ default=None,
+ description="""A list of metric results for each evaluation case. The order of the metric results is guaranteed to be the same as the order of the instances in the request.""",
+ )
+ bleu_results: Optional[BleuResults] = Field(
+ default=None, description="""Results for bleu metric."""
+ )
+ comet_result: Optional[CometResult] = Field(
+ default=None, description="""Translation metrics. Result for Comet metric."""
+ )
+ exact_match_results: Optional[ExactMatchResults] = Field(
+ default=None,
+ description="""Auto metric evaluation results. Results for exact match metric.""",
+ )
+ metricx_result: Optional[MetricxResult] = Field(
+ default=None, description="""Result for Metricx metric."""
+ )
+ pairwise_metric_result: Optional[genai_types.PairwiseMetricResult] = Field(
+ default=None, description="""Result for pairwise metric."""
+ )
+ pointwise_metric_result: Optional[genai_types.PointwiseMetricResult] = Field(
+ default=None, description="""Generic metrics. Result for pointwise metric."""
+ )
+ rouge_results: Optional[RougeResults] = Field(
+ default=None, description="""Results for rouge metric."""
+ )
+ tool_call_valid_results: Optional[ToolCallValidResults] = Field(
+ default=None,
+ description="""Tool call metrics. Results for tool call valid metric.""",
+ )
+ tool_name_match_results: Optional[ToolNameMatchResults] = Field(
+ default=None, description="""Results for tool name match metric."""
+ )
+ tool_parameter_key_match_results: Optional[ToolParameterKeyMatchResults] = Field(
+ default=None, description="""Results for tool parameter key match metric."""
+ )
+ tool_parameter_kv_match_results: Optional[ToolParameterKVMatchResults] = Field(
+ default=None,
+ description="""Results for tool parameter key value match metric.""",
+ )
+
+
+class EvaluateInstancesResponseDict(TypedDict, total=False):
+ """Result of evaluating an LLM metric."""
+
+ rubric_based_metric_result: Optional[RubricBasedMetricResultDict]
+ """Result for rubric based metric."""
+
+ metric_results: Optional[list[MetricResultDict]]
+ """A list of metric results for each evaluation case. The order of the metric results is guaranteed to be the same as the order of the instances in the request."""
+
+ bleu_results: Optional[BleuResultsDict]
+ """Results for bleu metric."""
+
+ comet_result: Optional[CometResultDict]
+ """Translation metrics. Result for Comet metric."""
+
+ exact_match_results: Optional[ExactMatchResultsDict]
+ """Auto metric evaluation results. Results for exact match metric."""
+
+ metricx_result: Optional[MetricxResultDict]
+ """Result for Metricx metric."""
+
+ pairwise_metric_result: Optional[genai_types.PairwiseMetricResultDict]
+ """Result for pairwise metric."""
+
+ pointwise_metric_result: Optional[genai_types.PointwiseMetricResultDict]
+ """Generic metrics. Result for pointwise metric."""
+
+ rouge_results: Optional[RougeResultsDict]
+ """Results for rouge metric."""
+
+ tool_call_valid_results: Optional[ToolCallValidResultsDict]
+ """Tool call metrics. Results for tool call valid metric."""
+
+ tool_name_match_results: Optional[ToolNameMatchResultsDict]
+ """Results for tool name match metric."""
+
+ tool_parameter_key_match_results: Optional[ToolParameterKeyMatchResultsDict]
+ """Results for tool parameter key match metric."""
+
+ tool_parameter_kv_match_results: Optional[ToolParameterKVMatchResultsDict]
+ """Results for tool parameter key value match metric."""
+
+
+EvaluateInstancesResponseOrDict = Union[
+ EvaluateInstancesResponse, EvaluateInstancesResponseDict
+]
+
+
+class GenerateUserScenariosConfig(_common.BaseModel):
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GenerateUserScenariosConfigDict(TypedDict, total=False):
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GenerateUserScenariosConfigOrDict = Union[
+ GenerateUserScenariosConfig, GenerateUserScenariosConfigDict
+]
+
+
+class _GenerateUserScenariosParameters(_common.BaseModel):
+ """Parameters for GenerateUserScenarios."""
+
+ location: Optional[str] = Field(default=None, description="""""")
+ agents: Optional[dict[str, evals_types.AgentConfig]] = Field(
+ default=None, description=""""""
+ )
+ root_agent_id: Optional[str] = Field(default=None, description="""""")
+ user_scenario_generation_config: Optional[
+ evals_types.UserScenarioGenerationConfig
+ ] = Field(default=None, description="""""")
+ config: Optional[GenerateUserScenariosConfig] = Field(
+ default=None, description=""""""
+ )
+ allow_cross_region_model: Optional[bool] = Field(
+ default=None,
+ description="""Opt-in flag to authorize cross-region routing for LLM models.""",
+ )
+
+
+class _GenerateUserScenariosParametersDict(TypedDict, total=False):
+ """Parameters for GenerateUserScenarios."""
+
+ location: Optional[str]
+ """"""
+
+ agents: Optional[dict[str, evals_types.AgentConfig]]
+ """"""
+
+ root_agent_id: Optional[str]
+ """"""
+
+ user_scenario_generation_config: Optional[evals_types.UserScenarioGenerationConfig]
+ """"""
+
+ config: Optional[GenerateUserScenariosConfigDict]
+ """"""
+
+ allow_cross_region_model: Optional[bool]
+ """Opt-in flag to authorize cross-region routing for LLM models."""
+
+
+_GenerateUserScenariosParametersOrDict = Union[
+ _GenerateUserScenariosParameters, _GenerateUserScenariosParametersDict
+]
+
+
+class GenerateUserScenariosResponse(_common.BaseModel):
+ """Response message for DataFoundryService.GenerateUserScenarios."""
+
+ user_scenarios: Optional[list[evals_types.UserScenario]] = Field(
+ default=None, description=""""""
+ )
+
+
+class GenerateUserScenariosResponseDict(TypedDict, total=False):
+ """Response message for DataFoundryService.GenerateUserScenarios."""
+
+ user_scenarios: Optional[list[evals_types.UserScenario]]
+ """"""
+
+
+GenerateUserScenariosResponseOrDict = Union[
+ GenerateUserScenariosResponse, GenerateUserScenariosResponseDict
+]
+
+
+class GenerateLossClustersConfig(_common.BaseModel):
+ """Config for generating loss clusters."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GenerateLossClustersConfigDict(TypedDict, total=False):
+ """Config for generating loss clusters."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GenerateLossClustersConfigOrDict = Union[
+ GenerateLossClustersConfig, GenerateLossClustersConfigDict
+]
+
+
+class _GenerateLossClustersParameters(_common.BaseModel):
+ """Parameters for GenerateLossClusters."""
+
+ location: Optional[str] = Field(
+ default=None,
+ description="""The resource name of the Location. Format: `projects/{project}/locations/{location}`.""",
+ )
+ evaluation_set: Optional[str] = Field(
+ default=None,
+ description="""Reference to a persisted EvaluationSet. The service will read items from this set.""",
+ )
+ inline_results: Optional[list[EvaluationResult]] = Field(
+ default=None,
+ description="""Inline evaluation results. Useful for ephemeral analysis in notebooks/SDKs where data isn't persisted.""",
+ )
+ configs: Optional[list[LossAnalysisConfig]] = Field(
+ default=None,
+ description="""Configuration for the analysis algorithm. Analysis for multiple metrics and multiple candidates could be specified.""",
+ )
+ config: Optional[GenerateLossClustersConfig] = Field(
+ default=None, description="""Config for generating loss clusters."""
+ )
+
+
+class _GenerateLossClustersParametersDict(TypedDict, total=False):
+ """Parameters for GenerateLossClusters."""
+
+ location: Optional[str]
+ """The resource name of the Location. Format: `projects/{project}/locations/{location}`."""
+
+ evaluation_set: Optional[str]
+ """Reference to a persisted EvaluationSet. The service will read items from this set."""
+
+ inline_results: Optional[list[EvaluationResultDict]]
+ """Inline evaluation results. Useful for ephemeral analysis in notebooks/SDKs where data isn't persisted."""
+
+ configs: Optional[list[LossAnalysisConfigDict]]
+ """Configuration for the analysis algorithm. Analysis for multiple metrics and multiple candidates could be specified."""
+
+ config: Optional[GenerateLossClustersConfigDict]
+ """Config for generating loss clusters."""
+
+
+_GenerateLossClustersParametersOrDict = Union[
+ _GenerateLossClustersParameters, _GenerateLossClustersParametersDict
+]
+
+
+class GenerateLossClustersResponse(_common.BaseModel):
+ """Response message for EvaluationAnalyticsService.GenerateLossClusters."""
+
+ analysis_time: Optional[str] = Field(
+ default=None, description="""The timestamp when this analysis was completed."""
+ )
+ results: Optional[list[LossAnalysisResult]] = Field(
+ default=None,
+ description="""The analysis results, one per config provided in the request.""",
+ )
+
+ def show(self) -> None:
+ """Shows the loss pattern analysis report with rich HTML visualization."""
+ from .. import _evals_visualization
+
+ _evals_visualization.display_loss_clusters_response(self)
+
+
+class GenerateLossClustersResponseDict(TypedDict, total=False):
+ """Response message for EvaluationAnalyticsService.GenerateLossClusters."""
+
+ analysis_time: Optional[str]
+ """The timestamp when this analysis was completed."""
+
+ results: Optional[list[LossAnalysisResultDict]]
+ """The analysis results, one per config provided in the request."""
+
+
+GenerateLossClustersResponseOrDict = Union[
+ GenerateLossClustersResponse, GenerateLossClustersResponseDict
+]
+
+
+class GenerateLossClustersOperation(_common.BaseModel):
+ """Long-running operation for generating loss clusters."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[GenerateLossClustersResponse] = Field(
+ default=None,
+ description="""Response message for EvaluationAnalyticsService.GenerateLossClusters.""",
+ )
+
+
+class GenerateLossClustersOperationDict(TypedDict, total=False):
+ """Long-running operation for generating loss clusters."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[GenerateLossClustersResponseDict]
+ """Response message for EvaluationAnalyticsService.GenerateLossClusters."""
+
+
+GenerateLossClustersOperationOrDict = Union[
+ GenerateLossClustersOperation, GenerateLossClustersOperationDict
+]
+
+
+class RubricGenerationConfig(_common.BaseModel):
+ """Config for generating rubrics."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class RubricGenerationConfigDict(TypedDict, total=False):
+ """Config for generating rubrics."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+RubricGenerationConfigOrDict = Union[RubricGenerationConfig, RubricGenerationConfigDict]
+
+
+class _GenerateInstanceRubricsRequest(_common.BaseModel):
+ """Parameters for generating rubrics."""
+
+ contents: Optional[list[genai_types.Content]] = Field(
+ default=None,
+ description="""The prompt to generate rubrics from. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request.""",
+ )
+ predefined_rubric_generation_spec: Optional[genai_types.PredefinedMetricSpec] = (
+ Field(
+ default=None,
+ description="""Specification for using the rubric generation configs of a pre-defined
+ metric, e.g. "generic_quality_v1" and "instruction_following_v1".
+ Some of the configs may be only used in rubric generation and not
+ supporting evaluation, e.g. "fully_customized_generic_quality_v1".
+ If this field is set, the `rubric_generation_spec` field will be ignored.
+ """,
+ )
+ )
+ rubric_generation_spec: Optional[genai_types.RubricGenerationSpec] = Field(
+ default=None,
+ description="""Specification for how the rubrics should be generated.""",
+ )
+ metric_resource_name: Optional[str] = Field(
+ default=None,
+ description="""Registered metric resource name. If this field is set, the configuration provided in this field is used for rubric generation. The `predefined_rubric_generation_spec` and `rubric_generation_spec` fields will be ignored.""",
+ )
+ config: Optional[RubricGenerationConfig] = Field(default=None, description="""""")
+
+
+class _GenerateInstanceRubricsRequestDict(TypedDict, total=False):
+ """Parameters for generating rubrics."""
+
+ contents: Optional[list[genai_types.ContentDict]]
+ """The prompt to generate rubrics from. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request."""
+
+ predefined_rubric_generation_spec: Optional[genai_types.PredefinedMetricSpecDict]
+ """Specification for using the rubric generation configs of a pre-defined
+ metric, e.g. "generic_quality_v1" and "instruction_following_v1".
+ Some of the configs may be only used in rubric generation and not
+ supporting evaluation, e.g. "fully_customized_generic_quality_v1".
+ If this field is set, the `rubric_generation_spec` field will be ignored.
+ """
+
+ rubric_generation_spec: Optional[genai_types.RubricGenerationSpecDict]
+ """Specification for how the rubrics should be generated."""
+
+ metric_resource_name: Optional[str]
+ """Registered metric resource name. If this field is set, the configuration provided in this field is used for rubric generation. The `predefined_rubric_generation_spec` and `rubric_generation_spec` fields will be ignored."""
+
+ config: Optional[RubricGenerationConfigDict]
+ """"""
+
+
+_GenerateInstanceRubricsRequestOrDict = Union[
+ _GenerateInstanceRubricsRequest, _GenerateInstanceRubricsRequestDict
+]
+
+
+class GenerateInstanceRubricsResponse(_common.BaseModel):
+ """Response for generating rubrics."""
+
+ generated_rubrics: Optional[list[evals_types.Rubric]] = Field(
+ default=None, description="""A list of generated rubrics."""
+ )
+
+
+class GenerateInstanceRubricsResponseDict(TypedDict, total=False):
+ """Response for generating rubrics."""
+
+ generated_rubrics: Optional[list[evals_types.Rubric]]
+ """A list of generated rubrics."""
+
+
+GenerateInstanceRubricsResponseOrDict = Union[
+ GenerateInstanceRubricsResponse, GenerateInstanceRubricsResponseDict
+]
+
+
+class GetEvaluationMetricConfig(_common.BaseModel):
+ """Config for getting an evaluation metric."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetEvaluationMetricConfigDict(TypedDict, total=False):
+ """Config for getting an evaluation metric."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetEvaluationMetricConfigOrDict = Union[
+ GetEvaluationMetricConfig, GetEvaluationMetricConfigDict
+]
+
+
+class _GetEvaluationMetricParameters(_common.BaseModel):
+ """Parameters for getting an evaluation metric."""
+
+ metric_resource_name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[GetEvaluationMetricConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetEvaluationMetricParametersDict(TypedDict, total=False):
+ """Parameters for getting an evaluation metric."""
+
+ metric_resource_name: Optional[str]
+ """"""
+
+ config: Optional[GetEvaluationMetricConfigDict]
+ """"""
+
+
+_GetEvaluationMetricParametersOrDict = Union[
+ _GetEvaluationMetricParameters, _GetEvaluationMetricParametersDict
+]
+
+
+class GetEvaluationRunConfig(_common.BaseModel):
+ """Config for get evaluation run."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetEvaluationRunConfigDict(TypedDict, total=False):
+ """Config for get evaluation run."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetEvaluationRunConfigOrDict = Union[GetEvaluationRunConfig, GetEvaluationRunConfigDict]
+
+
+class _GetEvaluationRunParameters(_common.BaseModel):
+ """Represents a job that runs evaluation."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[GetEvaluationRunConfig] = Field(default=None, description="""""")
+
+
+class _GetEvaluationRunParametersDict(TypedDict, total=False):
+ """Represents a job that runs evaluation."""
+
+ name: Optional[str]
+ """"""
+
+ config: Optional[GetEvaluationRunConfigDict]
+ """"""
+
+
+_GetEvaluationRunParametersOrDict = Union[
+ _GetEvaluationRunParameters, _GetEvaluationRunParametersDict
+]
+
+
+class GetEvaluationSetConfig(_common.BaseModel):
+ """Config for get evaluation set."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetEvaluationSetConfigDict(TypedDict, total=False):
+ """Config for get evaluation set."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetEvaluationSetConfigOrDict = Union[GetEvaluationSetConfig, GetEvaluationSetConfigDict]
+
+
+class _GetEvaluationSetParameters(_common.BaseModel):
+ """Represents a job that gets an evaluation set."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[GetEvaluationSetConfig] = Field(default=None, description="""""")
+
+
+class _GetEvaluationSetParametersDict(TypedDict, total=False):
+ """Represents a job that gets an evaluation set."""
+
+ name: Optional[str]
+ """"""
+
+ config: Optional[GetEvaluationSetConfigDict]
+ """"""
+
+
+_GetEvaluationSetParametersOrDict = Union[
+ _GetEvaluationSetParameters, _GetEvaluationSetParametersDict
+]
+
+
+class GetEvaluationItemConfig(_common.BaseModel):
+ """Config for get evaluation item."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetEvaluationItemConfigDict(TypedDict, total=False):
+ """Config for get evaluation item."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetEvaluationItemConfigOrDict = Union[
+ GetEvaluationItemConfig, GetEvaluationItemConfigDict
+]
+
+
+class _GetEvaluationItemParameters(_common.BaseModel):
+ """Represents a job that gets an evaluation item."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[GetEvaluationItemConfig] = Field(default=None, description="""""")
+
+
+class _GetEvaluationItemParametersDict(TypedDict, total=False):
+ """Represents a job that gets an evaluation item."""
+
+ name: Optional[str]
+ """"""
+
+ config: Optional[GetEvaluationItemConfigDict]
+ """"""
+
+
+_GetEvaluationItemParametersOrDict = Union[
+ _GetEvaluationItemParameters, _GetEvaluationItemParametersDict
+]
+
+
+class ListEvaluationMetricsConfig(_common.BaseModel):
+ """Config for listing evaluation metrics."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.
+ For more information about filter syntax, see
+ `AIP-160 `_.""",
+ )
+ order_by: Optional[str] = Field(
+ default=None,
+ description="""A comma-separated list of fields to order by, sorted in ascending
+ order by default. Use ``desc`` after a field name for descending.
+ Example: ``"create_time desc"``.""",
+ )
+
+
+class ListEvaluationMetricsConfigDict(TypedDict, total=False):
+ """Config for listing evaluation metrics."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.
+ For more information about filter syntax, see
+ `AIP-160 `_."""
+
+ order_by: Optional[str]
+ """A comma-separated list of fields to order by, sorted in ascending
+ order by default. Use ``desc`` after a field name for descending.
+ Example: ``"create_time desc"``."""
+
+
+ListEvaluationMetricsConfigOrDict = Union[
+ ListEvaluationMetricsConfig, ListEvaluationMetricsConfigDict
+]
+
+
+class _ListEvaluationMetricsParameters(_common.BaseModel):
+ """Parameters for listing evaluation metrics."""
+
+ config: Optional[ListEvaluationMetricsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListEvaluationMetricsParametersDict(TypedDict, total=False):
+ """Parameters for listing evaluation metrics."""
+
+ config: Optional[ListEvaluationMetricsConfigDict]
+ """"""
+
+
+_ListEvaluationMetricsParametersOrDict = Union[
+ _ListEvaluationMetricsParameters, _ListEvaluationMetricsParametersDict
+]
+
+
+class ListEvaluationMetricsResponse(_common.BaseModel):
+ """Response for listing evaluation metrics."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ evaluation_metrics: Optional[list[EvaluationMetric]] = Field(
+ default=None,
+ description="""List of evaluation metrics.
+ """,
+ )
+
+
+class ListEvaluationMetricsResponseDict(TypedDict, total=False):
+ """Response for listing evaluation metrics."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ evaluation_metrics: Optional[list[EvaluationMetricDict]]
+ """List of evaluation metrics.
+ """
+
+
+ListEvaluationMetricsResponseOrDict = Union[
+ ListEvaluationMetricsResponse, ListEvaluationMetricsResponseDict
+]
+
+
+class OptimizeConfig(_common.BaseModel):
+ """Config for Prompt Optimizer."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ optimization_target: Optional[OptimizeTarget] = Field(
+ default=None,
+ description="""The optimization target for the prompt optimizer. It must be one of the OptimizeTarget enum values: OPTIMIZATION_TARGET_GEMINI_NANO for the prompts from Android core API, OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS for the few-shot prompt optimizer with rubrics, OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE for the few-shot prompt optimizer with target responses.""",
+ )
+ examples_dataframe: Optional[PandasDataFrame] = Field(
+ default=None,
+ description="""The examples dataframe for the few-shot prompt optimizer. It must contain "prompt" and "model_response" columns. Depending on which optimization target is used, it also needs to contain "rubrics" and "rubrics_evaluations" or "target_response" columns.""",
+ )
+
+
+class OptimizeConfigDict(TypedDict, total=False):
+ """Config for Prompt Optimizer."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ optimization_target: Optional[OptimizeTarget]
+ """The optimization target for the prompt optimizer. It must be one of the OptimizeTarget enum values: OPTIMIZATION_TARGET_GEMINI_NANO for the prompts from Android core API, OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS for the few-shot prompt optimizer with rubrics, OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE for the few-shot prompt optimizer with target responses."""
+
+ examples_dataframe: Optional[PandasDataFrame]
+ """The examples dataframe for the few-shot prompt optimizer. It must contain "prompt" and "model_response" columns. Depending on which optimization target is used, it also needs to contain "rubrics" and "rubrics_evaluations" or "target_response" columns."""
+
+
+OptimizeConfigOrDict = Union[OptimizeConfig, OptimizeConfigDict]
+
+
+class _OptimizeRequestParameters(_common.BaseModel):
+ """Request for the optimize_prompt method."""
+
+ content: Optional[genai_types.Content] = Field(default=None, description="""""")
+ config: Optional[OptimizeConfig] = Field(default=None, description="""""")
+
+
+class _OptimizeRequestParametersDict(TypedDict, total=False):
+ """Request for the optimize_prompt method."""
+
+ content: Optional[genai_types.ContentDict]
+ """"""
+
+ config: Optional[OptimizeConfigDict]
+ """"""
+
+
+_OptimizeRequestParametersOrDict = Union[
+ _OptimizeRequestParameters, _OptimizeRequestParametersDict
+]
+
+
+class OptimizeResponseEndpoint(_common.BaseModel):
+ """Response for the optimize_prompt method."""
+
+ content: Optional[genai_types.Content] = Field(default=None, description="""""")
+
+
+class OptimizeResponseEndpointDict(TypedDict, total=False):
+ """Response for the optimize_prompt method."""
+
+ content: Optional[genai_types.ContentDict]
+ """"""
+
+
+OptimizeResponseEndpointOrDict = Union[
+ OptimizeResponseEndpoint, OptimizeResponseEndpointDict
+]
+
+
+class DnsPeeringConfig(_common.BaseModel):
+ """DNS peering configuration. These configurations are used to create DNS peering zones in the Vertex tenant project VPC, enabling resolution of records within the specified domain hosted in the target network's Cloud DNS."""
+
+ domain: Optional[str] = Field(
+ default=None,
+ description="""Required. The DNS name suffix of the zone being peered to, e.g., "my-internal-domain.corp.". Must end with a dot.""",
+ )
+ target_network: Optional[str] = Field(
+ default=None,
+ description="""Required. The VPC network name in the target_project where the DNS zone specified by 'domain' is visible.""",
+ )
+ target_project: Optional[str] = Field(
+ default=None,
+ description="""Required. The project ID hosting the Cloud DNS managed zone that contains the 'domain'. The Vertex AI Service Agent requires the dns.peer role on this project.""",
+ )
+
+
+class DnsPeeringConfigDict(TypedDict, total=False):
+ """DNS peering configuration. These configurations are used to create DNS peering zones in the Vertex tenant project VPC, enabling resolution of records within the specified domain hosted in the target network's Cloud DNS."""
+
+ domain: Optional[str]
+ """Required. The DNS name suffix of the zone being peered to, e.g., "my-internal-domain.corp.". Must end with a dot."""
+
+ target_network: Optional[str]
+ """Required. The VPC network name in the target_project where the DNS zone specified by 'domain' is visible."""
+
+ target_project: Optional[str]
+ """Required. The project ID hosting the Cloud DNS managed zone that contains the 'domain'. The Vertex AI Service Agent requires the dns.peer role on this project."""
+
+
+DnsPeeringConfigOrDict = Union[DnsPeeringConfig, DnsPeeringConfigDict]
+
+
+class PscInterfaceConfig(_common.BaseModel):
+ """Configuration for PSC-I."""
+
+ dns_peering_configs: Optional[list[DnsPeeringConfig]] = Field(
+ default=None,
+ description="""Optional. DNS peering configurations. When specified, Vertex AI will attempt to configure DNS peering zones in the tenant project VPC to resolve the specified domains using the target network's Cloud DNS. The user must grant the dns.peer role to the Vertex AI Service Agent on the target project.""",
+ )
+ network_attachment: Optional[str] = Field(
+ default=None,
+ description="""Optional. The name of the Compute Engine [network attachment](https://cloud.google.com/vpc/docs/about-network-attachments) to attach to the resource within the region and user project. To specify this field, you must have already [created a network attachment] (https://cloud.google.com/vpc/docs/create-manage-network-attachments#create-network-attachments). This field is only used for resources using PSC-I.""",
+ )
+
+
+class PscInterfaceConfigDict(TypedDict, total=False):
+ """Configuration for PSC-I."""
+
+ dns_peering_configs: Optional[list[DnsPeeringConfigDict]]
+ """Optional. DNS peering configurations. When specified, Vertex AI will attempt to configure DNS peering zones in the tenant project VPC to resolve the specified domains using the target network's Cloud DNS. The user must grant the dns.peer role to the Vertex AI Service Agent on the target project."""
+
+ network_attachment: Optional[str]
+ """Optional. The name of the Compute Engine [network attachment](https://cloud.google.com/vpc/docs/about-network-attachments) to attach to the resource within the region and user project. To specify this field, you must have already [created a network attachment] (https://cloud.google.com/vpc/docs/create-manage-network-attachments#create-network-attachments). This field is only used for resources using PSC-I."""
+
+
+PscInterfaceConfigOrDict = Union[PscInterfaceConfig, PscInterfaceConfigDict]
+
+
+class Scheduling(_common.BaseModel):
+ """All parameters related to queuing and scheduling of custom jobs."""
+
+ disable_retries: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Indicates if the job should retry for internal errors after the job starts running. If true, overrides `Scheduling.restart_job_on_worker_restart` to false.""",
+ )
+ max_wait_duration: Optional[str] = Field(
+ default=None,
+ description="""Optional. This is the maximum duration that a job will wait for the requested resources to be provisioned if the scheduling strategy is set to [Strategy.DWS_FLEX_START]. If set to 0, the job will wait indefinitely. The default is 24 hours.""",
+ )
+ restart_job_on_worker_restart: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Restarts the entire CustomJob if a worker gets restarted. This feature can be used by distributed training jobs that are not resilient to workers leaving and joining a job.""",
+ )
+ strategy: Optional[Strategy] = Field(
+ default=None,
+ description="""Optional. This determines which type of scheduling strategy to use.""",
+ )
+ timeout: Optional[str] = Field(
+ default=None,
+ description="""Optional. The maximum job running time. The default is 7 days.""",
+ )
+
+
+class SchedulingDict(TypedDict, total=False):
+ """All parameters related to queuing and scheduling of custom jobs."""
+
+ disable_retries: Optional[bool]
+ """Optional. Indicates if the job should retry for internal errors after the job starts running. If true, overrides `Scheduling.restart_job_on_worker_restart` to false."""
+
+ max_wait_duration: Optional[str]
+ """Optional. This is the maximum duration that a job will wait for the requested resources to be provisioned if the scheduling strategy is set to [Strategy.DWS_FLEX_START]. If set to 0, the job will wait indefinitely. The default is 24 hours."""
+
+ restart_job_on_worker_restart: Optional[bool]
+ """Optional. Restarts the entire CustomJob if a worker gets restarted. This feature can be used by distributed training jobs that are not resilient to workers leaving and joining a job."""
+
+ strategy: Optional[Strategy]
+ """Optional. This determines which type of scheduling strategy to use."""
+
+ timeout: Optional[str]
+ """Optional. The maximum job running time. The default is 7 days."""
+
+
+SchedulingOrDict = Union[Scheduling, SchedulingDict]
+
+
+class EnvVar(_common.BaseModel):
+ """Represents an environment variable present in a Container or Python Module."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Required. Name of the environment variable. Must be a valid C identifier.""",
+ )
+ value: Optional[str] = Field(
+ default=None,
+ description="""Required. Variables that reference a $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not.""",
+ )
+
+
+class EnvVarDict(TypedDict, total=False):
+ """Represents an environment variable present in a Container or Python Module."""
+
+ name: Optional[str]
+ """Required. Name of the environment variable. Must be a valid C identifier."""
+
+ value: Optional[str]
+ """Required. Variables that reference a $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not."""
+
+
+EnvVarOrDict = Union[EnvVar, EnvVarDict]
+
+
+class ContainerSpec(_common.BaseModel):
+ """The spec of a Container."""
+
+ args: Optional[list[str]] = Field(
+ default=None,
+ description="""The arguments to be passed when starting the container.""",
+ )
+ command: Optional[list[str]] = Field(
+ default=None,
+ description="""The command to be invoked when the container is started. It overrides the entrypoint instruction in Dockerfile when provided.""",
+ )
+ env: Optional[list[EnvVar]] = Field(
+ default=None,
+ description="""Environment variables to be passed to the container. Maximum limit is 100.""",
+ )
+ image_uri: Optional[str] = Field(
+ default=None,
+ description="""Required. The URI of a container image in the Container Registry that is to be run on each worker replica.""",
+ )
+
+
+class ContainerSpecDict(TypedDict, total=False):
+ """The spec of a Container."""
+
+ args: Optional[list[str]]
+ """The arguments to be passed when starting the container."""
+
+ command: Optional[list[str]]
+ """The command to be invoked when the container is started. It overrides the entrypoint instruction in Dockerfile when provided."""
+
+ env: Optional[list[EnvVarDict]]
+ """Environment variables to be passed to the container. Maximum limit is 100."""
+
+ image_uri: Optional[str]
+ """Required. The URI of a container image in the Container Registry that is to be run on each worker replica."""
+
+
+ContainerSpecOrDict = Union[ContainerSpec, ContainerSpecDict]
+
+
+class DiskSpec(_common.BaseModel):
+ """Represents the spec of disk options."""
+
+ boot_disk_size_gb: Optional[int] = Field(
+ default=None, description="""Size in GB of the boot disk (default is 100GB)."""
+ )
+ boot_disk_type: Optional[str] = Field(
+ default=None,
+ description="""Type of the boot disk. For non-A3U machines, the default value is "pd-ssd", for A3U machines, the default value is "hyperdisk-balanced". Valid values: "pd-ssd" (Persistent Disk Solid State Drive), "pd-standard" (Persistent Disk Hard Disk Drive) or "hyperdisk-balanced".""",
+ )
+
+
+class DiskSpecDict(TypedDict, total=False):
+ """Represents the spec of disk options."""
+
+ boot_disk_size_gb: Optional[int]
+ """Size in GB of the boot disk (default is 100GB)."""
+
+ boot_disk_type: Optional[str]
+ """Type of the boot disk. For non-A3U machines, the default value is "pd-ssd", for A3U machines, the default value is "hyperdisk-balanced". Valid values: "pd-ssd" (Persistent Disk Solid State Drive), "pd-standard" (Persistent Disk Hard Disk Drive) or "hyperdisk-balanced"."""
+
+
+DiskSpecOrDict = Union[DiskSpec, DiskSpecDict]
+
+
+class LustreMount(_common.BaseModel):
+ """Represents a mount configuration for Lustre file system."""
+
+ filesystem: Optional[str] = Field(
+ default=None, description="""Required. The name of the Lustre filesystem."""
+ )
+ instance_ip: Optional[str] = Field(
+ default=None, description="""Required. IP address of the Lustre instance."""
+ )
+ mount_point: Optional[str] = Field(
+ default=None,
+ description="""Required. Destination mount path. The Lustre file system will be mounted for the user under /mnt/lustre/""",
+ )
+ volume_handle: Optional[str] = Field(
+ default=None,
+ description="""Required. The unique identifier of the Lustre volume.""",
+ )
+
+
+class LustreMountDict(TypedDict, total=False):
+ """Represents a mount configuration for Lustre file system."""
+
+ filesystem: Optional[str]
+ """Required. The name of the Lustre filesystem."""
+
+ instance_ip: Optional[str]
+ """Required. IP address of the Lustre instance."""
+
+ mount_point: Optional[str]
+ """Required. Destination mount path. The Lustre file system will be mounted for the user under /mnt/lustre/"""
+
+ volume_handle: Optional[str]
+ """Required. The unique identifier of the Lustre volume."""
+
+
+LustreMountOrDict = Union[LustreMount, LustreMountDict]
+
+
+class ReservationAffinity(_common.BaseModel):
+ """A ReservationAffinity can be used to configure a Vertex AI resource (e.g., a DeployedModel) to draw its Compute Engine resources from a Shared Reservation, or exclusively from on-demand capacity."""
+
+ key: Optional[str] = Field(
+ default=None,
+ description="""Optional. Corresponds to the label key of a reservation resource. To target a SPECIFIC_RESERVATION by name, use `compute.googleapis.com/reservation-name` as the key and specify the name of your reservation as its value.""",
+ )
+ reservation_affinity_type: Optional[Type] = Field(
+ default=None,
+ description="""Required. Specifies the reservation affinity type.""",
+ )
+ values: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. Corresponds to the label values of a reservation resource. This must be the full resource name of the reservation or reservation block.""",
+ )
+
+
+class ReservationAffinityDict(TypedDict, total=False):
+ """A ReservationAffinity can be used to configure a Vertex AI resource (e.g., a DeployedModel) to draw its Compute Engine resources from a Shared Reservation, or exclusively from on-demand capacity."""
+
+ key: Optional[str]
+ """Optional. Corresponds to the label key of a reservation resource. To target a SPECIFIC_RESERVATION by name, use `compute.googleapis.com/reservation-name` as the key and specify the name of your reservation as its value."""
+
+ reservation_affinity_type: Optional[Type]
+ """Required. Specifies the reservation affinity type."""
+
+ values: Optional[list[str]]
+ """Optional. Corresponds to the label values of a reservation resource. This must be the full resource name of the reservation or reservation block."""
+
+
+ReservationAffinityOrDict = Union[ReservationAffinity, ReservationAffinityDict]
+
+
+class MachineSpec(_common.BaseModel):
+ """Specification of a single machine."""
+
+ accelerator_count: Optional[int] = Field(
+ default=None,
+ description="""The number of accelerators to attach to the machine. For accelerator optimized machine types (https://cloud.google.com/compute/docs/accelerator-optimized-machines), One may set the accelerator_count from 1 to N for machine with N GPUs. If accelerator_count is less than or equal to N / 2, Vertex will co-schedule the replicas of the model into the same VM to save cost. For example, if the machine type is a3-highgpu-8g, which has 8 H100 GPUs, one can set accelerator_count to 1 to 8. If accelerator_count is 1, 2, 3, or 4, Vertex will co-schedule 8, 4, 2, or 2 replicas of the model into the same VM to save cost. When co-scheduling, CPU, memory and storage on the VM will be distributed to replicas on the VM. For example, one can expect a co-scheduled replica requesting 2 GPUs out of a 8-GPU VM will receive 25% of the CPU, memory and storage of the VM. Note that the feature is not compatible with multihost_gpu_node_count. When multihost_gpu_node_count is set, the co-scheduling will not be enabled.""",
+ )
+ accelerator_type: Optional[AcceleratorType] = Field(
+ default=None,
+ description="""Immutable. The type of accelerator(s) that may be attached to the machine as per accelerator_count.""",
+ )
+ gpu_partition_size: Optional[str] = Field(
+ default=None,
+ description="""Optional. Immutable. The Nvidia GPU partition size. When specified, the requested accelerators will be partitioned into smaller GPU partitions. For example, if the request is for 8 units of NVIDIA A100 GPUs, and gpu_partition_size="1g.10gb", the service will create 8 * 7 = 56 partitioned MIG instances. The partition size must be a value supported by the requested accelerator. Refer to [Nvidia GPU Partitioning](https://cloud.google.com/kubernetes-engine/docs/how-to/gpus-multi#multi-instance_gpu_partitions) for the available partition sizes. If set, the accelerator_count should be set to 1.""",
+ )
+ machine_type: Optional[str] = Field(
+ default=None,
+ description="""Immutable. The type of the machine. See the [list of machine types supported for prediction](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute#machine-types) See the [list of machine types supported for custom training](https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types). For DeployedModel this field is optional, and the default value is `n1-standard-2`. For BatchPredictionJob or as part of WorkerPoolSpec this field is required.""",
+ )
+ min_gpu_driver_version: Optional[str] = Field(
+ default=None,
+ description="""Optional. Immutable. The minimum GPU driver version that this machine requires. For example, "535.104.06". If not specified, the default GPU driver version will be used by the underlying infrastructure.""",
+ )
+ multihost_gpu_node_count: Optional[int] = Field(
+ default=None,
+ description="""Optional. Immutable. The number of nodes per replica for multihost GPU deployments.""",
+ )
+ reservation_affinity: Optional[ReservationAffinity] = Field(
+ default=None,
+ description="""Optional. Immutable. Configuration controlling how this resource pool consumes reservation.""",
+ )
+ tpu_topology: Optional[str] = Field(
+ default=None,
+ description="""Immutable. The topology of the TPUs. Corresponds to the TPU topologies available from GKE. (Example: tpu_topology: "2x2x1").""",
+ )
+
+
+class MachineSpecDict(TypedDict, total=False):
+ """Specification of a single machine."""
+
+ accelerator_count: Optional[int]
+ """The number of accelerators to attach to the machine. For accelerator optimized machine types (https://cloud.google.com/compute/docs/accelerator-optimized-machines), One may set the accelerator_count from 1 to N for machine with N GPUs. If accelerator_count is less than or equal to N / 2, Vertex will co-schedule the replicas of the model into the same VM to save cost. For example, if the machine type is a3-highgpu-8g, which has 8 H100 GPUs, one can set accelerator_count to 1 to 8. If accelerator_count is 1, 2, 3, or 4, Vertex will co-schedule 8, 4, 2, or 2 replicas of the model into the same VM to save cost. When co-scheduling, CPU, memory and storage on the VM will be distributed to replicas on the VM. For example, one can expect a co-scheduled replica requesting 2 GPUs out of a 8-GPU VM will receive 25% of the CPU, memory and storage of the VM. Note that the feature is not compatible with multihost_gpu_node_count. When multihost_gpu_node_count is set, the co-scheduling will not be enabled."""
+
+ accelerator_type: Optional[AcceleratorType]
+ """Immutable. The type of accelerator(s) that may be attached to the machine as per accelerator_count."""
+
+ gpu_partition_size: Optional[str]
+ """Optional. Immutable. The Nvidia GPU partition size. When specified, the requested accelerators will be partitioned into smaller GPU partitions. For example, if the request is for 8 units of NVIDIA A100 GPUs, and gpu_partition_size="1g.10gb", the service will create 8 * 7 = 56 partitioned MIG instances. The partition size must be a value supported by the requested accelerator. Refer to [Nvidia GPU Partitioning](https://cloud.google.com/kubernetes-engine/docs/how-to/gpus-multi#multi-instance_gpu_partitions) for the available partition sizes. If set, the accelerator_count should be set to 1."""
+
+ machine_type: Optional[str]
+ """Immutable. The type of the machine. See the [list of machine types supported for prediction](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute#machine-types) See the [list of machine types supported for custom training](https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types). For DeployedModel this field is optional, and the default value is `n1-standard-2`. For BatchPredictionJob or as part of WorkerPoolSpec this field is required."""
+
+ min_gpu_driver_version: Optional[str]
+ """Optional. Immutable. The minimum GPU driver version that this machine requires. For example, "535.104.06". If not specified, the default GPU driver version will be used by the underlying infrastructure."""
+
+ multihost_gpu_node_count: Optional[int]
+ """Optional. Immutable. The number of nodes per replica for multihost GPU deployments."""
+
+ reservation_affinity: Optional[ReservationAffinityDict]
+ """Optional. Immutable. Configuration controlling how this resource pool consumes reservation."""
+
+ tpu_topology: Optional[str]
+ """Immutable. The topology of the TPUs. Corresponds to the TPU topologies available from GKE. (Example: tpu_topology: "2x2x1")."""
+
+
+MachineSpecOrDict = Union[MachineSpec, MachineSpecDict]
+
+
+class NfsMount(_common.BaseModel):
+ """Represents a mount configuration for Network File System (NFS) to mount."""
+
+ mount_point: Optional[str] = Field(
+ default=None,
+ description="""Required. Destination mount path. The NFS will be mounted for the user under /mnt/nfs/""",
+ )
+ path: Optional[str] = Field(
+ default=None,
+ description="""Required. Source path exported from NFS server. Has to start with '/', and combined with the ip address, it indicates the source mount path in the form of `server:path`""",
+ )
+ server: Optional[str] = Field(
+ default=None, description="""Required. IP address of the NFS server."""
+ )
+
+
+class NfsMountDict(TypedDict, total=False):
+ """Represents a mount configuration for Network File System (NFS) to mount."""
+
+ mount_point: Optional[str]
+ """Required. Destination mount path. The NFS will be mounted for the user under /mnt/nfs/"""
+
+ path: Optional[str]
+ """Required. Source path exported from NFS server. Has to start with '/', and combined with the ip address, it indicates the source mount path in the form of `server:path`"""
+
+ server: Optional[str]
+ """Required. IP address of the NFS server."""
+
+
+NfsMountOrDict = Union[NfsMount, NfsMountDict]
+
+
+class PythonPackageSpec(_common.BaseModel):
+ """The spec of a Python packaged code."""
+
+ args: Optional[list[str]] = Field(
+ default=None,
+ description="""Command line arguments to be passed to the Python task.""",
+ )
+ env: Optional[list[EnvVar]] = Field(
+ default=None,
+ description="""Environment variables to be passed to the python module. Maximum limit is 100.""",
+ )
+ executor_image_uri: Optional[str] = Field(
+ default=None,
+ description="""Required. The URI of a container image in Artifact Registry that will run the provided Python package. Vertex AI provides a wide range of executor images with pre-installed packages to meet users' various use cases. See the list of [pre-built containers for training](https://cloud.google.com/vertex-ai/docs/training/pre-built-containers). You must use an image from this list.""",
+ )
+ package_uris: Optional[list[str]] = Field(
+ default=None,
+ description="""Required. The Google Cloud Storage location of the Python package files which are the training program and its dependent packages. The maximum number of package URIs is 100.""",
+ )
+ python_module: Optional[str] = Field(
+ default=None,
+ description="""Required. The Python module name to run after installing the packages.""",
+ )
+
+
+class PythonPackageSpecDict(TypedDict, total=False):
+ """The spec of a Python packaged code."""
+
+ args: Optional[list[str]]
+ """Command line arguments to be passed to the Python task."""
+
+ env: Optional[list[EnvVarDict]]
+ """Environment variables to be passed to the python module. Maximum limit is 100."""
+
+ executor_image_uri: Optional[str]
+ """Required. The URI of a container image in Artifact Registry that will run the provided Python package. Vertex AI provides a wide range of executor images with pre-installed packages to meet users' various use cases. See the list of [pre-built containers for training](https://cloud.google.com/vertex-ai/docs/training/pre-built-containers). You must use an image from this list."""
+
+ package_uris: Optional[list[str]]
+ """Required. The Google Cloud Storage location of the Python package files which are the training program and its dependent packages. The maximum number of package URIs is 100."""
+
+ python_module: Optional[str]
+ """Required. The Python module name to run after installing the packages."""
+
+
+PythonPackageSpecOrDict = Union[PythonPackageSpec, PythonPackageSpecDict]
+
+
+class WorkerPoolSpec(_common.BaseModel):
+ """Represents the spec of a worker pool in a job."""
+
+ container_spec: Optional[ContainerSpec] = Field(
+ default=None, description="""The custom container task."""
+ )
+ disk_spec: Optional[DiskSpec] = Field(default=None, description="""Disk spec.""")
+ lustre_mounts: Optional[list[LustreMount]] = Field(
+ default=None, description="""Optional. List of Lustre mounts."""
+ )
+ machine_spec: Optional[MachineSpec] = Field(
+ default=None,
+ description="""Optional. Immutable. The specification of a single machine.""",
+ )
+ nfs_mounts: Optional[list[NfsMount]] = Field(
+ default=None, description="""Optional. List of NFS mount spec."""
+ )
+ python_package_spec: Optional[PythonPackageSpec] = Field(
+ default=None, description="""The Python packaged task."""
+ )
+ replica_count: Optional[int] = Field(
+ default=None,
+ description="""Optional. The number of worker replicas to use for this worker pool.""",
+ )
+
+
+class WorkerPoolSpecDict(TypedDict, total=False):
+ """Represents the spec of a worker pool in a job."""
+
+ container_spec: Optional[ContainerSpecDict]
+ """The custom container task."""
+
+ disk_spec: Optional[DiskSpecDict]
+ """Disk spec."""
+
+ lustre_mounts: Optional[list[LustreMountDict]]
+ """Optional. List of Lustre mounts."""
+
+ machine_spec: Optional[MachineSpecDict]
+ """Optional. Immutable. The specification of a single machine."""
+
+ nfs_mounts: Optional[list[NfsMountDict]]
+ """Optional. List of NFS mount spec."""
+
+ python_package_spec: Optional[PythonPackageSpecDict]
+ """The Python packaged task."""
+
+ replica_count: Optional[int]
+ """Optional. The number of worker replicas to use for this worker pool."""
+
+
+WorkerPoolSpecOrDict = Union[WorkerPoolSpec, WorkerPoolSpecDict]
+
+
+class CustomJobSpec(_common.BaseModel):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ base_output_directory: Optional[genai_types.GcsDestination] = Field(
+ default=None,
+ description="""The Cloud Storage location to store the output of this CustomJob or HyperparameterTuningJob. For HyperparameterTuningJob, the baseOutputDirectory of each child CustomJob backing a Trial is set to a subdirectory of name id under its parent HyperparameterTuningJob's baseOutputDirectory. The following Vertex AI environment variables will be passed to containers or python modules when this field is set: For CustomJob: * AIP_MODEL_DIR = `/model/` * AIP_CHECKPOINT_DIR = `/checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `/logs/` For CustomJob backing a Trial of HyperparameterTuningJob: * AIP_MODEL_DIR = `//model/` * AIP_CHECKPOINT_DIR = `//checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `//logs/`""",
+ )
+ enable_dashboard_access: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Whether you want Vertex AI to enable access to the customized dashboard in training chief container. If set to `true`, you can access the dashboard at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials).""",
+ )
+ enable_web_access: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Whether you want Vertex AI to enable [interactive shell access](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) to training containers. If set to `true`, you can access interactive shells at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials).""",
+ )
+ experiment: Optional[str] = Field(
+ default=None,
+ description="""Optional. The Experiment associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}`""",
+ )
+ experiment_run: Optional[str] = Field(
+ default=None,
+ description="""Optional. The Experiment Run associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}-{experiment-run-name}`""",
+ )
+ models: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. The name of the Model resources for which to generate a mapping to artifact URIs. Applicable only to some of the Google-provided custom jobs. Format: `projects/{project}/locations/{location}/models/{model}` In order to retrieve a specific version of the model, also provide the version ID or version alias. Example: `projects/{project}/locations/{location}/models/{model}@2` or `projects/{project}/locations/{location}/models/{model}@golden` If no version ID or alias is specified, the "default" version will be returned. The "default" version alias is created for the first version of the model, and can be moved to other versions later on. There will be exactly one default version.""",
+ )
+ network: Optional[str] = Field(
+ default=None,
+ description="""Optional. The full name of the Compute Engine [network](/compute/docs/networks-and-firewalls#networks) to which the Job should be peered. For example, `projects/12345/global/networks/myVPC`. [Format](/compute/docs/reference/rest/v1/networks/insert) is of the form `projects/{project}/global/networks/{network}`. Where {project} is a project number, as in `12345`, and {network} is a network name. To specify this field, you must have already [configured VPC Network Peering for Vertex AI](https://cloud.google.com/vertex-ai/docs/general/vpc-peering). If this field is left unspecified, the job is not peered with any network.""",
+ )
+ persistent_resource_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. The ID of the PersistentResource in the same Project and Location which to run If this is specified, the job will be run on existing machines held by the PersistentResource instead of on-demand short-live machines. The network and CMEK configs on the job should be consistent with those on the PersistentResource, otherwise, the job will be rejected.""",
+ )
+ protected_artifact_location_id: Optional[str] = Field(
+ default=None,
+ description="""The ID of the location to store protected artifacts. e.g. us-central1. Populate only when the location is different than CustomJob location. List of supported locations: https://cloud.google.com/vertex-ai/docs/general/locations""",
+ )
+ psc_interface_config: Optional[PscInterfaceConfig] = Field(
+ default=None, description="""Optional. Configuration for PSC-I for CustomJob."""
+ )
+ reserved_ip_ranges: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. A list of names for the reserved ip ranges under the VPC network that can be used for this job. If set, we will deploy the job within the provided ip ranges. Otherwise, the job will be deployed to any ip ranges under the provided VPC network. Example: ['vertex-ai-ip-range'].""",
+ )
+ scheduling: Optional[Scheduling] = Field(
+ default=None, description="""Scheduling options for a CustomJob."""
+ )
+ service_account: Optional[str] = Field(
+ default=None,
+ description="""Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. If unspecified, the [Vertex AI Custom Code Service Agent](https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) for the CustomJob's project is used.""",
+ )
+ tensorboard: Optional[str] = Field(
+ default=None,
+ description="""Optional. The name of a Vertex AI Tensorboard resource to which this CustomJob will upload Tensorboard logs. Format: `projects/{project}/locations/{location}/tensorboards/{tensorboard}`""",
+ )
+ worker_pool_specs: Optional[list[WorkerPoolSpec]] = Field(
+ default=None,
+ description="""Required. The spec of the worker pools including machine type and Docker image. All worker pools except the first one are optional and can be skipped by providing an empty value.""",
+ )
+
+
+class CustomJobSpecDict(TypedDict, total=False):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ base_output_directory: Optional[genai_types.GcsDestinationDict]
+ """The Cloud Storage location to store the output of this CustomJob or HyperparameterTuningJob. For HyperparameterTuningJob, the baseOutputDirectory of each child CustomJob backing a Trial is set to a subdirectory of name id under its parent HyperparameterTuningJob's baseOutputDirectory. The following Vertex AI environment variables will be passed to containers or python modules when this field is set: For CustomJob: * AIP_MODEL_DIR = `/model/` * AIP_CHECKPOINT_DIR = `/checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `/logs/` For CustomJob backing a Trial of HyperparameterTuningJob: * AIP_MODEL_DIR = `//model/` * AIP_CHECKPOINT_DIR = `//checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `//logs/`"""
+
+ enable_dashboard_access: Optional[bool]
+ """Optional. Whether you want Vertex AI to enable access to the customized dashboard in training chief container. If set to `true`, you can access the dashboard at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials)."""
+
+ enable_web_access: Optional[bool]
+ """Optional. Whether you want Vertex AI to enable [interactive shell access](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) to training containers. If set to `true`, you can access interactive shells at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials)."""
+
+ experiment: Optional[str]
+ """Optional. The Experiment associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}`"""
+
+ experiment_run: Optional[str]
+ """Optional. The Experiment Run associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}-{experiment-run-name}`"""
+
+ models: Optional[list[str]]
+ """Optional. The name of the Model resources for which to generate a mapping to artifact URIs. Applicable only to some of the Google-provided custom jobs. Format: `projects/{project}/locations/{location}/models/{model}` In order to retrieve a specific version of the model, also provide the version ID or version alias. Example: `projects/{project}/locations/{location}/models/{model}@2` or `projects/{project}/locations/{location}/models/{model}@golden` If no version ID or alias is specified, the "default" version will be returned. The "default" version alias is created for the first version of the model, and can be moved to other versions later on. There will be exactly one default version."""
+
+ network: Optional[str]
+ """Optional. The full name of the Compute Engine [network](/compute/docs/networks-and-firewalls#networks) to which the Job should be peered. For example, `projects/12345/global/networks/myVPC`. [Format](/compute/docs/reference/rest/v1/networks/insert) is of the form `projects/{project}/global/networks/{network}`. Where {project} is a project number, as in `12345`, and {network} is a network name. To specify this field, you must have already [configured VPC Network Peering for Vertex AI](https://cloud.google.com/vertex-ai/docs/general/vpc-peering). If this field is left unspecified, the job is not peered with any network."""
+
+ persistent_resource_id: Optional[str]
+ """Optional. The ID of the PersistentResource in the same Project and Location which to run If this is specified, the job will be run on existing machines held by the PersistentResource instead of on-demand short-live machines. The network and CMEK configs on the job should be consistent with those on the PersistentResource, otherwise, the job will be rejected."""
+
+ protected_artifact_location_id: Optional[str]
+ """The ID of the location to store protected artifacts. e.g. us-central1. Populate only when the location is different than CustomJob location. List of supported locations: https://cloud.google.com/vertex-ai/docs/general/locations"""
+
+ psc_interface_config: Optional[PscInterfaceConfigDict]
+ """Optional. Configuration for PSC-I for CustomJob."""
+
+ reserved_ip_ranges: Optional[list[str]]
+ """Optional. A list of names for the reserved ip ranges under the VPC network that can be used for this job. If set, we will deploy the job within the provided ip ranges. Otherwise, the job will be deployed to any ip ranges under the provided VPC network. Example: ['vertex-ai-ip-range']."""
+
+ scheduling: Optional[SchedulingDict]
+ """Scheduling options for a CustomJob."""
+
+ service_account: Optional[str]
+ """Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. If unspecified, the [Vertex AI Custom Code Service Agent](https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) for the CustomJob's project is used."""
+
+ tensorboard: Optional[str]
+ """Optional. The name of a Vertex AI Tensorboard resource to which this CustomJob will upload Tensorboard logs. Format: `projects/{project}/locations/{location}/tensorboards/{tensorboard}`"""
+
+ worker_pool_specs: Optional[list[WorkerPoolSpecDict]]
+ """Required. The spec of the worker pools including machine type and Docker image. All worker pools except the first one are optional and can be skipped by providing an empty value."""
+
+
+CustomJobSpecOrDict = Union[CustomJobSpec, CustomJobSpecDict]
+
+
+class CustomJob(_common.BaseModel):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Required. The display name of the CustomJob. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
+ )
+ job_spec: Optional[CustomJobSpec] = Field(
+ default=None, description="""Required. Job spec."""
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""Customer-managed encryption key options for a CustomJob. If this is set, then all resources created by the CustomJob will be encrypted with the provided encryption key.""",
+ )
+ state: Optional[genai_types.JobState] = Field(
+ default=None, description="""Output only. The detailed state of the job."""
+ )
+ error: Optional[genai_types.GoogleRpcStatus] = Field(
+ default=None,
+ description="""Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Time when the CustomJob was created.""",
+ )
+ end_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Time when the CustomJob entered any of the following states: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The labels with user-defined metadata to organize CustomJobs. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
+ )
+ name: Optional[str] = Field(
+ default=None, description="""Output only. Resource name of a CustomJob."""
+ )
+ satisfies_pzi: Optional[bool] = Field(
+ default=None, description="""Output only. Reserved for future use."""
+ )
+ satisfies_pzs: Optional[bool] = Field(
+ default=None, description="""Output only. Reserved for future use."""
+ )
+ start_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Time when the CustomJob for the first time entered the `JOB_STATE_RUNNING` state.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Time when the CustomJob was most recently updated.""",
+ )
+ web_access_uris: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Output only. URIs for accessing [interactive shells](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) (one URI for each training node). Only available if job_spec.enable_web_access is `true`. The keys are names of each node in the training job; for example, `workerpool0-0` for the primary node, `workerpool1-0` for the first node in the second worker pool, and `workerpool1-1` for the second node in the second worker pool. The values are the URIs for each node's interactive shell.""",
+ )
+
+
+class CustomJobDict(TypedDict, total=False):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ display_name: Optional[str]
+ """Required. The display name of the CustomJob. The name can be up to 128 characters long and can consist of any UTF-8 characters."""
+
+ job_spec: Optional[CustomJobSpecDict]
+ """Required. Job spec."""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """Customer-managed encryption key options for a CustomJob. If this is set, then all resources created by the CustomJob will be encrypted with the provided encryption key."""
+
+ state: Optional[genai_types.JobState]
+ """Output only. The detailed state of the job."""
+
+ error: Optional[genai_types.GoogleRpcStatusDict]
+ """Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Time when the CustomJob was created."""
+
+ end_time: Optional[datetime.datetime]
+ """Output only. Time when the CustomJob entered any of the following states: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`."""
+
+ labels: Optional[dict[str, str]]
+ """The labels with user-defined metadata to organize CustomJobs. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""
+
+ name: Optional[str]
+ """Output only. Resource name of a CustomJob."""
+
+ satisfies_pzi: Optional[bool]
+ """Output only. Reserved for future use."""
+
+ satisfies_pzs: Optional[bool]
+ """Output only. Reserved for future use."""
+
+ start_time: Optional[datetime.datetime]
+ """Output only. Time when the CustomJob for the first time entered the `JOB_STATE_RUNNING` state."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Time when the CustomJob was most recently updated."""
+
+ web_access_uris: Optional[dict[str, str]]
+ """Output only. URIs for accessing [interactive shells](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) (one URI for each training node). Only available if job_spec.enable_web_access is `true`. The keys are names of each node in the training job; for example, `workerpool0-0` for the primary node, `workerpool1-0` for the first node in the second worker pool, and `workerpool1-1` for the second node in the second worker pool. The values are the URIs for each node's interactive shell."""
+
+
+CustomJobOrDict = Union[CustomJob, CustomJobDict]
+
+
+class VertexBaseConfig(_common.BaseModel):
+ """Base config for Vertex AI."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class VertexBaseConfigDict(TypedDict, total=False):
+ """Base config for Vertex AI."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+VertexBaseConfigOrDict = Union[VertexBaseConfig, VertexBaseConfigDict]
+
+
+class _CustomJobParameters(_common.BaseModel):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ custom_job: Optional[CustomJob] = Field(default=None, description="""""")
+ config: Optional[VertexBaseConfig] = Field(default=None, description="""""")
+
+
+class _CustomJobParametersDict(TypedDict, total=False):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ custom_job: Optional[CustomJobDict]
+ """"""
+
+ config: Optional[VertexBaseConfigDict]
+ """"""
+
+
+_CustomJobParametersOrDict = Union[_CustomJobParameters, _CustomJobParametersDict]
+
+
+class _GetCustomJobParameters(_common.BaseModel):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[VertexBaseConfig] = Field(default=None, description="""""")
+
+
+class _GetCustomJobParametersDict(TypedDict, total=False):
+ """Represents a job that runs custom workloads such as a Docker container or a Python package."""
+
+ name: Optional[str]
+ """"""
+
+ config: Optional[VertexBaseConfigDict]
+ """"""
+
+
+_GetCustomJobParametersOrDict = Union[
+ _GetCustomJobParameters, _GetCustomJobParametersDict
+]
+
+
+class CancelQueryJobAgentEngineConfig(_common.BaseModel):
+ """Config for canceling async querying agent engines."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ operation_name: Optional[str] = Field(
+ default=None,
+ description="""Name of the longrunning operation returned from run_query_job.""",
+ )
+
+
+class CancelQueryJobAgentEngineConfigDict(TypedDict, total=False):
+ """Config for canceling async querying agent engines."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ operation_name: Optional[str]
+ """Name of the longrunning operation returned from run_query_job."""
+
+
+CancelQueryJobAgentEngineConfigOrDict = Union[
+ CancelQueryJobAgentEngineConfig, CancelQueryJobAgentEngineConfigDict
+]
+
+
+class _CancelQueryJobAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for canceling async querying agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the reasoning engine resource."""
+ )
+ config: Optional[CancelQueryJobAgentEngineConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CancelQueryJobAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for canceling async querying agent engines."""
+
+ name: Optional[str]
+ """Name of the reasoning engine resource."""
+
+ config: Optional[CancelQueryJobAgentEngineConfigDict]
+ """"""
+
+
+_CancelQueryJobAgentEngineRequestParametersOrDict = Union[
+ _CancelQueryJobAgentEngineRequestParameters,
+ _CancelQueryJobAgentEngineRequestParametersDict,
+]
+
+
+class CancelQueryJobResult(_common.BaseModel):
+ """Result of canceling a query job."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class CancelQueryJobResultDict(TypedDict, total=False):
+ """Result of canceling a query job."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+CancelQueryJobResultOrDict = Union[CancelQueryJobResult, CancelQueryJobResultDict]
+
+
+class CheckQueryJobAgentEngineConfig(_common.BaseModel):
+ """Config for async querying agent engines."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ retrieve_result: Optional[bool] = Field(
+ default=None,
+ description="""Whether to retrieve the results of the query job.""",
+ )
+
+
+class CheckQueryJobAgentEngineConfigDict(TypedDict, total=False):
+ """Config for async querying agent engines."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ retrieve_result: Optional[bool]
+ """Whether to retrieve the results of the query job."""
+
+
+CheckQueryJobAgentEngineConfigOrDict = Union[
+ CheckQueryJobAgentEngineConfig, CheckQueryJobAgentEngineConfigDict
+]
+
+
+class _CheckQueryJobAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for async querying agent engines."""
+
+ name: Optional[str] = Field(default=None, description="""Name of the query job.""")
+ config: Optional[CheckQueryJobAgentEngineConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CheckQueryJobAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for async querying agent engines."""
+
+ name: Optional[str]
+ """Name of the query job."""
+
+ config: Optional[CheckQueryJobAgentEngineConfigDict]
+ """"""
+
+
+_CheckQueryJobAgentEngineRequestParametersOrDict = Union[
+ _CheckQueryJobAgentEngineRequestParameters,
+ _CheckQueryJobAgentEngineRequestParametersDict,
+]
+
+
+class CheckQueryJobResult(_common.BaseModel):
+ """Result of checking a query job."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ operation_name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine operation."""
+ )
+ output_gcs_uri: Optional[str] = Field(
+ default=None, description="""The GCS URI of the output file."""
+ )
+ status: Optional[str] = Field(
+ default=None, description="""Status of the operation."""
+ )
+ result: Optional[str] = Field(
+ default=None, description="""JSON result of the operation."""
+ )
+
+
+class CheckQueryJobResultDict(TypedDict, total=False):
+ """Result of checking a query job."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ operation_name: Optional[str]
+ """Name of the agent engine operation."""
+
+ output_gcs_uri: Optional[str]
+ """The GCS URI of the output file."""
+
+ status: Optional[str]
+ """Status of the operation."""
+
+ result: Optional[str]
+ """JSON result of the operation."""
+
+
+CheckQueryJobResultOrDict = Union[CheckQueryJobResult, CheckQueryJobResultDict]
+
+
+class _RunQueryJobAgentEngineConfig(_common.BaseModel):
+ """Config for running a query job on an agent engine."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ input_gcs_uri: Optional[str] = Field(
+ default=None, description="""The GCS URI of the input file."""
+ )
+ output_gcs_uri: Optional[str] = Field(
+ default=None, description="""The GCS URI of the output file."""
+ )
+
+
+class _RunQueryJobAgentEngineConfigDict(TypedDict, total=False):
+ """Config for running a query job on an agent engine."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ input_gcs_uri: Optional[str]
+ """The GCS URI of the input file."""
+
+ output_gcs_uri: Optional[str]
+ """The GCS URI of the output file."""
+
+
+_RunQueryJobAgentEngineConfigOrDict = Union[
+ _RunQueryJobAgentEngineConfig, _RunQueryJobAgentEngineConfigDict
+]
+
+
+class _RunQueryJobAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for running a query job on an agent engine."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[_RunQueryJobAgentEngineConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _RunQueryJobAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for running a query job on an agent engine."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[_RunQueryJobAgentEngineConfigDict]
+ """"""
+
+
+_RunQueryJobAgentEngineRequestParametersOrDict = Union[
+ _RunQueryJobAgentEngineRequestParameters,
+ _RunQueryJobAgentEngineRequestParametersDict,
+]
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent(
+ _common.BaseModel
+):
+ """The conversation source event for generating memories."""
+
+ content: Optional[genai_types.Content] = Field(
+ default=None, description="""Required. Represents the content of the event."""
+ )
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict(
+ TypedDict, total=False
+):
+ """The conversation source event for generating memories."""
+
+ content: Optional[genai_types.ContentDict]
+ """Required. Represents the content of the event."""
+
+
+MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventOrDict = (
+ Union[
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent,
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict,
+ ]
+)
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource(
+ _common.BaseModel
+):
+ """A conversation source for the example. This is similar to `DirectContentsSource`."""
+
+ events: Optional[
+ list[
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent
+ ]
+ ] = Field(
+ default=None,
+ description="""Optional. Represents the input conversation events for the example.""",
+ )
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict(
+ TypedDict, total=False
+):
+ """A conversation source for the example. This is similar to `DirectContentsSource`."""
+
+ events: Optional[
+ list[
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict
+ ]
+ ]
+ """Optional. Represents the input conversation events for the example."""
+
+
+MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceOrDict = Union[
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource,
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict,
+]
+
+
+class MemoryTopicId(_common.BaseModel):
+ """The topic ID for a memory."""
+
+ custom_memory_topic_label: Optional[str] = Field(
+ default=None,
+ description="""Optional. Represents the custom memory topic label.""",
+ )
+ managed_memory_topic: Optional[ManagedTopicEnum] = Field(
+ default=None, description="""Optional. Represents the managed memory topic."""
+ )
+
+
+class MemoryTopicIdDict(TypedDict, total=False):
+ """The topic ID for a memory."""
+
+ custom_memory_topic_label: Optional[str]
+ """Optional. Represents the custom memory topic label."""
+
+ managed_memory_topic: Optional[ManagedTopicEnum]
+ """Optional. Represents the managed memory topic."""
+
+
+MemoryTopicIdOrDict = Union[MemoryTopicId, MemoryTopicIdDict]
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory(
+ _common.BaseModel
+):
+ """A memory generated by the operation."""
+
+ fact: Optional[str] = Field(
+ default=None,
+ description="""Required. Represents the fact to generate a memory from.""",
+ )
+ topics: Optional[list[MemoryTopicId]] = Field(
+ default=None,
+ description="""Optional. Represents the list of topics that the memory should be associated with. For example, use `custom_memory_topic_label = "jargon"` if the extracted memory is an example of memory extraction for the custom topic `jargon`.""",
+ )
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict(
+ TypedDict, total=False
+):
+ """A memory generated by the operation."""
+
+ fact: Optional[str]
+ """Required. Represents the fact to generate a memory from."""
+
+ topics: Optional[list[MemoryTopicIdDict]]
+ """Optional. Represents the list of topics that the memory should be associated with. For example, use `custom_memory_topic_label = "jargon"` if the extracted memory is an example of memory extraction for the custom topic `jargon`."""
+
+
+MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryOrDict = Union[
+ MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory,
+ MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict,
+]
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExample(_common.BaseModel):
+ """An example of how to generate memories for a particular scope."""
+
+ conversation_source: Optional[
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource
+ ] = Field(default=None, description="""A conversation source for the example.""")
+ generated_memories: Optional[
+ list[MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory]
+ ] = Field(
+ default=None,
+ description="""Optional. Represents the memories that are expected to be generated from the input conversation. An empty list indicates that no memories are expected to be generated for the input conversation.""",
+ )
+
+
+class MemoryBankCustomizationConfigGenerateMemoriesExampleDict(TypedDict, total=False):
+ """An example of how to generate memories for a particular scope."""
+
+ conversation_source: Optional[
+ MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict
+ ]
+ """A conversation source for the example."""
+
+ generated_memories: Optional[
+ list[MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict]
+ ]
+ """Optional. Represents the memories that are expected to be generated from the input conversation. An empty list indicates that no memories are expected to be generated for the input conversation."""
+
+
+MemoryBankCustomizationConfigGenerateMemoriesExampleOrDict = Union[
+ MemoryBankCustomizationConfigGenerateMemoriesExample,
+ MemoryBankCustomizationConfigGenerateMemoriesExampleDict,
+]
+
+
+class MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic(_common.BaseModel):
+ """A custom memory topic defined by the developer."""
+
+ label: Optional[str] = Field(
+ default=None, description="""Required. Represents the label of the topic."""
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="""Required. Represents the description of the memory topic. This should explain what information should be extracted for this topic.""",
+ )
+
+
+class MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict(
+ TypedDict, total=False
+):
+ """A custom memory topic defined by the developer."""
+
+ label: Optional[str]
+ """Required. Represents the label of the topic."""
+
+ description: Optional[str]
+ """Required. Represents the description of the memory topic. This should explain what information should be extracted for this topic."""
+
+
+MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicOrDict = Union[
+ MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic,
+ MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict,
+]
+
+
+class MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic(_common.BaseModel):
+ """A managed memory topic defined by the system."""
+
+ managed_topic_enum: Optional[ManagedTopicEnum] = Field(
+ default=None, description="""Required. Represents the managed topic."""
+ )
+
+
+class MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict(
+ TypedDict, total=False
+):
+ """A managed memory topic defined by the system."""
+
+ managed_topic_enum: Optional[ManagedTopicEnum]
+ """Required. Represents the managed topic."""
+
+
+MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicOrDict = Union[
+ MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic,
+ MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict,
+]
+
+
+class MemoryBankCustomizationConfigMemoryTopic(_common.BaseModel):
+ """A topic of information that should be extracted from conversations and stored as memories."""
+
+ custom_memory_topic: Optional[
+ MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic
+ ] = Field(
+ default=None, description="""A custom memory topic defined by the developer."""
+ )
+ managed_memory_topic: Optional[
+ MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic
+ ] = Field(
+ default=None, description="""A managed memory topic defined by Memory Bank."""
+ )
+
+
+class MemoryBankCustomizationConfigMemoryTopicDict(TypedDict, total=False):
+ """A topic of information that should be extracted from conversations and stored as memories."""
+
+ custom_memory_topic: Optional[
+ MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict
+ ]
+ """A custom memory topic defined by the developer."""
+
+ managed_memory_topic: Optional[
+ MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict
+ ]
+ """A managed memory topic defined by Memory Bank."""
+
+
+MemoryBankCustomizationConfigMemoryTopicOrDict = Union[
+ MemoryBankCustomizationConfigMemoryTopic,
+ MemoryBankCustomizationConfigMemoryTopicDict,
+]
+
+
+class MemoryBankCustomizationConfigConsolidationConfig(_common.BaseModel):
+ """Represents configuration for customizing how memories are consolidated."""
+
+ revisions_per_candidate_count: Optional[int] = Field(
+ default=None,
+ description="""Optional. Represents the maximum number of revisions to consider for each candidate memory. If not set, then the default value (1) will be used, which means that only the latest revision will be considered.""",
+ )
+
+
+class MemoryBankCustomizationConfigConsolidationConfigDict(TypedDict, total=False):
+ """Represents configuration for customizing how memories are consolidated."""
+
+ revisions_per_candidate_count: Optional[int]
+ """Optional. Represents the maximum number of revisions to consider for each candidate memory. If not set, then the default value (1) will be used, which means that only the latest revision will be considered."""
+
+
+MemoryBankCustomizationConfigConsolidationConfigOrDict = Union[
+ MemoryBankCustomizationConfigConsolidationConfig,
+ MemoryBankCustomizationConfigConsolidationConfigDict,
+]
+
+
+class MemoryBankCustomizationConfig(_common.BaseModel):
+ """Represents configuration for organizing natural language memories for a particular scope."""
+
+ enable_third_person_memories: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Indicates whether the memories will be generated in the third person (i.e. "The user generates memories with Memory Bank."). By default, the memories will be generated in the first person (i.e. "I generate memories with Memory Bank.")""",
+ )
+ generate_memories_examples: Optional[
+ list[MemoryBankCustomizationConfigGenerateMemoriesExample]
+ ] = Field(
+ default=None,
+ description="""Optional. Provides examples of how to generate memories for a particular scope.""",
+ )
+ memory_topics: Optional[list[MemoryBankCustomizationConfigMemoryTopic]] = Field(
+ default=None,
+ description="""Optional. Represents topics of information that should be extracted from conversations and stored as memories. If not set, then Memory Bank's default topics will be used.""",
+ )
+ scope_keys: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. Represents the scope keys (i.e. 'user_id') for which to use this config. A request's scope must include all of the provided keys for the config to be used (order does not matter). If empty, then the config will be used for all requests that do not have a more specific config. Only one default config is allowed per Memory Bank.""",
+ )
+ consolidation_config: Optional[MemoryBankCustomizationConfigConsolidationConfig] = (
+ Field(
+ default=None,
+ description="""Optional. Represents configuration for customizing how memories are consolidated together.""",
+ )
+ )
+ disable_natural_language_memories: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Indicates whether natural language memory generation should be disabled for all requests. By default, natural language memory generation is enabled. Set this to `true` when you only want to generate structured memories.""",
+ )
+
+
+class MemoryBankCustomizationConfigDict(TypedDict, total=False):
+ """Represents configuration for organizing natural language memories for a particular scope."""
+
+ enable_third_person_memories: Optional[bool]
+ """Optional. Indicates whether the memories will be generated in the third person (i.e. "The user generates memories with Memory Bank."). By default, the memories will be generated in the first person (i.e. "I generate memories with Memory Bank.")"""
+
+ generate_memories_examples: Optional[
+ list[MemoryBankCustomizationConfigGenerateMemoriesExampleDict]
+ ]
+ """Optional. Provides examples of how to generate memories for a particular scope."""
+
+ memory_topics: Optional[list[MemoryBankCustomizationConfigMemoryTopicDict]]
+ """Optional. Represents topics of information that should be extracted from conversations and stored as memories. If not set, then Memory Bank's default topics will be used."""
+
+ scope_keys: Optional[list[str]]
+ """Optional. Represents the scope keys (i.e. 'user_id') for which to use this config. A request's scope must include all of the provided keys for the config to be used (order does not matter). If empty, then the config will be used for all requests that do not have a more specific config. Only one default config is allowed per Memory Bank."""
+
+ consolidation_config: Optional[MemoryBankCustomizationConfigConsolidationConfigDict]
+ """Optional. Represents configuration for customizing how memories are consolidated together."""
+
+ disable_natural_language_memories: Optional[bool]
+ """Optional. Indicates whether natural language memory generation should be disabled for all requests. By default, natural language memory generation is enabled. Set this to `true` when you only want to generate structured memories."""
+
+
+MemoryBankCustomizationConfigOrDict = Union[
+ MemoryBankCustomizationConfig, MemoryBankCustomizationConfigDict
+]
+
+
+class MemoryGenerationTriggerConfigGenerationTriggerRule(_common.BaseModel):
+ """Represents the active rule that determines when to flush the buffer."""
+
+ event_count: Optional[int] = Field(
+ default=None,
+ description="""Specifies to trigger generation when the event count reaches this limit.""",
+ )
+ fixed_interval: Optional[str] = Field(
+ default=None,
+ description="""Specifies to trigger generation at a fixed interval. The duration must have a minute-level granularity.""",
+ )
+ idle_duration: Optional[str] = Field(
+ default=None,
+ description="""Specifies to trigger generation if the stream is inactive for the specified duration after the most recent event. The duration must have a minute-level granularity.""",
+ )
+
+
+class MemoryGenerationTriggerConfigGenerationTriggerRuleDict(TypedDict, total=False):
+ """Represents the active rule that determines when to flush the buffer."""
+
+ event_count: Optional[int]
+ """Specifies to trigger generation when the event count reaches this limit."""
+
+ fixed_interval: Optional[str]
+ """Specifies to trigger generation at a fixed interval. The duration must have a minute-level granularity."""
+
+ idle_duration: Optional[str]
+ """Specifies to trigger generation if the stream is inactive for the specified duration after the most recent event. The duration must have a minute-level granularity."""
+
+
+MemoryGenerationTriggerConfigGenerationTriggerRuleOrDict = Union[
+ MemoryGenerationTriggerConfigGenerationTriggerRule,
+ MemoryGenerationTriggerConfigGenerationTriggerRuleDict,
+]
+
+
+class MemoryGenerationTriggerConfig(_common.BaseModel):
+ """The configuration for triggering memory generation for ingested events."""
+
+ generation_rule: Optional[MemoryGenerationTriggerConfigGenerationTriggerRule] = (
+ Field(
+ default=None,
+ description="""Optional. Represents the active rule that determines when to flush the buffer. If not set, then the stream will be force flushed immediately.""",
+ )
+ )
+
+
+class MemoryGenerationTriggerConfigDict(TypedDict, total=False):
+ """The configuration for triggering memory generation for ingested events."""
+
+ generation_rule: Optional[MemoryGenerationTriggerConfigGenerationTriggerRuleDict]
+ """Optional. Represents the active rule that determines when to flush the buffer. If not set, then the stream will be force flushed immediately."""
+
+
+MemoryGenerationTriggerConfigOrDict = Union[
+ MemoryGenerationTriggerConfig, MemoryGenerationTriggerConfigDict
+]
+
+
+class ReasoningEngineContextSpecMemoryBankConfigGenerationConfig(_common.BaseModel):
+ """Configuration for how to generate memories."""
+
+ model: Optional[str] = Field(
+ default=None,
+ description="""Optional. The model used to generate memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`.""",
+ )
+ generation_trigger_config: Optional[MemoryGenerationTriggerConfig] = Field(
+ default=None,
+ description="""Optional. Specifies the default trigger configuration for generating memories using `IngestEvents`.""",
+ )
+
+
+class ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict(
+ TypedDict, total=False
+):
+ """Configuration for how to generate memories."""
+
+ model: Optional[str]
+ """Optional. The model used to generate memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`."""
+
+ generation_trigger_config: Optional[MemoryGenerationTriggerConfigDict]
+ """Optional. Specifies the default trigger configuration for generating memories using `IngestEvents`."""
+
+
+ReasoningEngineContextSpecMemoryBankConfigGenerationConfigOrDict = Union[
+ ReasoningEngineContextSpecMemoryBankConfigGenerationConfig,
+ ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict,
+]
+
+
+class ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig(
+ _common.BaseModel
+):
+ """Configuration for how to perform similarity search on memories."""
+
+ embedding_model: Optional[str] = Field(
+ default=None,
+ description="""Required. The model used to generate embeddings to lookup similar memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`.""",
+ )
+
+
+class ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict(
+ TypedDict, total=False
+):
+ """Configuration for how to perform similarity search on memories."""
+
+ embedding_model: Optional[str]
+ """Required. The model used to generate embeddings to lookup similar memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`."""
+
+
+ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigOrDict = Union[
+ ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig,
+ ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict,
+]
+
+
+class ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig(
+ _common.BaseModel
+):
+ """Configuration for TTL of the memories in the Memory Bank based on the action that created or updated the memory."""
+
+ create_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. The TTL duration for memories uploaded via CreateMemory.""",
+ )
+ generate_created_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. The TTL duration for memories newly generated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.CREATED).""",
+ )
+ generate_updated_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. The TTL duration for memories updated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.UPDATED). In the case of an UPDATE action, the `expire_time` of the existing memory will be updated to the new value (now + TTL).""",
+ )
+
+
+class ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict(
+ TypedDict, total=False
+):
+ """Configuration for TTL of the memories in the Memory Bank based on the action that created or updated the memory."""
+
+ create_ttl: Optional[str]
+ """Optional. The TTL duration for memories uploaded via CreateMemory."""
+
+ generate_created_ttl: Optional[str]
+ """Optional. The TTL duration for memories newly generated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.CREATED)."""
+
+ generate_updated_ttl: Optional[str]
+ """Optional. The TTL duration for memories updated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.UPDATED). In the case of an UPDATE action, the `expire_time` of the existing memory will be updated to the new value (now + TTL)."""
+
+
+ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigOrDict = Union[
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig,
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict,
+]
+
+
+class ReasoningEngineContextSpecMemoryBankConfigTtlConfig(_common.BaseModel):
+ """Configuration for automatically setting the TTL ("time-to-live") of the memories in the Memory Bank."""
+
+ default_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. The default TTL duration of the memories in the Memory Bank. This applies to all operations that create or update a memory.""",
+ )
+ granular_ttl_config: Optional[
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig
+ ] = Field(
+ default=None,
+ description="""Optional. The granular TTL configuration of the memories in the Memory Bank.""",
+ )
+ memory_revision_default_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. The default TTL duration of the memory revisions in the Memory Bank. This applies to all operations that create a memory revision. If not set, a default TTL of 365 days will be used.""",
+ )
+
+
+class ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict(TypedDict, total=False):
+ """Configuration for automatically setting the TTL ("time-to-live") of the memories in the Memory Bank."""
+
+ default_ttl: Optional[str]
+ """Optional. The default TTL duration of the memories in the Memory Bank. This applies to all operations that create or update a memory."""
+
+ granular_ttl_config: Optional[
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict
+ ]
+ """Optional. The granular TTL configuration of the memories in the Memory Bank."""
+
+ memory_revision_default_ttl: Optional[str]
+ """Optional. The default TTL duration of the memory revisions in the Memory Bank. This applies to all operations that create a memory revision. If not set, a default TTL of 365 days will be used."""
+
+
+ReasoningEngineContextSpecMemoryBankConfigTtlConfigOrDict = Union[
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfig,
+ ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict,
+]
+
+
+class StructuredMemorySchemaConfig(_common.BaseModel):
+ """Represents the OpenAPI schema of the structured memories."""
+
+ memory_schema: Optional[genai_types.Schema] = Field(
+ default=None,
+ description="""Required. Represents the OpenAPI schema of the structured memories.""",
+ )
+ id: Optional[str] = Field(
+ default=None,
+ description="""Required. Represents the ID of the schema. Must be 1-63 characters, start with a lowercase letter, and consist of lowercase letters, numbers, and hyphens.""",
+ )
+ memory_type: Optional[MemoryType] = Field(
+ default=None,
+ description="""Optional. Represents the type of the structured memories associated with the schema. If not set, then `STRUCTURED_PROFILE` will be used.""",
+ )
+
+
+class StructuredMemorySchemaConfigDict(TypedDict, total=False):
+ """Represents the OpenAPI schema of the structured memories."""
+
+ memory_schema: Optional[genai_types.SchemaDict]
+ """Required. Represents the OpenAPI schema of the structured memories."""
+
+ id: Optional[str]
+ """Required. Represents the ID of the schema. Must be 1-63 characters, start with a lowercase letter, and consist of lowercase letters, numbers, and hyphens."""
+
+ memory_type: Optional[MemoryType]
+ """Optional. Represents the type of the structured memories associated with the schema. If not set, then `STRUCTURED_PROFILE` will be used."""
+
+
+StructuredMemorySchemaConfigOrDict = Union[
+ StructuredMemorySchemaConfig, StructuredMemorySchemaConfigDict
+]
+
+
+class StructuredMemoryConfig(_common.BaseModel):
+ """Configuration for organizing structured memories within a scope."""
+
+ schema_configs: Optional[list[StructuredMemorySchemaConfig]] = Field(
+ default=None,
+ description="""Optional. Represents configuration of the structured memories' schemas.""",
+ )
+ scope_keys: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. Represents the scope keys (i.e. 'user_id') for which to use this config. A request's scope must include all of the provided keys for the config to be used (order does not matter). If empty, then the config will be used for all requests that do not have a more specific config. Only one default config is allowed per Memory Bank.""",
+ )
+
+
+class StructuredMemoryConfigDict(TypedDict, total=False):
+ """Configuration for organizing structured memories within a scope."""
+
+ schema_configs: Optional[list[StructuredMemorySchemaConfigDict]]
+ """Optional. Represents configuration of the structured memories' schemas."""
+
+ scope_keys: Optional[list[str]]
+ """Optional. Represents the scope keys (i.e. 'user_id') for which to use this config. A request's scope must include all of the provided keys for the config to be used (order does not matter). If empty, then the config will be used for all requests that do not have a more specific config. Only one default config is allowed per Memory Bank."""
+
+
+StructuredMemoryConfigOrDict = Union[StructuredMemoryConfig, StructuredMemoryConfigDict]
+
+
+class ReasoningEngineContextSpecMemoryBankConfig(_common.BaseModel):
+ """Specification for a Memory Bank."""
+
+ customization_configs: Optional[list[MemoryBankCustomizationConfig]] = Field(
+ default=None,
+ description="""Optional. Configuration for how to customize Memory Bank behavior for a particular scope.""",
+ )
+ disable_memory_revisions: Optional[bool] = Field(
+ default=None,
+ description="""If true, no memory revisions will be created for any requests to the Memory Bank.""",
+ )
+ generation_config: Optional[
+ ReasoningEngineContextSpecMemoryBankConfigGenerationConfig
+ ] = Field(
+ default=None,
+ description="""Optional. Configuration for how to generate memories for the Memory Bank.""",
+ )
+ similarity_search_config: Optional[
+ ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig
+ ] = Field(
+ default=None,
+ description="""Optional. Configuration for how to perform similarity search on memories. If not set, the Memory Bank will use the default embedding model `text-embedding-005`.""",
+ )
+ ttl_config: Optional[ReasoningEngineContextSpecMemoryBankConfigTtlConfig] = Field(
+ default=None,
+ description="""Optional. Configuration for automatic TTL ("time-to-live") of the memories in the Memory Bank. If not set, TTL will not be applied automatically. The TTL can be explicitly set by modifying the `expire_time` of each Memory resource.""",
+ )
+ structured_memory_configs: Optional[list[StructuredMemoryConfig]] = Field(
+ default=None,
+ description="""Optional. Configuration for organizing structured memories for a particular scope.""",
+ )
+
+
+class ReasoningEngineContextSpecMemoryBankConfigDict(TypedDict, total=False):
+ """Specification for a Memory Bank."""
+
+ customization_configs: Optional[list[MemoryBankCustomizationConfigDict]]
+ """Optional. Configuration for how to customize Memory Bank behavior for a particular scope."""
+
+ disable_memory_revisions: Optional[bool]
+ """If true, no memory revisions will be created for any requests to the Memory Bank."""
+
+ generation_config: Optional[
+ ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict
+ ]
+ """Optional. Configuration for how to generate memories for the Memory Bank."""
+
+ similarity_search_config: Optional[
+ ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict
+ ]
+ """Optional. Configuration for how to perform similarity search on memories. If not set, the Memory Bank will use the default embedding model `text-embedding-005`."""
+
+ ttl_config: Optional[ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict]
+ """Optional. Configuration for automatic TTL ("time-to-live") of the memories in the Memory Bank. If not set, TTL will not be applied automatically. The TTL can be explicitly set by modifying the `expire_time` of each Memory resource."""
+
+ structured_memory_configs: Optional[list[StructuredMemoryConfigDict]]
+ """Optional. Configuration for organizing structured memories for a particular scope."""
+
+
+ReasoningEngineContextSpecMemoryBankConfigOrDict = Union[
+ ReasoningEngineContextSpecMemoryBankConfig,
+ ReasoningEngineContextSpecMemoryBankConfigDict,
+]
+
+
+class ReasoningEngineContextSpec(_common.BaseModel):
+ """Configuration for how Agent Engine sub-resources should manage context."""
+
+ memory_bank_config: Optional[ReasoningEngineContextSpecMemoryBankConfig] = Field(
+ default=None,
+ description="""Optional. Specification for a Memory Bank, which manages memories for the Agent Engine.""",
+ )
+
+
+class ReasoningEngineContextSpecDict(TypedDict, total=False):
+ """Configuration for how Agent Engine sub-resources should manage context."""
+
+ memory_bank_config: Optional[ReasoningEngineContextSpecMemoryBankConfigDict]
+ """Optional. Specification for a Memory Bank, which manages memories for the Agent Engine."""
+
+
+ReasoningEngineContextSpecOrDict = Union[
+ ReasoningEngineContextSpec, ReasoningEngineContextSpecDict
+]
+
+
+class SecretRef(_common.BaseModel):
+ """Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable."""
+
+ secret: Optional[str] = Field(
+ default=None,
+ description="""Required. The name of the secret in Cloud Secret Manager. Format: {secret_name}.""",
+ )
+ version: Optional[str] = Field(
+ default=None,
+ description="""The Cloud Secret Manager secret version. Can be 'latest' for the latest version, an integer for a specific version, or a version alias.""",
+ )
+
+
+class SecretRefDict(TypedDict, total=False):
+ """Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable."""
+
+ secret: Optional[str]
+ """Required. The name of the secret in Cloud Secret Manager. Format: {secret_name}."""
+
+ version: Optional[str]
+ """The Cloud Secret Manager secret version. Can be 'latest' for the latest version, an integer for a specific version, or a version alias."""
+
+
+SecretRefOrDict = Union[SecretRef, SecretRefDict]
+
+
+class SecretEnvVar(_common.BaseModel):
+ """Represents an environment variable where the value is a secret in Cloud Secret Manager."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Required. Name of the secret environment variable.""",
+ )
+ secret_ref: Optional[SecretRef] = Field(
+ default=None,
+ description="""Required. Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable.""",
+ )
+
+
+class SecretEnvVarDict(TypedDict, total=False):
+ """Represents an environment variable where the value is a secret in Cloud Secret Manager."""
+
+ name: Optional[str]
+ """Required. Name of the secret environment variable."""
+
+ secret_ref: Optional[SecretRefDict]
+ """Required. Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable."""
+
+
+SecretEnvVarOrDict = Union[SecretEnvVar, SecretEnvVarDict]
+
+
+class ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfig(
+ _common.BaseModel
+):
+ """Configuration for traffic originating from a Reasoning Engine."""
+
+ agent_gateway: Optional[str] = Field(
+ default=None,
+ description="""Required. The resource name of the Agent Gateway for outbound traffic. It must be set to a Google-managed gateway whose `governed_access_path` is `AGENT_TO_ANYWHERE`. Format: `projects/{project}/locations/{location}/agentGateways/{agent_gateway}`""",
+ )
+
+
+class ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigDict(
+ TypedDict, total=False
+):
+ """Configuration for traffic originating from a Reasoning Engine."""
+
+ agent_gateway: Optional[str]
+ """Required. The resource name of the Agent Gateway for outbound traffic. It must be set to a Google-managed gateway whose `governed_access_path` is `AGENT_TO_ANYWHERE`. Format: `projects/{project}/locations/{location}/agentGateways/{agent_gateway}`"""
+
+
+ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigOrDict = Union[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfig,
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigDict,
+]
+
+
+class ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfig(
+ _common.BaseModel
+):
+ """Configuration for traffic targeting a Reasoning Engine."""
+
+ agent_gateway: Optional[str] = Field(
+ default=None,
+ description="""Required. The resource name of the Agent Gateway to use for inbound traffic. It must be set to a Google-managed gateway whose `governed_access_path` is `CLIENT_TO_AGENT`. Format: `projects/{project}/locations/{location}/agentGateways/{agent_gateway}`""",
+ )
+
+
+class ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigDict(
+ TypedDict, total=False
+):
+ """Configuration for traffic targeting a Reasoning Engine."""
+
+ agent_gateway: Optional[str]
+ """Required. The resource name of the Agent Gateway to use for inbound traffic. It must be set to a Google-managed gateway whose `governed_access_path` is `CLIENT_TO_AGENT`. Format: `projects/{project}/locations/{location}/agentGateways/{agent_gateway}`"""
+
+
+ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigOrDict = Union[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfig,
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigDict,
+]
+
+
+class ReasoningEngineSpecDeploymentSpecAgentGatewayConfig(_common.BaseModel):
+ """Agent Gateway configuration for a Reasoning Engine deployment."""
+
+ agent_to_anywhere_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfig
+ ] = Field(
+ default=None,
+ description="""Optional. Configuration for traffic originating from the Reasoning Engine. When unset, outgoing traffic is not routed through an Agent Gateway.""",
+ )
+ client_to_agent_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfig
+ ] = Field(
+ default=None,
+ description="""Optional. Configuration for traffic targeting the Reasoning Engine. When unset, incoming traffic is not routed through an Agent Gateway.""",
+ )
+
+
+class ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict(TypedDict, total=False):
+ """Agent Gateway configuration for a Reasoning Engine deployment."""
+
+ agent_to_anywhere_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigAgentToAnywhereConfigDict
+ ]
+ """Optional. Configuration for traffic originating from the Reasoning Engine. When unset, outgoing traffic is not routed through an Agent Gateway."""
+
+ client_to_agent_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigClientToAgentConfigDict
+ ]
+ """Optional. Configuration for traffic targeting the Reasoning Engine. When unset, incoming traffic is not routed through an Agent Gateway."""
+
+
+ReasoningEngineSpecDeploymentSpecAgentGatewayConfigOrDict = Union[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfig,
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict,
+]
+
+
+class KeepAliveProbeHttpGet(_common.BaseModel):
+ """Specifies the HTTP GET configuration for the probe."""
+
+ path: Optional[str] = Field(
+ default=None,
+ description="""Required. Specifies the path of the HTTP GET request (e.g., "/is_busy").""",
+ )
+ port: Optional[int] = Field(
+ default=None,
+ description="""Optional. Specifies the port number on the container to which the request is sent.""",
+ )
+
+
+class KeepAliveProbeHttpGetDict(TypedDict, total=False):
+ """Specifies the HTTP GET configuration for the probe."""
+
+ path: Optional[str]
+ """Required. Specifies the path of the HTTP GET request (e.g., "/is_busy")."""
+
+ port: Optional[int]
+ """Optional. Specifies the port number on the container to which the request is sent."""
+
+
+KeepAliveProbeHttpGetOrDict = Union[KeepAliveProbeHttpGet, KeepAliveProbeHttpGetDict]
+
+
+class KeepAliveProbe(_common.BaseModel):
+ """Represents the configuration for keep-alive probe. Contains configuration on a specified endpoint that a deployment host should use to keep the container alive based on the probe settings."""
+
+ http_get: Optional[KeepAliveProbeHttpGet] = Field(
+ default=None,
+ description="""Optional. Specifies the HTTP GET configuration for the probe.""",
+ )
+ max_seconds: Optional[int] = Field(
+ default=None,
+ description="""Optional. Specifies the maximum duration (in seconds) to keep the instance alive via this probe. Can be a maximum of 3600 seconds (1 hour).""",
+ )
+
+
+class KeepAliveProbeDict(TypedDict, total=False):
+ """Represents the configuration for keep-alive probe. Contains configuration on a specified endpoint that a deployment host should use to keep the container alive based on the probe settings."""
+
+ http_get: Optional[KeepAliveProbeHttpGetDict]
+ """Optional. Specifies the HTTP GET configuration for the probe."""
+
+ max_seconds: Optional[int]
+ """Optional. Specifies the maximum duration (in seconds) to keep the instance alive via this probe. Can be a maximum of 3600 seconds (1 hour)."""
+
+
+KeepAliveProbeOrDict = Union[KeepAliveProbe, KeepAliveProbeDict]
+
+
+class ReasoningEngineSpecDeploymentSpec(_common.BaseModel):
+ """The specification of a Reasoning Engine deployment."""
+
+ agent_server_mode: Optional[AgentServerMode] = Field(
+ default=None, description="""The agent server mode."""
+ )
+ container_concurrency: Optional[int] = Field(
+ default=None,
+ description="""Optional. Concurrency for each container and agent server. Recommended value: 2 * cpu + 1. Defaults to 9.""",
+ )
+ env: Optional[list[EnvVar]] = Field(
+ default=None,
+ description="""Optional. Environment variables to be set with the Reasoning Engine deployment. The environment variables can be updated through the UpdateReasoningEngine API.""",
+ )
+ max_instances: Optional[int] = Field(
+ default=None,
+ description="""Optional. The maximum number of application instances that can be launched to handle increased traffic. Defaults to 100. Range: [1, 1000]. If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].""",
+ )
+ min_instances: Optional[int] = Field(
+ default=None,
+ description="""Optional. The minimum number of application instances that will be kept running at all times. Defaults to 1. Range: [0, 75].""",
+ )
+ psc_interface_config: Optional[PscInterfaceConfig] = Field(
+ default=None, description="""Optional. Configuration for PSC-I."""
+ )
+ resource_limits: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Optional. Resource limits for each container. Only 'cpu' and 'memory' keys are supported. Defaults to {"cpu": "4", "memory": "4Gi"}. * The only supported values for CPU are '1', '2', '4', '6' and '8'. For more information, go to https://cloud.google.com/run/docs/configuring/cpu. * The only supported values for memory are '1Gi', '2Gi', ... '32 Gi'. * For required cpu on different memory values, go to https://cloud.google.com/run/docs/configuring/memory-limits""",
+ )
+ secret_env: Optional[list[SecretEnvVar]] = Field(
+ default=None,
+ description="""Optional. Environment variables where the value is a secret in Cloud Secret Manager. To use this feature, add 'Secret Manager Secret Accessor' role (roles/secretmanager.secretAccessor) to AI Platform Reasoning Engine Service Agent.""",
+ )
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfig
+ ] = Field(
+ default=None,
+ description="""Optional. Agent Gateway configuration for the Reasoning Engine deployment.""",
+ )
+ keep_alive_probe: Optional[KeepAliveProbe] = Field(
+ default=None,
+ description="""Optional. Specifies the configuration for keep-alive probe. Contains configuration on a specified endpoint that a deployment host should use to keep the container alive based on the probe settings.""",
+ )
+
+
+class ReasoningEngineSpecDeploymentSpecDict(TypedDict, total=False):
+ """The specification of a Reasoning Engine deployment."""
+
+ agent_server_mode: Optional[AgentServerMode]
+ """The agent server mode."""
+
+ container_concurrency: Optional[int]
+ """Optional. Concurrency for each container and agent server. Recommended value: 2 * cpu + 1. Defaults to 9."""
+
+ env: Optional[list[EnvVarDict]]
+ """Optional. Environment variables to be set with the Reasoning Engine deployment. The environment variables can be updated through the UpdateReasoningEngine API."""
+
+ max_instances: Optional[int]
+ """Optional. The maximum number of application instances that can be launched to handle increased traffic. Defaults to 100. Range: [1, 1000]. If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100]."""
+
+ min_instances: Optional[int]
+ """Optional. The minimum number of application instances that will be kept running at all times. Defaults to 1. Range: [0, 75]."""
+
+ psc_interface_config: Optional[PscInterfaceConfigDict]
+ """Optional. Configuration for PSC-I."""
+
+ resource_limits: Optional[dict[str, str]]
+ """Optional. Resource limits for each container. Only 'cpu' and 'memory' keys are supported. Defaults to {"cpu": "4", "memory": "4Gi"}. * The only supported values for CPU are '1', '2', '4', '6' and '8'. For more information, go to https://cloud.google.com/run/docs/configuring/cpu. * The only supported values for memory are '1Gi', '2Gi', ... '32 Gi'. * For required cpu on different memory values, go to https://cloud.google.com/run/docs/configuring/memory-limits"""
+
+ secret_env: Optional[list[SecretEnvVarDict]]
+ """Optional. Environment variables where the value is a secret in Cloud Secret Manager. To use this feature, add 'Secret Manager Secret Accessor' role (roles/secretmanager.secretAccessor) to AI Platform Reasoning Engine Service Agent."""
+
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
+ ]
+ """Optional. Agent Gateway configuration for the Reasoning Engine deployment."""
+
+ keep_alive_probe: Optional[KeepAliveProbeDict]
+ """Optional. Specifies the configuration for keep-alive probe. Contains configuration on a specified endpoint that a deployment host should use to keep the container alive based on the probe settings."""
+
+
+ReasoningEngineSpecDeploymentSpecOrDict = Union[
+ ReasoningEngineSpecDeploymentSpec, ReasoningEngineSpecDeploymentSpecDict
+]
+
+
+class ReasoningEngineSpecPackageSpec(_common.BaseModel):
+ """User-provided package specification, containing pickled object and package requirements."""
+
+ dependency_files_gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""Optional. The Cloud Storage URI of the dependency files in tar.gz format.""",
+ )
+ pickle_object_gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""Optional. The Cloud Storage URI of the pickled python object.""",
+ )
+ python_version: Optional[str] = Field(
+ default=None,
+ description="""Optional. The Python version. Supported values are 3.9, 3.10, 3.11, 3.12, 3.13, 3.14. If not specified, the default value is 3.10.""",
+ )
+ requirements_gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""Optional. The Cloud Storage URI of the `requirements.txt` file""",
+ )
+
+
+class ReasoningEngineSpecPackageSpecDict(TypedDict, total=False):
+ """User-provided package specification, containing pickled object and package requirements."""
+
+ dependency_files_gcs_uri: Optional[str]
+ """Optional. The Cloud Storage URI of the dependency files in tar.gz format."""
+
+ pickle_object_gcs_uri: Optional[str]
+ """Optional. The Cloud Storage URI of the pickled python object."""
+
+ python_version: Optional[str]
+ """Optional. The Python version. Supported values are 3.9, 3.10, 3.11, 3.12, 3.13, 3.14. If not specified, the default value is 3.10."""
+
+ requirements_gcs_uri: Optional[str]
+ """Optional. The Cloud Storage URI of the `requirements.txt` file"""
+
+
+ReasoningEngineSpecPackageSpecOrDict = Union[
+ ReasoningEngineSpecPackageSpec, ReasoningEngineSpecPackageSpecDict
+]
+
+
+class ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfig(_common.BaseModel):
+ """Configuration for the Agent Development Kit (ADK)."""
+
+ json_config: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Required. The value of the ADK config in JSON format.""",
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigDict(
+ TypedDict, total=False
+):
+ """Configuration for the Agent Development Kit (ADK)."""
+
+ json_config: Optional[dict[str, Any]]
+ """Required. The value of the ADK config in JSON format."""
+
+
+ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfig,
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigDict,
+]
+
+
+class ReasoningEngineSpecSourceCodeSpecInlineSource(_common.BaseModel):
+ """Specifies source code provided as a byte stream."""
+
+ source_archive: Optional[bytes] = Field(
+ default=None,
+ description="""Required. Input only. The application source code archive. It must be a compressed tarball (.tar.gz) file.""",
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecInlineSourceDict(TypedDict, total=False):
+ """Specifies source code provided as a byte stream."""
+
+ source_archive: Optional[bytes]
+ """Required. Input only. The application source code archive. It must be a compressed tarball (.tar.gz) file."""
+
+
+ReasoningEngineSpecSourceCodeSpecInlineSourceOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpecInlineSource,
+ ReasoningEngineSpecSourceCodeSpecInlineSourceDict,
+]
+
+
+class ReasoningEngineSpecSourceCodeSpecAgentConfigSource(_common.BaseModel):
+ """Specification for the deploying from agent config."""
+
+ adk_config: Optional[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfig
+ ] = Field(default=None, description="""Required. The ADK configuration.""")
+ inline_source: Optional[ReasoningEngineSpecSourceCodeSpecInlineSource] = Field(
+ default=None,
+ description="""Optional. Any additional files needed to interpret the config. If a `requirements.txt` file is present in the `inline_source`, the corresponding packages will be installed. If no `requirements.txt` file is present in `inline_source`, then the latest version of `google-adk` will be installed for interpreting the ADK config.""",
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict(TypedDict, total=False):
+ """Specification for the deploying from agent config."""
+
+ adk_config: Optional[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSourceAdkConfigDict
+ ]
+ """Required. The ADK configuration."""
+
+ inline_source: Optional[ReasoningEngineSpecSourceCodeSpecInlineSourceDict]
+ """Optional. Any additional files needed to interpret the config. If a `requirements.txt` file is present in the `inline_source`, the corresponding packages will be installed. If no `requirements.txt` file is present in `inline_source`, then the latest version of `google-adk` will be installed for interpreting the ADK config."""
+
+
+ReasoningEngineSpecSourceCodeSpecAgentConfigSourceOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSource,
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict,
+]
+
+
+class ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig(_common.BaseModel):
+ """Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect.
+
+ This includes the repository, revision, and directory to use.
+ """
+
+ git_repository_link: Optional[str] = Field(
+ default=None,
+ description="""Required. The Developer Connect Git repository link, formatted as `projects/{project_id}/locations/{location_id}/connections/{connection_id}/gitRepositoryLink/{repository_link_id}`.""",
+ )
+ dir: Optional[str] = Field(
+ default=None,
+ description="""Required. Directory, relative to the source root, in which to run the build.""",
+ )
+ revision: Optional[str] = Field(
+ default=None,
+ description="""Required. The revision to fetch from the Git repository such as a branch, a tag, a commit SHA, or any Git ref.""",
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict(
+ TypedDict, total=False
+):
+ """Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect.
+
+ This includes the repository, revision, and directory to use.
+ """
+
+ git_repository_link: Optional[str]
+ """Required. The Developer Connect Git repository link, formatted as `projects/{project_id}/locations/{location_id}/connections/{connection_id}/gitRepositoryLink/{repository_link_id}`."""
+
+ dir: Optional[str]
+ """Required. Directory, relative to the source root, in which to run the build."""
+
+ revision: Optional[str]
+ """Required. The revision to fetch from the Git repository such as a branch, a tag, a commit SHA, or any Git ref."""
+
+
+ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig,
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict,
+]
+
+
+class ReasoningEngineSpecSourceCodeSpecDeveloperConnectSource(_common.BaseModel):
+ """Specifies source code to be fetched from a Git repository managed through the Developer Connect service."""
+
+ config: Optional[ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig] = Field(
+ default=None,
+ description="""Required. The Developer Connect configuration that defines the specific repository, revision, and directory to use as the source code root.""",
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceDict(
+ TypedDict, total=False
+):
+ """Specifies source code to be fetched from a Git repository managed through the Developer Connect service."""
+
+ config: Optional[ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict]
+ """Required. The Developer Connect configuration that defines the specific repository, revision, and directory to use as the source code root."""
+
+
+ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectSource,
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceDict,
+]
+
+
+class ReasoningEngineSpecSourceCodeSpecImageSpec(_common.BaseModel):
+ """The image spec for building an image (within a single build step), based on the config file (i.e. Dockerfile) in the source directory."""
+
+ build_args: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Optional. Build arguments to be used. They will be passed through --build-arg flags.""",
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecImageSpecDict(TypedDict, total=False):
+ """The image spec for building an image (within a single build step), based on the config file (i.e. Dockerfile) in the source directory."""
+
+ build_args: Optional[dict[str, str]]
+ """Optional. Build arguments to be used. They will be passed through --build-arg flags."""
+
+
+ReasoningEngineSpecSourceCodeSpecImageSpecOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpecImageSpec,
+ ReasoningEngineSpecSourceCodeSpecImageSpecDict,
+]
+
+
+class ReasoningEngineSpecSourceCodeSpecPythonSpec(_common.BaseModel):
+ """Specification for running a Python application from source."""
+
+ entrypoint_module: Optional[str] = Field(
+ default=None,
+ description="""Optional. The Python module to load as the entrypoint, specified as a fully qualified module name. For example: path.to.agent. If not specified, defaults to "agent". The project root will be added to Python sys.path, allowing imports to be specified relative to the root. This field should not be set if the source is `agent_config_source`.""",
+ )
+ entrypoint_object: Optional[str] = Field(
+ default=None,
+ description="""Optional. The name of the callable object within the `entrypoint_module` to use as the application If not specified, defaults to "root_agent". This field should not be set if the source is `agent_config_source`.""",
+ )
+ requirements_file: Optional[str] = Field(
+ default=None,
+ description="""Optional. The path to the requirements file, relative to the source root. If not specified, defaults to "requirements.txt".""",
+ )
+ version: Optional[str] = Field(
+ default=None,
+ description="""Optional. The version of Python to use. Support version includes 3.9, 3.10, 3.11, 3.12, 3.13, 3.14. If not specified, default value is 3.10.""",
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecPythonSpecDict(TypedDict, total=False):
+ """Specification for running a Python application from source."""
+
+ entrypoint_module: Optional[str]
+ """Optional. The Python module to load as the entrypoint, specified as a fully qualified module name. For example: path.to.agent. If not specified, defaults to "agent". The project root will be added to Python sys.path, allowing imports to be specified relative to the root. This field should not be set if the source is `agent_config_source`."""
+
+ entrypoint_object: Optional[str]
+ """Optional. The name of the callable object within the `entrypoint_module` to use as the application If not specified, defaults to "root_agent". This field should not be set if the source is `agent_config_source`."""
+
+ requirements_file: Optional[str]
+ """Optional. The path to the requirements file, relative to the source root. If not specified, defaults to "requirements.txt"."""
+
+ version: Optional[str]
+ """Optional. The version of Python to use. Support version includes 3.9, 3.10, 3.11, 3.12, 3.13, 3.14. If not specified, default value is 3.10."""
+
+
+ReasoningEngineSpecSourceCodeSpecPythonSpecOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpecPythonSpec,
+ ReasoningEngineSpecSourceCodeSpecPythonSpecDict,
+]
+
+
+class ReasoningEngineSpecSourceCodeSpec(_common.BaseModel):
+ """Specification for deploying from source code."""
+
+ agent_config_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSource
+ ] = Field(
+ default=None, description="""Source code is generated from the agent config."""
+ )
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectSource
+ ] = Field(
+ default=None,
+ description="""Source code is in a Git repository managed by Developer Connect.""",
+ )
+ image_spec: Optional[ReasoningEngineSpecSourceCodeSpecImageSpec] = Field(
+ default=None,
+ description="""Optional. Configuration for building an image with custom config file.""",
+ )
+ inline_source: Optional[ReasoningEngineSpecSourceCodeSpecInlineSource] = Field(
+ default=None, description="""Source code is provided directly in the request."""
+ )
+ python_spec: Optional[ReasoningEngineSpecSourceCodeSpecPythonSpec] = Field(
+ default=None, description="""Configuration for a Python application."""
+ )
+
+
+class ReasoningEngineSpecSourceCodeSpecDict(TypedDict, total=False):
+ """Specification for deploying from source code."""
+
+ agent_config_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict
+ ]
+ """Source code is generated from the agent config."""
+
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectSourceDict
+ ]
+ """Source code is in a Git repository managed by Developer Connect."""
+
+ image_spec: Optional[ReasoningEngineSpecSourceCodeSpecImageSpecDict]
+ """Optional. Configuration for building an image with custom config file."""
+
+ inline_source: Optional[ReasoningEngineSpecSourceCodeSpecInlineSourceDict]
+ """Source code is provided directly in the request."""
+
+ python_spec: Optional[ReasoningEngineSpecSourceCodeSpecPythonSpecDict]
+ """Configuration for a Python application."""
+
+
+ReasoningEngineSpecSourceCodeSpecOrDict = Union[
+ ReasoningEngineSpecSourceCodeSpec, ReasoningEngineSpecSourceCodeSpecDict
+]
+
+
+class ReasoningEngineSpecContainerSpec(_common.BaseModel):
+ """Specification for deploying from a container image."""
+
+ image_uri: Optional[str] = Field(
+ default=None,
+ description="""Required. The Artifact Registry Docker image URI (e.g., us-central1-docker.pkg.dev/my-project/my-repo/my-image:tag) of the container image that is to be run on each worker replica.""",
+ )
+
+
+class ReasoningEngineSpecContainerSpecDict(TypedDict, total=False):
+ """Specification for deploying from a container image."""
+
+ image_uri: Optional[str]
+ """Required. The Artifact Registry Docker image URI (e.g., us-central1-docker.pkg.dev/my-project/my-repo/my-image:tag) of the container image that is to be run on each worker replica."""
+
+
+ReasoningEngineSpecContainerSpecOrDict = Union[
+ ReasoningEngineSpecContainerSpec, ReasoningEngineSpecContainerSpecDict
+]
+
+
+class ReasoningEngineSpec(_common.BaseModel):
+ """The specification of an agent engine."""
+
+ agent_card: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional. The A2A Agent Card for the agent (if available). It follows the specification at https://a2a-protocol.org/latest/specification/#5-agent-discovery-the-agent-card.""",
+ )
+ agent_framework: Optional[str] = Field(
+ default=None,
+ description="""Optional. The OSS agent framework used to develop the agent. Currently supported values: "google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom".""",
+ )
+ class_methods: Optional[list[dict[str, Any]]] = Field(
+ default=None,
+ description="""Optional. Declarations for object class methods in OpenAPI specification format.""",
+ )
+ deployment_spec: Optional[ReasoningEngineSpecDeploymentSpec] = Field(
+ default=None,
+ description="""Optional. The specification of a Reasoning Engine deployment.""",
+ )
+ effective_identity: Optional[str] = Field(
+ default=None,
+ description="""Output only. The identity to use for the Reasoning Engine. It can contain one of the following values: * service-{project}@gcp-sa-aiplatform-re.googleapis.com (for SERVICE_AGENT identity type) * {name}@{project}.gserviceaccount.com (for SERVICE_ACCOUNT identity type) * agents.global.{org}.system.id.goog/resources/aiplatform/projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine} (for AGENT_IDENTITY identity type)""",
+ )
+ identity_type: Optional[IdentityType] = Field(
+ default=None,
+ description="""Optional. The identity type to use for the Reasoning Engine. If not specified, the `service_account` field will be used if set, otherwise the default Vertex AI Reasoning Engine Service Agent in the project will be used.""",
+ )
+ package_spec: Optional[ReasoningEngineSpecPackageSpec] = Field(
+ default=None,
+ description="""Optional. User provided package spec of the ReasoningEngine. Ignored when users directly specify a deployment image through `deployment_spec.first_party_image_override`, but keeping the field_behavior to avoid introducing breaking changes. The `deployment_source` field should not be set if `package_spec` is specified.""",
+ )
+ service_account: Optional[str] = Field(
+ default=None,
+ description="""Optional. The service account that the Reasoning Engine artifact runs as. It should have "roles/storage.objectViewer" for reading the user project's Cloud Storage and "roles/aiplatform.user" for using Vertex extensions. If not specified, the Vertex AI Reasoning Engine Service Agent in the project will be used.""",
+ )
+ source_code_spec: Optional[ReasoningEngineSpecSourceCodeSpec] = Field(
+ default=None,
+ description="""Deploy from source code files with a defined entrypoint.""",
+ )
+ container_spec: Optional[ReasoningEngineSpecContainerSpec] = Field(
+ default=None,
+ description="""Deploy from a container image with a defined entrypoint and commands.""",
+ )
+
+
+class ReasoningEngineSpecDict(TypedDict, total=False):
+ """The specification of an agent engine."""
+
+ agent_card: Optional[dict[str, Any]]
+ """Optional. The A2A Agent Card for the agent (if available). It follows the specification at https://a2a-protocol.org/latest/specification/#5-agent-discovery-the-agent-card."""
+
+ agent_framework: Optional[str]
+ """Optional. The OSS agent framework used to develop the agent. Currently supported values: "google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"."""
+
+ class_methods: Optional[list[dict[str, Any]]]
+ """Optional. Declarations for object class methods in OpenAPI specification format."""
+
+ deployment_spec: Optional[ReasoningEngineSpecDeploymentSpecDict]
+ """Optional. The specification of a Reasoning Engine deployment."""
+
+ effective_identity: Optional[str]
+ """Output only. The identity to use for the Reasoning Engine. It can contain one of the following values: * service-{project}@gcp-sa-aiplatform-re.googleapis.com (for SERVICE_AGENT identity type) * {name}@{project}.gserviceaccount.com (for SERVICE_ACCOUNT identity type) * agents.global.{org}.system.id.goog/resources/aiplatform/projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine} (for AGENT_IDENTITY identity type)"""
+
+ identity_type: Optional[IdentityType]
+ """Optional. The identity type to use for the Reasoning Engine. If not specified, the `service_account` field will be used if set, otherwise the default Vertex AI Reasoning Engine Service Agent in the project will be used."""
+
+ package_spec: Optional[ReasoningEngineSpecPackageSpecDict]
+ """Optional. User provided package spec of the ReasoningEngine. Ignored when users directly specify a deployment image through `deployment_spec.first_party_image_override`, but keeping the field_behavior to avoid introducing breaking changes. The `deployment_source` field should not be set if `package_spec` is specified."""
+
+ service_account: Optional[str]
+ """Optional. The service account that the Reasoning Engine artifact runs as. It should have "roles/storage.objectViewer" for reading the user project's Cloud Storage and "roles/aiplatform.user" for using Vertex extensions. If not specified, the Vertex AI Reasoning Engine Service Agent in the project will be used."""
+
+ source_code_spec: Optional[ReasoningEngineSpecSourceCodeSpecDict]
+ """Deploy from source code files with a defined entrypoint."""
+
+ container_spec: Optional[ReasoningEngineSpecContainerSpecDict]
+ """Deploy from a container image with a defined entrypoint and commands."""
+
+
+ReasoningEngineSpecOrDict = Union[ReasoningEngineSpec, ReasoningEngineSpecDict]
+
+
+class ReasoningEngineTrafficConfigTrafficSplitAlwaysLatest(_common.BaseModel):
+ """Traffic distribution configuration, where all traffic is sent to the latest Runtime Revision."""
+
+ pass
+
+
+class ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestDict(TypedDict, total=False):
+ """Traffic distribution configuration, where all traffic is sent to the latest Runtime Revision."""
+
+ pass
+
+
+ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestOrDict = Union[
+ ReasoningEngineTrafficConfigTrafficSplitAlwaysLatest,
+ ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestDict,
+]
+
+
+class ReasoningEngineTrafficConfigTrafficSplitManualTarget(_common.BaseModel):
+ """A single target for the traffic split, specifying a Runtime Revision and the percentage of traffic to send to it."""
+
+ percent: Optional[int] = Field(
+ default=None,
+ description="""Required. Specifies percent of the traffic to this Runtime Revision.""",
+ )
+ runtime_revision_name: Optional[str] = Field(
+ default=None,
+ description="""Required. The Runtime Revision name to which to send this portion of traffic, if traffic allocation is by Runtime Revision.""",
+ )
+
+
+class ReasoningEngineTrafficConfigTrafficSplitManualTargetDict(TypedDict, total=False):
+ """A single target for the traffic split, specifying a Runtime Revision and the percentage of traffic to send to it."""
+
+ percent: Optional[int]
+ """Required. Specifies percent of the traffic to this Runtime Revision."""
+
+ runtime_revision_name: Optional[str]
+ """Required. The Runtime Revision name to which to send this portion of traffic, if traffic allocation is by Runtime Revision."""
+
+
+ReasoningEngineTrafficConfigTrafficSplitManualTargetOrDict = Union[
+ ReasoningEngineTrafficConfigTrafficSplitManualTarget,
+ ReasoningEngineTrafficConfigTrafficSplitManualTargetDict,
+]
+
+
+class ReasoningEngineTrafficConfigTrafficSplitManual(_common.BaseModel):
+ """Manual traffic distribution configuration, where the user specifies the Runtime Revision IDs and the percentage of traffic to send to each."""
+
+ targets: Optional[list[ReasoningEngineTrafficConfigTrafficSplitManualTarget]] = (
+ Field(
+ default=None,
+ description="""A list of traffic targets for the Runtimes Revisions. The sum of percentages must equal to 100.""",
+ )
+ )
+
+
+class ReasoningEngineTrafficConfigTrafficSplitManualDict(TypedDict, total=False):
+ """Manual traffic distribution configuration, where the user specifies the Runtime Revision IDs and the percentage of traffic to send to each."""
+
+ targets: Optional[list[ReasoningEngineTrafficConfigTrafficSplitManualTargetDict]]
+ """A list of traffic targets for the Runtimes Revisions. The sum of percentages must equal to 100."""
+
+
+ReasoningEngineTrafficConfigTrafficSplitManualOrDict = Union[
+ ReasoningEngineTrafficConfigTrafficSplitManual,
+ ReasoningEngineTrafficConfigTrafficSplitManualDict,
+]
+
+
+class ReasoningEngineTrafficConfig(_common.BaseModel):
+ """Traffic distribution configuration."""
+
+ traffic_split_always_latest: Optional[
+ ReasoningEngineTrafficConfigTrafficSplitAlwaysLatest
+ ] = Field(
+ default=None,
+ description="""Optional. Traffic distribution configuration, where all traffic is sent to the latest Runtime Revision.""",
+ )
+ traffic_split_manual: Optional[ReasoningEngineTrafficConfigTrafficSplitManual] = (
+ Field(
+ default=None,
+ description="""Optional. Manual traffic distribution configuration, where the user specifies the Runtime Revision IDs and the percentage of traffic to send to each.""",
+ )
+ )
+
+
+class ReasoningEngineTrafficConfigDict(TypedDict, total=False):
+ """Traffic distribution configuration."""
+
+ traffic_split_always_latest: Optional[
+ ReasoningEngineTrafficConfigTrafficSplitAlwaysLatestDict
+ ]
+ """Optional. Traffic distribution configuration, where all traffic is sent to the latest Runtime Revision."""
+
+ traffic_split_manual: Optional[ReasoningEngineTrafficConfigTrafficSplitManualDict]
+ """Optional. Manual traffic distribution configuration, where the user specifies the Runtime Revision IDs and the percentage of traffic to send to each."""
+
+
+ReasoningEngineTrafficConfigOrDict = Union[
+ ReasoningEngineTrafficConfig, ReasoningEngineTrafficConfigDict
+]
+
+
+class ReasoningEngine(_common.BaseModel):
+ """An agent engine."""
+
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""Customer-managed encryption key spec for a ReasoningEngine. If set, this ReasoningEngine and all sub-resources of this ReasoningEngine will be secured by this key.""",
+ )
+ context_spec: Optional[ReasoningEngineContextSpec] = Field(
+ default=None,
+ description="""Optional. Configuration for how Agent Engine sub-resources should manage context.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this ReasoningEngine was created.""",
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="""Optional. The description of the ReasoningEngine.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Required. The display name of the ReasoningEngine.""",
+ )
+ etag: Optional[str] = Field(
+ default=None,
+ description="""Optional. Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None, description="""Labels for the ReasoningEngine."""
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the ReasoningEngine. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}`""",
+ )
+ spec: Optional[ReasoningEngineSpec] = Field(
+ default=None, description="""Optional. Configurations of the ReasoningEngine"""
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this ReasoningEngine was most recently updated.""",
+ )
+ traffic_config: Optional[ReasoningEngineTrafficConfig] = Field(
+ default=None,
+ description="""Optional. Traffic distribution configuration for the Reasoning Engine.""",
+ )
+
+
+class ReasoningEngineDict(TypedDict, total=False):
+ """An agent engine."""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """Customer-managed encryption key spec for a ReasoningEngine. If set, this ReasoningEngine and all sub-resources of this ReasoningEngine will be secured by this key."""
+
+ context_spec: Optional[ReasoningEngineContextSpecDict]
+ """Optional. Configuration for how Agent Engine sub-resources should manage context."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this ReasoningEngine was created."""
+
+ description: Optional[str]
+ """Optional. The description of the ReasoningEngine."""
+
+ display_name: Optional[str]
+ """Required. The display name of the ReasoningEngine."""
+
+ etag: Optional[str]
+ """Optional. Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens."""
+
+ labels: Optional[dict[str, str]]
+ """Labels for the ReasoningEngine."""
+
+ name: Optional[str]
+ """Identifier. The resource name of the ReasoningEngine. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}`"""
+
+ spec: Optional[ReasoningEngineSpecDict]
+ """Optional. Configurations of the ReasoningEngine"""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this ReasoningEngine was most recently updated."""
+
+ traffic_config: Optional[ReasoningEngineTrafficConfigDict]
+ """Optional. Traffic distribution configuration for the Reasoning Engine."""
+
+
+ReasoningEngineOrDict = Union[ReasoningEngine, ReasoningEngineDict]
+
+
+class AgentEngineOperation(_common.BaseModel):
+ """Operation that has an agent engine as a response."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[ReasoningEngine] = Field(
+ default=None, description="""The created Agent Engine."""
+ )
+
+
+class AgentEngineOperationDict(TypedDict, total=False):
+ """Operation that has an agent engine as a response."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[ReasoningEngineDict]
+ """The created Agent Engine."""
+
+
+AgentEngineOperationOrDict = Union[AgentEngineOperation, AgentEngineOperationDict]
+
+
+class CreateAgentEngineConfig(_common.BaseModel):
+ """Config for create agent engine."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""The user-defined name of the Agent Engine.
+
+ The display name can be up to 128 characters long and can comprise any
+ UTF-8 characters.
+ """,
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the Agent Engine."""
+ )
+ spec: Optional[ReasoningEngineSpec] = Field(
+ default=None, description="""Optional. Configurations of the Agent Engine."""
+ )
+ context_spec: Optional[ReasoningEngineContextSpec] = Field(
+ default=None,
+ description="""Optional. The context spec to be used for the Agent Engine.""",
+ )
+ psc_interface_config: Optional[PscInterfaceConfig] = Field(
+ default=None,
+ description="""Optional. The PSC interface config for PSC-I to be used for the
+ Agent Engine.""",
+ )
+ min_instances: Optional[int] = Field(
+ default=None,
+ description="""The minimum number of instances to run for the Agent Engine.
+ Defaults to 1. Range: [0, 10].
+ """,
+ )
+ max_instances: Optional[int] = Field(
+ default=None,
+ description="""The maximum number of instances to run for the Agent Engine.
+ Defaults to 100. Range: [1, 1000].
+ If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
+ """,
+ )
+ resource_limits: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The resource limits to be applied to the Agent Engine.
+ Required keys: 'cpu' and 'memory'.
+ Supported values for 'cpu': '1', '2', '4', '6', '8'.
+ Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
+ """,
+ )
+ container_concurrency: Optional[int] = Field(
+ default=None,
+ description="""The container concurrency to be used for the Agent Engine.
+ Recommended value: 2 * cpu + 1. Defaults to 9.
+ """,
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""The encryption spec to be used for the Agent Engine.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None, description="""The labels to be used for the Agent Engine."""
+ )
+ class_methods: Optional[list[dict[str, Any]]] = Field(
+ default=None,
+ description="""The class methods to be used for the Agent Engine.
+ If specified, they'll override the class methods that are autogenerated by
+ default. By default, methods are generated by inspecting the agent object
+ and generating a corresponding method for each method defined on the
+ agent class.
+ """,
+ )
+ source_packages: Optional[list[str]] = Field(
+ default=None,
+ description="""The user-provided paths to the source packages (if any).
+ If specified, the files in the source packages will be packed into a
+ a tarball file, uploaded to Agent Engine's API, and deployed to the
+ Agent Engine.
+ The following fields will be ignored:
+ - agent
+ - extra_packages
+ - staging_bucket
+ - requirements
+ The following fields will be used to install and use the agent from the
+ source packages:
+ - entrypoint_module (required)
+ - entrypoint_object (required)
+ - requirements_file (optional)
+ - class_methods (required)
+ """,
+ )
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig
+ ] = Field(
+ default=None,
+ description="""Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect. This includes the repository, revision, and directory to use.""",
+ )
+ entrypoint_module: Optional[str] = Field(
+ default=None,
+ description="""The entrypoint module to be used for the Agent Engine
+ This field only used when source_packages is specified.""",
+ )
+ entrypoint_object: Optional[str] = Field(
+ default=None,
+ description="""The entrypoint object to be used for the Agent Engine.
+ This field only used when source_packages is specified.""",
+ )
+ requirements_file: Optional[str] = Field(
+ default=None,
+ description="""The user-provided path to the requirements file (if any).
+ This field is only used when source_packages is specified.
+ If not specified, agent engine will find and use the `requirements.txt` in
+ the source package.
+ """,
+ )
+ agent_framework: Optional[
+ Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
+ ] = Field(
+ default=None,
+ description="""The agent framework to be used for the Agent Engine.
+ The OSS agent framework used to develop the agent.
+ Currently supported values: "google-adk", "langchain", "langgraph",
+ "ag2", "llama-index", "custom".
+ If not specified:
+ - If `agent` is specified, the agent framework will be auto-detected.
+ - If `source_packages` is specified, the agent framework will
+ default to "custom".""",
+ )
+ python_version: Optional[Literal["3.10", "3.11", "3.12", "3.13", "3.14"]] = Field(
+ default=None,
+ description="""The Python version to be used for the Agent Engine.
+ If not specified, it will use the current Python version of the environment.
+ Supported versions: "3.10", "3.11", "3.12", "3.13", "3.14".
+ """,
+ )
+ build_options: Optional[dict[str, list[str]]] = Field(
+ default=None,
+ description="""The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ """,
+ )
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfig
+ ] = Field(
+ default=None,
+ description="""Agent Gateway configuration for a Reasoning Engine deployment.""",
+ )
+ keep_alive_probe: Optional[KeepAliveProbe] = Field(
+ default=None,
+ description="""Optional. Specifies the configuration for keep-alive probe.
+ Contains configuration on a specified endpoint that a deployment host
+ should use to keep the container alive based on the probe settings.""",
+ )
+
+
+class CreateAgentEngineConfigDict(TypedDict, total=False):
+ """Config for create agent engine."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The user-defined name of the Agent Engine.
+
+ The display name can be up to 128 characters long and can comprise any
+ UTF-8 characters.
+ """
+
+ description: Optional[str]
+ """The description of the Agent Engine."""
+
+ spec: Optional[ReasoningEngineSpecDict]
+ """Optional. Configurations of the Agent Engine."""
+
+ context_spec: Optional[ReasoningEngineContextSpecDict]
+ """Optional. The context spec to be used for the Agent Engine."""
+
+ psc_interface_config: Optional[PscInterfaceConfigDict]
+ """Optional. The PSC interface config for PSC-I to be used for the
+ Agent Engine."""
+
+ min_instances: Optional[int]
+ """The minimum number of instances to run for the Agent Engine.
+ Defaults to 1. Range: [0, 10].
+ """
+
+ max_instances: Optional[int]
+ """The maximum number of instances to run for the Agent Engine.
+ Defaults to 100. Range: [1, 1000].
+ If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
+ """
+
+ resource_limits: Optional[dict[str, str]]
+ """The resource limits to be applied to the Agent Engine.
+ Required keys: 'cpu' and 'memory'.
+ Supported values for 'cpu': '1', '2', '4', '6', '8'.
+ Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
+ """
+
+ container_concurrency: Optional[int]
+ """The container concurrency to be used for the Agent Engine.
+ Recommended value: 2 * cpu + 1. Defaults to 9.
+ """
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """The encryption spec to be used for the Agent Engine."""
+
+ labels: Optional[dict[str, str]]
+ """The labels to be used for the Agent Engine."""
+
+ class_methods: Optional[list[dict[str, Any]]]
+ """The class methods to be used for the Agent Engine.
+ If specified, they'll override the class methods that are autogenerated by
+ default. By default, methods are generated by inspecting the agent object
+ and generating a corresponding method for each method defined on the
+ agent class.
+ """
+
+ source_packages: Optional[list[str]]
+ """The user-provided paths to the source packages (if any).
+ If specified, the files in the source packages will be packed into a
+ a tarball file, uploaded to Agent Engine's API, and deployed to the
+ Agent Engine.
+ The following fields will be ignored:
+ - agent
+ - extra_packages
+ - staging_bucket
+ - requirements
+ The following fields will be used to install and use the agent from the
+ source packages:
+ - entrypoint_module (required)
+ - entrypoint_object (required)
+ - requirements_file (optional)
+ - class_methods (required)
+ """
+
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
+ ]
+ """Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect. This includes the repository, revision, and directory to use."""
+
+ entrypoint_module: Optional[str]
+ """The entrypoint module to be used for the Agent Engine
+ This field only used when source_packages is specified."""
+
+ entrypoint_object: Optional[str]
+ """The entrypoint object to be used for the Agent Engine.
+ This field only used when source_packages is specified."""
+
+ requirements_file: Optional[str]
+ """The user-provided path to the requirements file (if any).
+ This field is only used when source_packages is specified.
+ If not specified, agent engine will find and use the `requirements.txt` in
+ the source package.
+ """
+
+ agent_framework: Optional[
+ Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
+ ]
+ """The agent framework to be used for the Agent Engine.
+ The OSS agent framework used to develop the agent.
+ Currently supported values: "google-adk", "langchain", "langgraph",
+ "ag2", "llama-index", "custom".
+ If not specified:
+ - If `agent` is specified, the agent framework will be auto-detected.
+ - If `source_packages` is specified, the agent framework will
+ default to "custom"."""
+
+ python_version: Optional[Literal["3.10", "3.11", "3.12", "3.13", "3.14"]]
+ """The Python version to be used for the Agent Engine.
+ If not specified, it will use the current Python version of the environment.
+ Supported versions: "3.10", "3.11", "3.12", "3.13", "3.14".
+ """
+
+ build_options: Optional[dict[str, list[str]]]
+ """The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ """
+
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
+ ]
+ """Agent Gateway configuration for a Reasoning Engine deployment."""
+
+ keep_alive_probe: Optional[KeepAliveProbeDict]
+ """Optional. Specifies the configuration for keep-alive probe.
+ Contains configuration on a specified endpoint that a deployment host
+ should use to keep the container alive based on the probe settings."""
+
+
+CreateAgentEngineConfigOrDict = Union[
+ CreateAgentEngineConfig, CreateAgentEngineConfigDict
+]
+
+
+class _CreateAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for creating agent engines."""
+
+ config: Optional[CreateAgentEngineConfig] = Field(default=None, description="""""")
+
+
+class _CreateAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating agent engines."""
+
+ config: Optional[CreateAgentEngineConfigDict]
+ """"""
+
+
+_CreateAgentEngineRequestParametersOrDict = Union[
+ _CreateAgentEngineRequestParameters, _CreateAgentEngineRequestParametersDict
+]
+
+
+class DeleteAgentEngineConfig(_common.BaseModel):
+ """Config for deleting agent engine."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteAgentEngineConfigDict(TypedDict, total=False):
+ """Config for deleting agent engine."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteAgentEngineConfigOrDict = Union[
+ DeleteAgentEngineConfig, DeleteAgentEngineConfigDict
+]
+
+
+class _DeleteAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for deleting agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ force: Optional[bool] = Field(
+ default=False,
+ description="""If set to true, any child resources will also be deleted.""",
+ )
+ config: Optional[DeleteAgentEngineConfig] = Field(default=None, description="""""")
+
+
+class _DeleteAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ force: Optional[bool]
+ """If set to true, any child resources will also be deleted."""
+
+ config: Optional[DeleteAgentEngineConfigDict]
+ """"""
+
+
+_DeleteAgentEngineRequestParametersOrDict = Union[
+ _DeleteAgentEngineRequestParameters, _DeleteAgentEngineRequestParametersDict
+]
+
+
+class DeleteAgentEngineOperation(_common.BaseModel):
+ """Operation for deleting agent engines."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteAgentEngineOperationDict(TypedDict, total=False):
+ """Operation for deleting agent engines."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteAgentEngineOperationOrDict = Union[
+ DeleteAgentEngineOperation, DeleteAgentEngineOperationDict
+]
+
+
+class GetAgentEngineConfig(_common.BaseModel):
+ """Config for create agent engine."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineConfigDict(TypedDict, total=False):
+ """Config for create agent engine."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineConfigOrDict = Union[GetAgentEngineConfig, GetAgentEngineConfigDict]
+
+
+class _GetAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for getting agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[GetAgentEngineConfig] = Field(default=None, description="""""")
+
+
+class _GetAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[GetAgentEngineConfigDict]
+ """"""
+
+
+_GetAgentEngineRequestParametersOrDict = Union[
+ _GetAgentEngineRequestParameters, _GetAgentEngineRequestParametersDict
+]
+
+
+class ListAgentEngineConfig(_common.BaseModel):
+ """Config for listing agent engines."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListAgentEngineConfigDict(TypedDict, total=False):
+ """Config for listing agent engines."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListAgentEngineConfigOrDict = Union[ListAgentEngineConfig, ListAgentEngineConfigDict]
+
+
+class _ListAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for listing agent engines."""
+
+ config: Optional[ListAgentEngineConfig] = Field(default=None, description="""""")
+
+
+class _ListAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing agent engines."""
+
+ config: Optional[ListAgentEngineConfigDict]
+ """"""
+
+
+_ListAgentEngineRequestParametersOrDict = Union[
+ _ListAgentEngineRequestParameters, _ListAgentEngineRequestParametersDict
+]
+
+
+class ListReasoningEnginesResponse(_common.BaseModel):
+ """Response for listing agent engines."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ reasoning_engines: Optional[list[ReasoningEngine]] = Field(
+ default=None,
+ description="""List of agent engines.
+ """,
+ )
+
+
+class ListReasoningEnginesResponseDict(TypedDict, total=False):
+ """Response for listing agent engines."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ reasoning_engines: Optional[list[ReasoningEngineDict]]
+ """List of agent engines.
+ """
+
+
+ListReasoningEnginesResponseOrDict = Union[
+ ListReasoningEnginesResponse, ListReasoningEnginesResponseDict
+]
+
+
+class GetAgentEngineOperationConfig(_common.BaseModel):
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineOperationConfigDict(TypedDict, total=False):
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineOperationConfigOrDict = Union[
+ GetAgentEngineOperationConfig, GetAgentEngineOperationConfigDict
+]
+
+
+class _GetAgentEngineOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation with an agent engine as a response."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetAgentEngineOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetAgentEngineOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation with an agent engine as a response."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetAgentEngineOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetAgentEngineOperationParametersOrDict = Union[
+ _GetAgentEngineOperationParameters, _GetAgentEngineOperationParametersDict
+]
+
+
+class QueryAgentEngineConfig(_common.BaseModel):
+ """Config for querying agent engines."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ class_method: Optional[str] = Field(
+ default=None, description="""The class method to call."""
+ )
+ input: Optional[dict[str, Any]] = Field(
+ default=None, description="""The input to the class method."""
+ )
+ include_all_fields: Optional[bool] = Field(default=False, description="""""")
+
+
+class QueryAgentEngineConfigDict(TypedDict, total=False):
+ """Config for querying agent engines."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ class_method: Optional[str]
+ """The class method to call."""
+
+ input: Optional[dict[str, Any]]
+ """The input to the class method."""
+
+ include_all_fields: Optional[bool]
+ """"""
+
+
+QueryAgentEngineConfigOrDict = Union[QueryAgentEngineConfig, QueryAgentEngineConfigDict]
+
+
+class _QueryAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for querying agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[QueryAgentEngineConfig] = Field(default=None, description="""""")
+
+
+class _QueryAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for querying agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[QueryAgentEngineConfigDict]
+ """"""
+
+
+_QueryAgentEngineRequestParametersOrDict = Union[
+ _QueryAgentEngineRequestParameters, _QueryAgentEngineRequestParametersDict
+]
+
+
+class QueryReasoningEngineResponse(_common.BaseModel):
+ """The response for querying an agent engine."""
+
+ output: Optional[Any] = Field(
+ default=None,
+ description="""Response provided by users in JSON object format.""",
+ )
+
+
+class QueryReasoningEngineResponseDict(TypedDict, total=False):
+ """The response for querying an agent engine."""
+
+ output: Optional[Any]
+ """Response provided by users in JSON object format."""
+
+
+QueryReasoningEngineResponseOrDict = Union[
+ QueryReasoningEngineResponse, QueryReasoningEngineResponseDict
+]
+
+
+class UpdateAgentEngineConfig(_common.BaseModel):
+ """Config for updating agent engine."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""The user-defined name of the Agent Engine.
+
+ The display name can be up to 128 characters long and can comprise any
+ UTF-8 characters.
+ """,
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the Agent Engine."""
+ )
+ spec: Optional[ReasoningEngineSpec] = Field(
+ default=None, description="""Optional. Configurations of the Agent Engine."""
+ )
+ context_spec: Optional[ReasoningEngineContextSpec] = Field(
+ default=None,
+ description="""Optional. The context spec to be used for the Agent Engine.""",
+ )
+ psc_interface_config: Optional[PscInterfaceConfig] = Field(
+ default=None,
+ description="""Optional. The PSC interface config for PSC-I to be used for the
+ Agent Engine.""",
+ )
+ min_instances: Optional[int] = Field(
+ default=None,
+ description="""The minimum number of instances to run for the Agent Engine.
+ Defaults to 1. Range: [0, 10].
+ """,
+ )
+ max_instances: Optional[int] = Field(
+ default=None,
+ description="""The maximum number of instances to run for the Agent Engine.
+ Defaults to 100. Range: [1, 1000].
+ If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
+ """,
+ )
+ resource_limits: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The resource limits to be applied to the Agent Engine.
+ Required keys: 'cpu' and 'memory'.
+ Supported values for 'cpu': '1', '2', '4', '6', '8'.
+ Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
+ """,
+ )
+ container_concurrency: Optional[int] = Field(
+ default=None,
+ description="""The container concurrency to be used for the Agent Engine.
+ Recommended value: 2 * cpu + 1. Defaults to 9.
+ """,
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""The encryption spec to be used for the Agent Engine.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None, description="""The labels to be used for the Agent Engine."""
+ )
+ class_methods: Optional[list[dict[str, Any]]] = Field(
+ default=None,
+ description="""The class methods to be used for the Agent Engine.
+ If specified, they'll override the class methods that are autogenerated by
+ default. By default, methods are generated by inspecting the agent object
+ and generating a corresponding method for each method defined on the
+ agent class.
+ """,
+ )
+ source_packages: Optional[list[str]] = Field(
+ default=None,
+ description="""The user-provided paths to the source packages (if any).
+ If specified, the files in the source packages will be packed into a
+ a tarball file, uploaded to Agent Engine's API, and deployed to the
+ Agent Engine.
+ The following fields will be ignored:
+ - agent
+ - extra_packages
+ - staging_bucket
+ - requirements
+ The following fields will be used to install and use the agent from the
+ source packages:
+ - entrypoint_module (required)
+ - entrypoint_object (required)
+ - requirements_file (optional)
+ - class_methods (required)
+ """,
+ )
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig
+ ] = Field(
+ default=None,
+ description="""Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect. This includes the repository, revision, and directory to use.""",
+ )
+ entrypoint_module: Optional[str] = Field(
+ default=None,
+ description="""The entrypoint module to be used for the Agent Engine
+ This field only used when source_packages is specified.""",
+ )
+ entrypoint_object: Optional[str] = Field(
+ default=None,
+ description="""The entrypoint object to be used for the Agent Engine.
+ This field only used when source_packages is specified.""",
+ )
+ requirements_file: Optional[str] = Field(
+ default=None,
+ description="""The user-provided path to the requirements file (if any).
+ This field is only used when source_packages is specified.
+ If not specified, agent engine will find and use the `requirements.txt` in
+ the source package.
+ """,
+ )
+ agent_framework: Optional[
+ Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
+ ] = Field(
+ default=None,
+ description="""The agent framework to be used for the Agent Engine.
+ The OSS agent framework used to develop the agent.
+ Currently supported values: "google-adk", "langchain", "langgraph",
+ "ag2", "llama-index", "custom".
+ If not specified:
+ - If `agent` is specified, the agent framework will be auto-detected.
+ - If `source_packages` is specified, the agent framework will
+ default to "custom".""",
+ )
+ python_version: Optional[Literal["3.10", "3.11", "3.12", "3.13", "3.14"]] = Field(
+ default=None,
+ description="""The Python version to be used for the Agent Engine.
+ If not specified, it will use the current Python version of the environment.
+ Supported versions: "3.10", "3.11", "3.12", "3.13", "3.14".
+ """,
+ )
+ build_options: Optional[dict[str, list[str]]] = Field(
+ default=None,
+ description="""The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ """,
+ )
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfig
+ ] = Field(
+ default=None,
+ description="""Agent Gateway configuration for a Reasoning Engine deployment.""",
+ )
+ keep_alive_probe: Optional[KeepAliveProbe] = Field(
+ default=None,
+ description="""Optional. Specifies the configuration for keep-alive probe.
+ Contains configuration on a specified endpoint that a deployment host
+ should use to keep the container alive based on the probe settings.""",
+ )
+ update_mask: Optional[str] = Field(
+ default=None,
+ description="""The update mask to apply. For the `FieldMask` definition, see
+ https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask.""",
+ )
+ traffic_config: Optional[ReasoningEngineTrafficConfig] = Field(
+ default=None,
+ description="""Traffic distribution configuration for the Reasoning Engine.""",
+ )
+
+
+class UpdateAgentEngineConfigDict(TypedDict, total=False):
+ """Config for updating agent engine."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The user-defined name of the Agent Engine.
+
+ The display name can be up to 128 characters long and can comprise any
+ UTF-8 characters.
+ """
+
+ description: Optional[str]
+ """The description of the Agent Engine."""
+
+ spec: Optional[ReasoningEngineSpecDict]
+ """Optional. Configurations of the Agent Engine."""
+
+ context_spec: Optional[ReasoningEngineContextSpecDict]
+ """Optional. The context spec to be used for the Agent Engine."""
+
+ psc_interface_config: Optional[PscInterfaceConfigDict]
+ """Optional. The PSC interface config for PSC-I to be used for the
+ Agent Engine."""
+
+ min_instances: Optional[int]
+ """The minimum number of instances to run for the Agent Engine.
+ Defaults to 1. Range: [0, 10].
+ """
+
+ max_instances: Optional[int]
+ """The maximum number of instances to run for the Agent Engine.
+ Defaults to 100. Range: [1, 1000].
+ If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
+ """
+
+ resource_limits: Optional[dict[str, str]]
+ """The resource limits to be applied to the Agent Engine.
+ Required keys: 'cpu' and 'memory'.
+ Supported values for 'cpu': '1', '2', '4', '6', '8'.
+ Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
+ """
+
+ container_concurrency: Optional[int]
+ """The container concurrency to be used for the Agent Engine.
+ Recommended value: 2 * cpu + 1. Defaults to 9.
+ """
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """The encryption spec to be used for the Agent Engine."""
+
+ labels: Optional[dict[str, str]]
+ """The labels to be used for the Agent Engine."""
+
+ class_methods: Optional[list[dict[str, Any]]]
+ """The class methods to be used for the Agent Engine.
+ If specified, they'll override the class methods that are autogenerated by
+ default. By default, methods are generated by inspecting the agent object
+ and generating a corresponding method for each method defined on the
+ agent class.
+ """
+
+ source_packages: Optional[list[str]]
+ """The user-provided paths to the source packages (if any).
+ If specified, the files in the source packages will be packed into a
+ a tarball file, uploaded to Agent Engine's API, and deployed to the
+ Agent Engine.
+ The following fields will be ignored:
+ - agent
+ - extra_packages
+ - staging_bucket
+ - requirements
+ The following fields will be used to install and use the agent from the
+ source packages:
+ - entrypoint_module (required)
+ - entrypoint_object (required)
+ - requirements_file (optional)
+ - class_methods (required)
+ """
+
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
+ ]
+ """Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect. This includes the repository, revision, and directory to use."""
+
+ entrypoint_module: Optional[str]
+ """The entrypoint module to be used for the Agent Engine
+ This field only used when source_packages is specified."""
+
+ entrypoint_object: Optional[str]
+ """The entrypoint object to be used for the Agent Engine.
+ This field only used when source_packages is specified."""
+
+ requirements_file: Optional[str]
+ """The user-provided path to the requirements file (if any).
+ This field is only used when source_packages is specified.
+ If not specified, agent engine will find and use the `requirements.txt` in
+ the source package.
+ """
+
+ agent_framework: Optional[
+ Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
+ ]
+ """The agent framework to be used for the Agent Engine.
+ The OSS agent framework used to develop the agent.
+ Currently supported values: "google-adk", "langchain", "langgraph",
+ "ag2", "llama-index", "custom".
+ If not specified:
+ - If `agent` is specified, the agent framework will be auto-detected.
+ - If `source_packages` is specified, the agent framework will
+ default to "custom"."""
+
+ python_version: Optional[Literal["3.10", "3.11", "3.12", "3.13", "3.14"]]
+ """The Python version to be used for the Agent Engine.
+ If not specified, it will use the current Python version of the environment.
+ Supported versions: "3.10", "3.11", "3.12", "3.13", "3.14".
+ """
+
+ build_options: Optional[dict[str, list[str]]]
+ """The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ """
+
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
+ ]
+ """Agent Gateway configuration for a Reasoning Engine deployment."""
+
+ keep_alive_probe: Optional[KeepAliveProbeDict]
+ """Optional. Specifies the configuration for keep-alive probe.
+ Contains configuration on a specified endpoint that a deployment host
+ should use to keep the container alive based on the probe settings."""
+
+ update_mask: Optional[str]
+ """The update mask to apply. For the `FieldMask` definition, see
+ https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask."""
+
+ traffic_config: Optional[ReasoningEngineTrafficConfigDict]
+ """Traffic distribution configuration for the Reasoning Engine."""
+
+
+UpdateAgentEngineConfigOrDict = Union[
+ UpdateAgentEngineConfig, UpdateAgentEngineConfigDict
+]
+
+
+class _UpdateAgentEngineRequestParameters(_common.BaseModel):
+ """Parameters for updating agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[UpdateAgentEngineConfig] = Field(default=None, description="""""")
+
+
+class _UpdateAgentEngineRequestParametersDict(TypedDict, total=False):
+ """Parameters for updating agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[UpdateAgentEngineConfigDict]
+ """"""
+
+
+_UpdateAgentEngineRequestParametersOrDict = Union[
+ _UpdateAgentEngineRequestParameters, _UpdateAgentEngineRequestParametersDict
+]
+
+
+class MemoryMetadataValue(_common.BaseModel):
+ """The metadata values for memories."""
+
+ bool_value: Optional[bool] = Field(
+ default=None, description="""Represents a boolean value."""
+ )
+ double_value: Optional[float] = Field(
+ default=None, description="""Represents a double value."""
+ )
+ string_value: Optional[str] = Field(
+ default=None, description="""Represents a string value."""
+ )
+ timestamp_value: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Represents a timestamp value. When filtering on timestamp values, only the seconds field will be compared.""",
+ )
+
+
+class MemoryMetadataValueDict(TypedDict, total=False):
+ """The metadata values for memories."""
+
+ bool_value: Optional[bool]
+ """Represents a boolean value."""
+
+ double_value: Optional[float]
+ """Represents a double value."""
+
+ string_value: Optional[str]
+ """Represents a string value."""
+
+ timestamp_value: Optional[datetime.datetime]
+ """Represents a timestamp value. When filtering on timestamp values, only the seconds field will be compared."""
+
+
+MemoryMetadataValueOrDict = Union[MemoryMetadataValue, MemoryMetadataValueDict]
+
+
+class AgentEngineMemoryConfig(_common.BaseModel):
+ """Config for creating a Memory."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the memory."""
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the memory."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
+ )
+ revision_expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
+ )
+ revision_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL.""",
+ )
+ disable_memory_revisions: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Input only. If true, no revision will be created for this request.""",
+ )
+ topics: Optional[list[MemoryTopicId]] = Field(
+ default=None, description="""Optional. The topics of the memory."""
+ )
+ metadata: Optional[dict[str, MemoryMetadataValue]] = Field(
+ default=None,
+ description="""Optional. User-provided metadata for the Memory. This information was provided when creating, updating, or generating the Memory. It was not generated by Memory Bank.""",
+ )
+ memory_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. The user defined ID to use for memory, which will become the final component of the memory resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number.""",
+ )
+
+
+class AgentEngineMemoryConfigDict(TypedDict, total=False):
+ """Config for creating a Memory."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The display name of the memory."""
+
+ description: Optional[str]
+ """The description of the memory."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL."""
+
+ expire_time: Optional[datetime.datetime]
+ """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""
+
+ revision_expire_time: Optional[datetime.datetime]
+ """Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""
+
+ revision_ttl: Optional[str]
+ """Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL."""
+
+ disable_memory_revisions: Optional[bool]
+ """Optional. Input only. If true, no revision will be created for this request."""
+
+ topics: Optional[list[MemoryTopicIdDict]]
+ """Optional. The topics of the memory."""
+
+ metadata: Optional[dict[str, MemoryMetadataValueDict]]
+ """Optional. User-provided metadata for the Memory. This information was provided when creating, updating, or generating the Memory. It was not generated by Memory Bank."""
+
+ memory_id: Optional[str]
+ """Optional. The user defined ID to use for memory, which will become the final component of the memory resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number."""
+
+
+AgentEngineMemoryConfigOrDict = Union[
+ AgentEngineMemoryConfig, AgentEngineMemoryConfigDict
+]
+
+
+class _CreateAgentEngineMemoryRequestParameters(_common.BaseModel):
+ """Parameters for creating Agent Engine Memories."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to create the memory under.""",
+ )
+ fact: Optional[str] = Field(
+ default=None,
+ description="""The fact of the memory.
+
+ This is the semantic knowledge extracted from the source content).""",
+ )
+ scope: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The scope of the memory.
+
+ Memories are isolated within their scope. The scope is defined when
+ creating or generating memories. Up to 5 key-value pairs are accepted,
+ andscope values cannot contain the wildcard character '*'.""",
+ )
+ config: Optional[AgentEngineMemoryConfig] = Field(default=None, description="""""")
+
+
+class _CreateAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating Agent Engine Memories."""
+
+ name: Optional[str]
+ """Name of the agent engine to create the memory under."""
+
+ fact: Optional[str]
+ """The fact of the memory.
+
+ This is the semantic knowledge extracted from the source content)."""
+
+ scope: Optional[dict[str, str]]
+ """The scope of the memory.
+
+ Memories are isolated within their scope. The scope is defined when
+ creating or generating memories. Up to 5 key-value pairs are accepted,
+ andscope values cannot contain the wildcard character '*'."""
+
+ config: Optional[AgentEngineMemoryConfigDict]
+ """"""
+
+
+_CreateAgentEngineMemoryRequestParametersOrDict = Union[
+ _CreateAgentEngineMemoryRequestParameters,
+ _CreateAgentEngineMemoryRequestParametersDict,
+]
+
+
+class MemoryStructuredContent(_common.BaseModel):
+ """Represents the structured value of the memory."""
+
+ data: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Required. Represents the structured value of the memory.""",
+ )
+ schema_id: Optional[str] = Field(
+ default=None,
+ description="""Required. Represents the schema ID for which this structured memory belongs to.""",
+ )
+
+
+class MemoryStructuredContentDict(TypedDict, total=False):
+ """Represents the structured value of the memory."""
+
+ data: Optional[dict[str, Any]]
+ """Required. Represents the structured value of the memory."""
+
+ schema_id: Optional[str]
+ """Required. Represents the schema ID for which this structured memory belongs to."""
+
+
+MemoryStructuredContentOrDict = Union[
+ MemoryStructuredContent, MemoryStructuredContentDict
+]
+
+
+class Memory(_common.BaseModel):
+ """A memory."""
+
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Represents the timestamp when this Memory was created.""",
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="""Optional. Represents the description of the Memory.""",
+ )
+ disable_memory_revisions: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Input only. Indicates whether no revision will be created for this request.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Optional. Represents the display name of the Memory.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Represents the timestamp of when this resource is considered expired. This is *always* provided on output when `expiration` is set on input, regardless of whether `expire_time` or `ttl` was provided.""",
+ )
+ fact: Optional[str] = Field(
+ default=None,
+ description="""Optional. Represents semantic knowledge extracted from the source content.""",
+ )
+ metadata: Optional[dict[str, MemoryMetadataValue]] = Field(
+ default=None,
+ description="""Optional. Represents user-provided metadata for the Memory. This information was provided when creating, updating, or generating the Memory. It was not generated by Memory Bank.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. Represents the resource name of the Memory. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}`""",
+ )
+ revision_expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Input only. Represents the timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
+ )
+ revision_labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Optional. Input only. Represents the labels to apply to the Memory Revision created as a result of this request.""",
+ )
+ revision_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. Represents the TTL for the revision. The expiration time is computed: now + TTL.""",
+ )
+ scope: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Required. Immutable. Represents the scope of the Memory. Memories are isolated within their scope. The scope is defined when creating or generating memories. Scope values cannot contain the wildcard character '*'.""",
+ )
+ topics: Optional[list[MemoryTopicId]] = Field(
+ default=None, description="""Optional. Represents the Topics of the Memory."""
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. Represents the TTL for this resource. The expiration time is computed: now + TTL.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Represents the timestamp when this Memory was most recently updated.""",
+ )
+ memory_type: Optional[MemoryType] = Field(
+ default=None,
+ description="""Optional. Represents the type of the memory. If not set, the `NATURAL_LANGUAGE_COLLECTION` type is used. If `STRUCTURED_COLLECTION` or `STRUCTURED_PROFILE` is used, then `structured_data` must be provided.""",
+ )
+ structured_content: Optional[MemoryStructuredContent] = Field(
+ default=None,
+ description="""Optional. Represents the structured content of the memory.""",
+ )
+
+
+class MemoryDict(TypedDict, total=False):
+ """A memory."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Represents the timestamp when this Memory was created."""
+
+ description: Optional[str]
+ """Optional. Represents the description of the Memory."""
+
+ disable_memory_revisions: Optional[bool]
+ """Optional. Input only. Indicates whether no revision will be created for this request."""
+
+ display_name: Optional[str]
+ """Optional. Represents the display name of the Memory."""
+
+ expire_time: Optional[datetime.datetime]
+ """Optional. Represents the timestamp of when this resource is considered expired. This is *always* provided on output when `expiration` is set on input, regardless of whether `expire_time` or `ttl` was provided."""
+
+ fact: Optional[str]
+ """Optional. Represents semantic knowledge extracted from the source content."""
+
+ metadata: Optional[dict[str, MemoryMetadataValueDict]]
+ """Optional. Represents user-provided metadata for the Memory. This information was provided when creating, updating, or generating the Memory. It was not generated by Memory Bank."""
+
+ name: Optional[str]
+ """Identifier. Represents the resource name of the Memory. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}`"""
+
+ revision_expire_time: Optional[datetime.datetime]
+ """Optional. Input only. Represents the timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""
+
+ revision_labels: Optional[dict[str, str]]
+ """Optional. Input only. Represents the labels to apply to the Memory Revision created as a result of this request."""
+
+ revision_ttl: Optional[str]
+ """Optional. Input only. Represents the TTL for the revision. The expiration time is computed: now + TTL."""
+
+ scope: Optional[dict[str, str]]
+ """Required. Immutable. Represents the scope of the Memory. Memories are isolated within their scope. The scope is defined when creating or generating memories. Scope values cannot contain the wildcard character '*'."""
+
+ topics: Optional[list[MemoryTopicIdDict]]
+ """Optional. Represents the Topics of the Memory."""
+
+ ttl: Optional[str]
+ """Optional. Input only. Represents the TTL for this resource. The expiration time is computed: now + TTL."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Represents the timestamp when this Memory was most recently updated."""
+
+ memory_type: Optional[MemoryType]
+ """Optional. Represents the type of the memory. If not set, the `NATURAL_LANGUAGE_COLLECTION` type is used. If `STRUCTURED_COLLECTION` or `STRUCTURED_PROFILE` is used, then `structured_data` must be provided."""
+
+ structured_content: Optional[MemoryStructuredContentDict]
+ """Optional. Represents the structured content of the memory."""
+
+
+MemoryOrDict = Union[Memory, MemoryDict]
+
+
+class AgentEngineMemoryOperation(_common.BaseModel):
+ """Operation that has an agent engine memory as a response."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[Memory] = Field(
+ default=None, description="""The Agent Engine Memory."""
+ )
+
+
+class AgentEngineMemoryOperationDict(TypedDict, total=False):
+ """Operation that has an agent engine memory as a response."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[MemoryDict]
+ """The Agent Engine Memory."""
+
+
+AgentEngineMemoryOperationOrDict = Union[
+ AgentEngineMemoryOperation, AgentEngineMemoryOperationDict
+]
+
+
+class DeleteAgentEngineMemoryConfig(_common.BaseModel):
+ """Config for deleting an Agent Engine Memory."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteAgentEngineMemoryConfigDict(TypedDict, total=False):
+ """Config for deleting an Agent Engine Memory."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteAgentEngineMemoryConfigOrDict = Union[
+ DeleteAgentEngineMemoryConfig, DeleteAgentEngineMemoryConfigDict
+]
+
+
+class _DeleteAgentEngineMemoryRequestParameters(_common.BaseModel):
+ """Parameters for deleting agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine memory to delete."""
+ )
+ config: Optional[DeleteAgentEngineMemoryConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine memory to delete."""
+
+ config: Optional[DeleteAgentEngineMemoryConfigDict]
+ """"""
+
+
+_DeleteAgentEngineMemoryRequestParametersOrDict = Union[
+ _DeleteAgentEngineMemoryRequestParameters,
+ _DeleteAgentEngineMemoryRequestParametersDict,
+]
+
+
+class DeleteAgentEngineMemoryOperation(_common.BaseModel):
+ """Operation for deleting agent engines."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteAgentEngineMemoryOperationDict(TypedDict, total=False):
+ """Operation for deleting agent engines."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteAgentEngineMemoryOperationOrDict = Union[
+ DeleteAgentEngineMemoryOperation, DeleteAgentEngineMemoryOperationDict
+]
+
+
+class GenerateMemoriesRequestVertexSessionSource(_common.BaseModel):
+ """The vertex session source for generating memories."""
+
+ end_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. End time (exclusive) of the time range. If not set, the end time is unbounded.""",
+ )
+ session: Optional[str] = Field(
+ default=None,
+ description="""Required. The resource name of the Session to generate memories for. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}`""",
+ )
+ start_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Time range to define which session events should be used to generate memories. Start time (inclusive) of the time range. If not set, the start time is unbounded.""",
+ )
+
+
+class GenerateMemoriesRequestVertexSessionSourceDict(TypedDict, total=False):
+ """The vertex session source for generating memories."""
+
+ end_time: Optional[datetime.datetime]
+ """Optional. End time (exclusive) of the time range. If not set, the end time is unbounded."""
+
+ session: Optional[str]
+ """Required. The resource name of the Session to generate memories for. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}`"""
+
+ start_time: Optional[datetime.datetime]
+ """Optional. Time range to define which session events should be used to generate memories. Start time (inclusive) of the time range. If not set, the start time is unbounded."""
+
+
+GenerateMemoriesRequestVertexSessionSourceOrDict = Union[
+ GenerateMemoriesRequestVertexSessionSource,
+ GenerateMemoriesRequestVertexSessionSourceDict,
+]
+
+
+class GenerateMemoriesRequestDirectContentsSourceEvent(_common.BaseModel):
+
+ content: Optional[genai_types.Content] = Field(
+ default=None,
+ description="""Required. A single piece of content from which to generate memories.""",
+ )
+
+
+class GenerateMemoriesRequestDirectContentsSourceEventDict(TypedDict, total=False):
+
+ content: Optional[genai_types.ContentDict]
+ """Required. A single piece of content from which to generate memories."""
+
+
+GenerateMemoriesRequestDirectContentsSourceEventOrDict = Union[
+ GenerateMemoriesRequestDirectContentsSourceEvent,
+ GenerateMemoriesRequestDirectContentsSourceEventDict,
+]
+
+
+class GenerateMemoriesRequestDirectContentsSource(_common.BaseModel):
+ """The direct contents source for generating memories."""
+
+ events: Optional[list[GenerateMemoriesRequestDirectContentsSourceEvent]] = Field(
+ default=None,
+ description="""Required. The source content (i.e. chat history) to generate memories from.""",
+ )
+
+
+class GenerateMemoriesRequestDirectContentsSourceDict(TypedDict, total=False):
+ """The direct contents source for generating memories."""
+
+ events: Optional[list[GenerateMemoriesRequestDirectContentsSourceEventDict]]
+ """Required. The source content (i.e. chat history) to generate memories from."""
+
+
+GenerateMemoriesRequestDirectContentsSourceOrDict = Union[
+ GenerateMemoriesRequestDirectContentsSource,
+ GenerateMemoriesRequestDirectContentsSourceDict,
+]
+
+
+class GenerateMemoriesRequestDirectMemoriesSourceDirectMemory(_common.BaseModel):
+ """A direct memory to upload to Memory Bank."""
+
+ fact: Optional[str] = Field(
+ default=None,
+ description="""Required. The fact to consolidate with existing memories.""",
+ )
+ topics: Optional[list[MemoryTopicId]] = Field(
+ default=None,
+ description="""Optional. The topics that the consolidated memories should be associated with.""",
+ )
+
+
+class GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict(
+ TypedDict, total=False
+):
+ """A direct memory to upload to Memory Bank."""
+
+ fact: Optional[str]
+ """Required. The fact to consolidate with existing memories."""
+
+ topics: Optional[list[MemoryTopicIdDict]]
+ """Optional. The topics that the consolidated memories should be associated with."""
+
+
+GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryOrDict = Union[
+ GenerateMemoriesRequestDirectMemoriesSourceDirectMemory,
+ GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict,
+]
+
+
+class GenerateMemoriesRequestDirectMemoriesSource(_common.BaseModel):
+ """The direct memories source for generating memories."""
+
+ direct_memories: Optional[
+ list[GenerateMemoriesRequestDirectMemoriesSourceDirectMemory]
+ ] = Field(
+ default=None,
+ description="""Required. The direct memories to upload to Memory Bank. At most 5 direct memories are allowed per request.""",
+ )
+
+
+class GenerateMemoriesRequestDirectMemoriesSourceDict(TypedDict, total=False):
+ """The direct memories source for generating memories."""
+
+ direct_memories: Optional[
+ list[GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict]
+ ]
+ """Required. The direct memories to upload to Memory Bank. At most 5 direct memories are allowed per request."""
+
+
+GenerateMemoriesRequestDirectMemoriesSourceOrDict = Union[
+ GenerateMemoriesRequestDirectMemoriesSource,
+ GenerateMemoriesRequestDirectMemoriesSourceDict,
+]
+
+
+class GenerateAgentEngineMemoriesConfig(_common.BaseModel):
+ """Config for generating memories."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ disable_consolidation: Optional[bool] = Field(
+ default=None,
+ description="""Whether to disable consolidation of memories.
+
+ If true, generated memories will not be consolidated with existing
+ memories; all generated memories will be added as new memories regardless
+ of whether they are duplicates of or contradictory to existing memories.
+ By default, memory consolidation is enabled.""",
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+ revision_labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Labels to apply to the memory revision. For example, you can use this to label a revision with its data source.""",
+ )
+ revision_expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
+ )
+ revision_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL.""",
+ )
+ disable_memory_revisions: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Input only. If true, no revisions will be created for this request.""",
+ )
+ metadata: Optional[dict[str, MemoryMetadataValue]] = Field(
+ default=None,
+ description="""Optional. User-provided metadata for the generated memories. This is not generated by Memory Bank.""",
+ )
+ metadata_merge_strategy: Optional[MemoryMetadataMergeStrategy] = Field(
+ default=None,
+ description="""Optional. The strategy to use when applying metadata to existing memories.""",
+ )
+ allowed_topics: Optional[list[MemoryTopicId]] = Field(
+ default=None,
+ description="""Optional. Restricts memory generation to a subset of memory topics.""",
+ )
+
+
+class GenerateAgentEngineMemoriesConfigDict(TypedDict, total=False):
+ """Config for generating memories."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ disable_consolidation: Optional[bool]
+ """Whether to disable consolidation of memories.
+
+ If true, generated memories will not be consolidated with existing
+ memories; all generated memories will be added as new memories regardless
+ of whether they are duplicates of or contradictory to existing memories.
+ By default, memory consolidation is enabled."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+ revision_labels: Optional[dict[str, str]]
+ """Labels to apply to the memory revision. For example, you can use this to label a revision with its data source."""
+
+ revision_expire_time: Optional[datetime.datetime]
+ """Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""
+
+ revision_ttl: Optional[str]
+ """Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL."""
+
+ disable_memory_revisions: Optional[bool]
+ """Optional. Input only. If true, no revisions will be created for this request."""
+
+ metadata: Optional[dict[str, MemoryMetadataValueDict]]
+ """Optional. User-provided metadata for the generated memories. This is not generated by Memory Bank."""
+
+ metadata_merge_strategy: Optional[MemoryMetadataMergeStrategy]
+ """Optional. The strategy to use when applying metadata to existing memories."""
+
+ allowed_topics: Optional[list[MemoryTopicIdDict]]
+ """Optional. Restricts memory generation to a subset of memory topics."""
+
+
+GenerateAgentEngineMemoriesConfigOrDict = Union[
+ GenerateAgentEngineMemoriesConfig, GenerateAgentEngineMemoriesConfigDict
+]
+
+
+class _GenerateAgentEngineMemoriesRequestParameters(_common.BaseModel):
+ """Parameters for generating agent engine memories."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to generate memories for.""",
+ )
+ vertex_session_source: Optional[GenerateMemoriesRequestVertexSessionSource] = Field(
+ default=None,
+ description="""The vertex session source of the memories that should be generated.""",
+ )
+ direct_contents_source: Optional[GenerateMemoriesRequestDirectContentsSource] = (
+ Field(
+ default=None,
+ description="""The direct contents source of the memories that should be generated.""",
+ )
+ )
+ direct_memories_source: Optional[GenerateMemoriesRequestDirectMemoriesSource] = (
+ Field(
+ default=None,
+ description="""The direct memories source of the memories that should be generated.""",
+ )
+ )
+ scope: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The scope of the memories that should be generated.
+
+ Memories will be consolidated across memories with the same scope. Must be
+ provided unless the scope is defined in the source content. If `scope` is
+ provided, it will override the scope defined in the source content. Scope
+ values cannot contain the wildcard character '*'.""",
+ )
+ config: Optional[GenerateAgentEngineMemoriesConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GenerateAgentEngineMemoriesRequestParametersDict(TypedDict, total=False):
+ """Parameters for generating agent engine memories."""
+
+ name: Optional[str]
+ """Name of the agent engine to generate memories for."""
+
+ vertex_session_source: Optional[GenerateMemoriesRequestVertexSessionSourceDict]
+ """The vertex session source of the memories that should be generated."""
+
+ direct_contents_source: Optional[GenerateMemoriesRequestDirectContentsSourceDict]
+ """The direct contents source of the memories that should be generated."""
+
+ direct_memories_source: Optional[GenerateMemoriesRequestDirectMemoriesSourceDict]
+ """The direct memories source of the memories that should be generated."""
+
+ scope: Optional[dict[str, str]]
+ """The scope of the memories that should be generated.
+
+ Memories will be consolidated across memories with the same scope. Must be
+ provided unless the scope is defined in the source content. If `scope` is
+ provided, it will override the scope defined in the source content. Scope
+ values cannot contain the wildcard character '*'."""
+
+ config: Optional[GenerateAgentEngineMemoriesConfigDict]
+ """"""
+
+
+_GenerateAgentEngineMemoriesRequestParametersOrDict = Union[
+ _GenerateAgentEngineMemoriesRequestParameters,
+ _GenerateAgentEngineMemoriesRequestParametersDict,
+]
+
+
+class GenerateMemoriesResponseGeneratedMemory(_common.BaseModel):
+ """A memory that was generated."""
+
+ memory: Optional[Memory] = Field(
+ default=None, description="""The generated memory."""
+ )
+ action: Optional[GenerateMemoriesResponseGeneratedMemoryAction] = Field(
+ default=None, description="""The action to take."""
+ )
+ previous_revision: Optional[str] = Field(
+ default=None,
+ description="""The previous revision of the Memory before the action was performed. This
+ field is only set if the action is `UPDATED` or `DELETED`. You can use
+ this to rollback the Memory to the previous revision, undoing the action.
+ Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{revision}`""",
+ )
+
+
+class GenerateMemoriesResponseGeneratedMemoryDict(TypedDict, total=False):
+ """A memory that was generated."""
+
+ memory: Optional[MemoryDict]
+ """The generated memory."""
+
+ action: Optional[GenerateMemoriesResponseGeneratedMemoryAction]
+ """The action to take."""
+
+ previous_revision: Optional[str]
+ """The previous revision of the Memory before the action was performed. This
+ field is only set if the action is `UPDATED` or `DELETED`. You can use
+ this to rollback the Memory to the previous revision, undoing the action.
+ Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{revision}`"""
+
+
+GenerateMemoriesResponseGeneratedMemoryOrDict = Union[
+ GenerateMemoriesResponseGeneratedMemory, GenerateMemoriesResponseGeneratedMemoryDict
+]
+
+
+class GenerateMemoriesResponse(_common.BaseModel):
+ """The response for generating memories."""
+
+ generated_memories: Optional[list[GenerateMemoriesResponseGeneratedMemory]] = Field(
+ default=None, description="""The generated memories."""
+ )
+
+
+class GenerateMemoriesResponseDict(TypedDict, total=False):
+ """The response for generating memories."""
+
+ generated_memories: Optional[list[GenerateMemoriesResponseGeneratedMemoryDict]]
+ """The generated memories."""
+
+
+GenerateMemoriesResponseOrDict = Union[
+ GenerateMemoriesResponse, GenerateMemoriesResponseDict
+]
+
+
+class AgentEngineGenerateMemoriesOperation(_common.BaseModel):
+ """Operation that generates memories for an agent engine."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[GenerateMemoriesResponse] = Field(
+ default=None, description="""The response for generating memories."""
+ )
+
+
+class AgentEngineGenerateMemoriesOperationDict(TypedDict, total=False):
+ """Operation that generates memories for an agent engine."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[GenerateMemoriesResponseDict]
+ """The response for generating memories."""
+
+
+AgentEngineGenerateMemoriesOperationOrDict = Union[
+ AgentEngineGenerateMemoriesOperation, AgentEngineGenerateMemoriesOperationDict
+]
+
+
+class GetAgentEngineMemoryConfig(_common.BaseModel):
+ """Config for getting an Agent Engine Memory."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineMemoryConfigDict(TypedDict, total=False):
+ """Config for getting an Agent Engine Memory."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineMemoryConfigOrDict = Union[
+ GetAgentEngineMemoryConfig, GetAgentEngineMemoryConfigDict
+]
+
+
+class _GetAgentEngineMemoryRequestParameters(_common.BaseModel):
+ """Parameters for getting an agent engine."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[GetAgentEngineMemoryConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting an agent engine."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[GetAgentEngineMemoryConfigDict]
+ """"""
+
+
+_GetAgentEngineMemoryRequestParametersOrDict = Union[
+ _GetAgentEngineMemoryRequestParameters, _GetAgentEngineMemoryRequestParametersDict
+]
+
+
+class IngestionDirectContentsSourceEvent(_common.BaseModel):
+ """The direct contents source event for ingesting events."""
+
+ content: Optional[genai_types.Content] = Field(
+ default=None, description="""Required. The content of the event."""
+ )
+ event_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. A unique identifier for the event. If an event with the same event_id is ingested multiple times, it will be de-duplicated.""",
+ )
+ event_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. The time at which the event occurred. If provided, this timestamp will be used for ordering events within a stream. If not provided, the server-side ingestion time will be used.""",
+ )
+
+
+class IngestionDirectContentsSourceEventDict(TypedDict, total=False):
+ """The direct contents source event for ingesting events."""
+
+ content: Optional[genai_types.ContentDict]
+ """Required. The content of the event."""
+
+ event_id: Optional[str]
+ """Optional. A unique identifier for the event. If an event with the same event_id is ingested multiple times, it will be de-duplicated."""
+
+ event_time: Optional[datetime.datetime]
+ """Optional. The time at which the event occurred. If provided, this timestamp will be used for ordering events within a stream. If not provided, the server-side ingestion time will be used."""
+
+
+IngestionDirectContentsSourceEventOrDict = Union[
+ IngestionDirectContentsSourceEvent, IngestionDirectContentsSourceEventDict
+]
+
+
+class IngestionDirectContentsSource(_common.BaseModel):
+ """The direct contents source for ingesting events."""
+
+ events: Optional[list[IngestionDirectContentsSourceEvent]] = Field(
+ default=None, description="""Required. The events to ingest."""
+ )
+
+
+class IngestionDirectContentsSourceDict(TypedDict, total=False):
+ """The direct contents source for ingesting events."""
+
+ events: Optional[list[IngestionDirectContentsSourceEventDict]]
+ """Required. The events to ingest."""
+
+
+IngestionDirectContentsSourceOrDict = Union[
+ IngestionDirectContentsSource, IngestionDirectContentsSourceDict
+]
+
+
+class IngestEventsConfig(_common.BaseModel):
+ """Config for ingesting events."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=False,
+ description="""Waits for the underlying memory generation operation to complete
+ before returning. Defaults to false.""",
+ )
+ force_flush: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Forces a flush of all pending events in the stream and triggers memory generation immediately bypassing any conditions configured in the `generation_trigger_config`.""",
+ )
+
+
+class IngestEventsConfigDict(TypedDict, total=False):
+ """Config for ingesting events."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the underlying memory generation operation to complete
+ before returning. Defaults to false."""
+
+ force_flush: Optional[bool]
+ """Optional. Forces a flush of all pending events in the stream and triggers memory generation immediately bypassing any conditions configured in the `generation_trigger_config`."""
+
+
+IngestEventsConfigOrDict = Union[IngestEventsConfig, IngestEventsConfigDict]
+
+
+class _IngestEventsRequestParameters(_common.BaseModel):
+ """Parameters for purging agent engine memories."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the Agent Engine to ingest events into."""
+ )
+ stream_id: Optional[str] = Field(
+ default=None, description="""The ID of the stream to ingest events into."""
+ )
+ direct_contents_source: Optional[IngestionDirectContentsSource] = Field(
+ default=None,
+ description="""The direct memories source of the events that should be ingested.""",
+ )
+ scope: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The scope of the memories that should be generated from the stream.
+
+ Memories will be consolidated across memories with the same scope. Scope
+ values cannot contain the wildcard character '*'.""",
+ )
+ generation_trigger_config: Optional[MemoryGenerationTriggerConfig] = Field(
+ default=None,
+ description="""The configuration for the memory generation trigger.""",
+ )
+ config: Optional[IngestEventsConfig] = Field(default=None, description="""""")
+
+
+class _IngestEventsRequestParametersDict(TypedDict, total=False):
+ """Parameters for purging agent engine memories."""
+
+ name: Optional[str]
+ """Name of the Agent Engine to ingest events into."""
+
+ stream_id: Optional[str]
+ """The ID of the stream to ingest events into."""
+
+ direct_contents_source: Optional[IngestionDirectContentsSourceDict]
+ """The direct memories source of the events that should be ingested."""
+
+ scope: Optional[dict[str, str]]
+ """The scope of the memories that should be generated from the stream.
+
+ Memories will be consolidated across memories with the same scope. Scope
+ values cannot contain the wildcard character '*'."""
+
+ generation_trigger_config: Optional[MemoryGenerationTriggerConfigDict]
+ """The configuration for the memory generation trigger."""
+
+ config: Optional[IngestEventsConfigDict]
+ """"""
+
+
+_IngestEventsRequestParametersOrDict = Union[
+ _IngestEventsRequestParameters, _IngestEventsRequestParametersDict
+]
+
+
+class MemoryBankIngestEventsOperation(_common.BaseModel):
+ """Operation that ingests events into a memory bank."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class MemoryBankIngestEventsOperationDict(TypedDict, total=False):
+ """Operation that ingests events into a memory bank."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+MemoryBankIngestEventsOperationOrDict = Union[
+ MemoryBankIngestEventsOperation, MemoryBankIngestEventsOperationDict
+]
+
+
+class ListAgentEngineMemoryConfig(_common.BaseModel):
+ """Config for listing agent engine memories."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+ order_by: Optional[str] = Field(
+ default=None,
+ description="""The standard list order by string. If not specified, the default
+ order is `create_time desc`. If specified, the default sorting order of
+ provided fields is ascending. More detail in
+ [AIP-132](https://google.aip.dev/132).
+
+ Supported fields:
+ * `create_time`
+ * `update_time`""",
+ )
+
+
+class ListAgentEngineMemoryConfigDict(TypedDict, total=False):
+ """Config for listing agent engine memories."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+ order_by: Optional[str]
+ """The standard list order by string. If not specified, the default
+ order is `create_time desc`. If specified, the default sorting order of
+ provided fields is ascending. More detail in
+ [AIP-132](https://google.aip.dev/132).
+
+ Supported fields:
+ * `create_time`
+ * `update_time`"""
+
+
+ListAgentEngineMemoryConfigOrDict = Union[
+ ListAgentEngineMemoryConfig, ListAgentEngineMemoryConfigDict
+]
+
+
+class _ListAgentEngineMemoryRequestParameters(_common.BaseModel):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[ListAgentEngineMemoryConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[ListAgentEngineMemoryConfigDict]
+ """"""
+
+
+_ListAgentEngineMemoryRequestParametersOrDict = Union[
+ _ListAgentEngineMemoryRequestParameters, _ListAgentEngineMemoryRequestParametersDict
+]
+
+
+class ListReasoningEnginesMemoriesResponse(_common.BaseModel):
+ """Response for listing agent engine memories."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ memories: Optional[list[Memory]] = Field(
+ default=None, description="""List of agent engine memories."""
+ )
+
+
+class ListReasoningEnginesMemoriesResponseDict(TypedDict, total=False):
+ """Response for listing agent engine memories."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ memories: Optional[list[MemoryDict]]
+ """List of agent engine memories."""
+
+
+ListReasoningEnginesMemoriesResponseOrDict = Union[
+ ListReasoningEnginesMemoriesResponse, ListReasoningEnginesMemoriesResponseDict
+]
+
+
+class _GetAgentEngineMemoryOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation with a memory as a response."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetAgentEngineOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetAgentEngineMemoryOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation with a memory as a response."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetAgentEngineOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetAgentEngineMemoryOperationParametersOrDict = Union[
+ _GetAgentEngineMemoryOperationParameters,
+ _GetAgentEngineMemoryOperationParametersDict,
+]
+
+
+class _GetAgentEngineGenerateMemoriesOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation with generated memories as a response."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetAgentEngineOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetAgentEngineGenerateMemoriesOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation with generated memories as a response."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetAgentEngineOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetAgentEngineGenerateMemoriesOperationParametersOrDict = Union[
+ _GetAgentEngineGenerateMemoriesOperationParameters,
+ _GetAgentEngineGenerateMemoriesOperationParametersDict,
+]
+
+
+class RetrieveMemoriesRequestSimilaritySearchParams(_common.BaseModel):
+ """The parameters for semantic similarity search based retrieval."""
+
+ search_query: Optional[str] = Field(
+ default=None,
+ description="""Required. Query to use for similarity search retrieval. If provided, then the parent ReasoningEngine must have ReasoningEngineContextSpec.MemoryBankConfig.SimilaritySearchConfig set.""",
+ )
+ top_k: Optional[int] = Field(
+ default=None,
+ description="""Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100.""",
+ )
+
+
+class RetrieveMemoriesRequestSimilaritySearchParamsDict(TypedDict, total=False):
+ """The parameters for semantic similarity search based retrieval."""
+
+ search_query: Optional[str]
+ """Required. Query to use for similarity search retrieval. If provided, then the parent ReasoningEngine must have ReasoningEngineContextSpec.MemoryBankConfig.SimilaritySearchConfig set."""
+
+ top_k: Optional[int]
+ """Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100."""
+
+
+RetrieveMemoriesRequestSimilaritySearchParamsOrDict = Union[
+ RetrieveMemoriesRequestSimilaritySearchParams,
+ RetrieveMemoriesRequestSimilaritySearchParamsDict,
+]
+
+
+class RetrieveMemoriesRequestSimpleRetrievalParams(_common.BaseModel):
+ """The parameters for simple (non-similarity search) retrieval."""
+
+ page_size: Optional[int] = Field(
+ default=None,
+ description="""Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100.""",
+ )
+ page_token: Optional[str] = Field(
+ default=None,
+ description="""Optional. A page token, received from a previous `RetrieveMemories` call. Provide this to retrieve the subsequent page.""",
+ )
+
+
+class RetrieveMemoriesRequestSimpleRetrievalParamsDict(TypedDict, total=False):
+ """The parameters for simple (non-similarity search) retrieval."""
+
+ page_size: Optional[int]
+ """Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100."""
+
+ page_token: Optional[str]
+ """Optional. A page token, received from a previous `RetrieveMemories` call. Provide this to retrieve the subsequent page."""
+
+
+RetrieveMemoriesRequestSimpleRetrievalParamsOrDict = Union[
+ RetrieveMemoriesRequestSimpleRetrievalParams,
+ RetrieveMemoriesRequestSimpleRetrievalParamsDict,
+]
+
+
+class MemoryFilter(_common.BaseModel):
+ """Filter to apply when retrieving memories."""
+
+ key: Optional[str] = Field(
+ default=None,
+ description="""Represents the key of the filter. For example, "author" would apply to `metadata` entries with the key "author".""",
+ )
+ negate: Optional[bool] = Field(
+ default=None, description="""Indicates whether the filter will be negated."""
+ )
+ op: Optional[Operator] = Field(
+ default=None,
+ description="""Represents the operator to apply to the filter. If not set, then EQUAL will be used.""",
+ )
+ value: Optional[MemoryMetadataValue] = Field(
+ default=None, description="""Represents the value to compare to."""
+ )
+
+
+class MemoryFilterDict(TypedDict, total=False):
+ """Filter to apply when retrieving memories."""
+
+ key: Optional[str]
+ """Represents the key of the filter. For example, "author" would apply to `metadata` entries with the key "author"."""
+
+ negate: Optional[bool]
+ """Indicates whether the filter will be negated."""
+
+ op: Optional[Operator]
+ """Represents the operator to apply to the filter. If not set, then EQUAL will be used."""
+
+ value: Optional[MemoryMetadataValueDict]
+ """Represents the value to compare to."""
+
+
+MemoryFilterOrDict = Union[MemoryFilter, MemoryFilterDict]
+
+
+class MemoryConjunctionFilter(_common.BaseModel):
+ """The conjunction filter for memories."""
+
+ filters: Optional[list[MemoryFilter]] = Field(
+ default=None,
+ description="""Represents filters that will be combined using AND logic.""",
+ )
+
+
+class MemoryConjunctionFilterDict(TypedDict, total=False):
+ """The conjunction filter for memories."""
+
+ filters: Optional[list[MemoryFilterDict]]
+ """Represents filters that will be combined using AND logic."""
+
+
+MemoryConjunctionFilterOrDict = Union[
+ MemoryConjunctionFilter, MemoryConjunctionFilterDict
+]
+
+
+class RetrieveAgentEngineMemoriesConfig(_common.BaseModel):
+ """Config for retrieving memories."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ filter: Optional[str] = Field(
+ default=None,
+ description="""The standard list filter that will be applied to the retrieved
+ memories. More detail in [AIP-160](https://google.aip.dev/160).
+
+ Supported fields:
+ * `fact`
+ * `create_time`
+ * `update_time`
+ """,
+ )
+ filter_groups: Optional[list[MemoryConjunctionFilter]] = Field(
+ default=None,
+ description="""Metadata filters that will be applied to the retrieved memories'
+ `metadata` using OR logic. Filters are defined using disjunctive normal
+ form (OR of ANDs).
+
+ For example:
+ `filter_groups: [{filters: [{key: "author", value: {string_value: "agent
+ `123"}, op: EQUAL}]}, {filters: [{key: "label", value: {string_value:
+ "travel"}, op: EQUAL}, {key: "author", value: {string_value: "agent 321"},
+ op: EQUAL}]}]`
+
+ would be equivalent to the logical expression:
+ `(metadata.author = "agent 123" OR (metadata.label = "travel" AND
+ metadata.author = "agent 321"))`.
+ """,
+ )
+ memory_types: Optional[list[MemoryType]] = Field(
+ default=None,
+ description="""Specifies the types of memories to retrieve. If this field is empty
+ or not provided, the request will default to retrieving only memories of
+ type `NATURAL_LANGUAGE_COLLECTION`. If populated, the request will
+ retrieve memories matching any of the specified `MemoryType` values.""",
+ )
+
+
+class RetrieveAgentEngineMemoriesConfigDict(TypedDict, total=False):
+ """Config for retrieving memories."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ filter: Optional[str]
+ """The standard list filter that will be applied to the retrieved
+ memories. More detail in [AIP-160](https://google.aip.dev/160).
+
+ Supported fields:
+ * `fact`
+ * `create_time`
+ * `update_time`
+ """
+
+ filter_groups: Optional[list[MemoryConjunctionFilterDict]]
+ """Metadata filters that will be applied to the retrieved memories'
+ `metadata` using OR logic. Filters are defined using disjunctive normal
+ form (OR of ANDs).
+
+ For example:
+ `filter_groups: [{filters: [{key: "author", value: {string_value: "agent
+ `123"}, op: EQUAL}]}, {filters: [{key: "label", value: {string_value:
+ "travel"}, op: EQUAL}, {key: "author", value: {string_value: "agent 321"},
+ op: EQUAL}]}]`
+
+ would be equivalent to the logical expression:
+ `(metadata.author = "agent 123" OR (metadata.label = "travel" AND
+ metadata.author = "agent 321"))`.
+ """
+
+ memory_types: Optional[list[MemoryType]]
+ """Specifies the types of memories to retrieve. If this field is empty
+ or not provided, the request will default to retrieving only memories of
+ type `NATURAL_LANGUAGE_COLLECTION`. If populated, the request will
+ retrieve memories matching any of the specified `MemoryType` values."""
+
+
+RetrieveAgentEngineMemoriesConfigOrDict = Union[
+ RetrieveAgentEngineMemoriesConfig, RetrieveAgentEngineMemoriesConfigDict
+]
+
+
+class _RetrieveAgentEngineMemoriesRequestParameters(_common.BaseModel):
+ """Parameters for retrieving agent engine memories."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to retrieve memories from.""",
+ )
+ scope: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The scope of the memories to retrieve.
+
+ A memory must have exactly the same scope as the scope provided here to be
+ retrieved (i.e. same keys and values). Order does not matter, but it is
+ case-sensitive.""",
+ )
+ similarity_search_params: Optional[
+ RetrieveMemoriesRequestSimilaritySearchParams
+ ] = Field(
+ default=None,
+ description="""Parameters for semantic similarity search based retrieval.""",
+ )
+ simple_retrieval_params: Optional[RetrieveMemoriesRequestSimpleRetrievalParams] = (
+ Field(
+ default=None,
+ description="""Parameters for simple (non-similarity search) retrieval.""",
+ )
+ )
+ config: Optional[RetrieveAgentEngineMemoriesConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _RetrieveAgentEngineMemoriesRequestParametersDict(TypedDict, total=False):
+ """Parameters for retrieving agent engine memories."""
+
+ name: Optional[str]
+ """Name of the agent engine to retrieve memories from."""
+
+ scope: Optional[dict[str, str]]
+ """The scope of the memories to retrieve.
+
+ A memory must have exactly the same scope as the scope provided here to be
+ retrieved (i.e. same keys and values). Order does not matter, but it is
+ case-sensitive."""
+
+ similarity_search_params: Optional[
+ RetrieveMemoriesRequestSimilaritySearchParamsDict
+ ]
+ """Parameters for semantic similarity search based retrieval."""
+
+ simple_retrieval_params: Optional[RetrieveMemoriesRequestSimpleRetrievalParamsDict]
+ """Parameters for simple (non-similarity search) retrieval."""
+
+ config: Optional[RetrieveAgentEngineMemoriesConfigDict]
+ """"""
+
+
+_RetrieveAgentEngineMemoriesRequestParametersOrDict = Union[
+ _RetrieveAgentEngineMemoriesRequestParameters,
+ _RetrieveAgentEngineMemoriesRequestParametersDict,
+]
+
+
+class RetrieveMemoriesResponseRetrievedMemory(_common.BaseModel):
+ """A retrieved memory."""
+
+ distance: Optional[float] = Field(
+ default=None,
+ description="""The distance between the query and the retrieved Memory. Smaller values indicate more similar memories. This is only set if similarity search was used for retrieval.""",
+ )
+ memory: Optional[Memory] = Field(
+ default=None, description="""The retrieved Memory."""
+ )
+
+
+class RetrieveMemoriesResponseRetrievedMemoryDict(TypedDict, total=False):
+ """A retrieved memory."""
+
+ distance: Optional[float]
+ """The distance between the query and the retrieved Memory. Smaller values indicate more similar memories. This is only set if similarity search was used for retrieval."""
+
+ memory: Optional[MemoryDict]
+ """The retrieved Memory."""
+
+
+RetrieveMemoriesResponseRetrievedMemoryOrDict = Union[
+ RetrieveMemoriesResponseRetrievedMemory, RetrieveMemoriesResponseRetrievedMemoryDict
+]
+
+
+class RetrieveMemoriesResponse(_common.BaseModel):
+ """The response for retrieving memories."""
+
+ next_page_token: Optional[str] = Field(
+ default=None,
+ description="""A token that can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages. This token is not set if similarity search was used for retrieval.""",
+ )
+ retrieved_memories: Optional[list[RetrieveMemoriesResponseRetrievedMemory]] = Field(
+ default=None, description="""The retrieved memories."""
+ )
+
+
+class RetrieveMemoriesResponseDict(TypedDict, total=False):
+ """The response for retrieving memories."""
+
+ next_page_token: Optional[str]
+ """A token that can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages. This token is not set if similarity search was used for retrieval."""
+
+ retrieved_memories: Optional[list[RetrieveMemoriesResponseRetrievedMemoryDict]]
+ """The retrieved memories."""
+
+
+RetrieveMemoriesResponseOrDict = Union[
+ RetrieveMemoriesResponse, RetrieveMemoriesResponseDict
+]
+
+
+class RetrieveMemoryProfilesConfig(_common.BaseModel):
+ """Config for retrieving memory profiles."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class RetrieveMemoryProfilesConfigDict(TypedDict, total=False):
+ """Config for retrieving memory profiles."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+RetrieveMemoryProfilesConfigOrDict = Union[
+ RetrieveMemoryProfilesConfig, RetrieveMemoryProfilesConfigDict
+]
+
+
+class _RetrieveMemoryProfilesRequestParameters(_common.BaseModel):
+ """Parameters for retrieving agent engine memory profiles."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to retrieve memory profiles from.""",
+ )
+ scope: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The scope of the memories to retrieve.
+
+ A memory must have exactly the same scope as the scope provided here to be
+ retrieved (i.e. same keys and values). Order does not matter, but it is
+ case-sensitive.""",
+ )
+ config: Optional[RetrieveMemoryProfilesConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _RetrieveMemoryProfilesRequestParametersDict(TypedDict, total=False):
+ """Parameters for retrieving agent engine memory profiles."""
+
+ name: Optional[str]
+ """Name of the agent engine to retrieve memory profiles from."""
+
+ scope: Optional[dict[str, str]]
+ """The scope of the memories to retrieve.
+
+ A memory must have exactly the same scope as the scope provided here to be
+ retrieved (i.e. same keys and values). Order does not matter, but it is
+ case-sensitive."""
+
+ config: Optional[RetrieveMemoryProfilesConfigDict]
+ """"""
+
+
+_RetrieveMemoryProfilesRequestParametersOrDict = Union[
+ _RetrieveMemoryProfilesRequestParameters,
+ _RetrieveMemoryProfilesRequestParametersDict,
+]
+
+
+class MemoryProfile(_common.BaseModel):
+ """A memory profile."""
+
+ schema_id: Optional[str] = Field(
+ default=None,
+ description="""Represents the ID of the schema. This ID corresponds to the `schema_id` defined inside the SchemaConfig, under StructuredMemoryCustomizationConfig.""",
+ )
+ profile: Optional[dict[str, Any]] = Field(
+ default=None, description="""Represents the profile data."""
+ )
+
+
+class MemoryProfileDict(TypedDict, total=False):
+ """A memory profile."""
+
+ schema_id: Optional[str]
+ """Represents the ID of the schema. This ID corresponds to the `schema_id` defined inside the SchemaConfig, under StructuredMemoryCustomizationConfig."""
+
+ profile: Optional[dict[str, Any]]
+ """Represents the profile data."""
+
+
+MemoryProfileOrDict = Union[MemoryProfile, MemoryProfileDict]
+
+
+class RetrieveProfilesResponse(_common.BaseModel):
+ """The response for retrieving memory profiles."""
+
+ profiles: Optional[dict[str, MemoryProfile]] = Field(
+ default=None,
+ description="""The retrieved structured profiles, which match the schemas under the
+ requested scope. The key is the ID of the schema that the profile is
+ linked with, which corresponds to the `schema_id` defined inside the
+ `SchemaConfig`, under `StructuredMemoryCustomizationConfig`.""",
+ )
+
+
+class RetrieveProfilesResponseDict(TypedDict, total=False):
+ """The response for retrieving memory profiles."""
+
+ profiles: Optional[dict[str, MemoryProfileDict]]
+ """The retrieved structured profiles, which match the schemas under the
+ requested scope. The key is the ID of the schema that the profile is
+ linked with, which corresponds to the `schema_id` defined inside the
+ `SchemaConfig`, under `StructuredMemoryCustomizationConfig`."""
+
+
+RetrieveProfilesResponseOrDict = Union[
+ RetrieveProfilesResponse, RetrieveProfilesResponseDict
+]
+
+
+class RollbackAgentEngineMemoryConfig(_common.BaseModel):
+ """Config for rolling back a memory."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+
+
+class RollbackAgentEngineMemoryConfigDict(TypedDict, total=False):
+ """Config for rolling back a memory."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+
+RollbackAgentEngineMemoryConfigOrDict = Union[
+ RollbackAgentEngineMemoryConfig, RollbackAgentEngineMemoryConfigDict
+]
+
+
+class _RollbackAgentEngineMemoryRequestParameters(_common.BaseModel):
+ """Parameters for generating agent engine memories."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine memory to rollback."""
+ )
+ target_revision_id: Optional[str] = Field(
+ default=None, description="""The ID of the revision to rollback to."""
+ )
+ config: Optional[RollbackAgentEngineMemoryConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _RollbackAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
+ """Parameters for generating agent engine memories."""
+
+ name: Optional[str]
+ """Name of the agent engine memory to rollback."""
+
+ target_revision_id: Optional[str]
+ """The ID of the revision to rollback to."""
+
+ config: Optional[RollbackAgentEngineMemoryConfigDict]
+ """"""
+
+
+_RollbackAgentEngineMemoryRequestParametersOrDict = Union[
+ _RollbackAgentEngineMemoryRequestParameters,
+ _RollbackAgentEngineMemoryRequestParametersDict,
+]
+
+
+class AgentEngineRollbackMemoryOperation(_common.BaseModel):
+ """Operation that rolls back a memory."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class AgentEngineRollbackMemoryOperationDict(TypedDict, total=False):
+ """Operation that rolls back a memory."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+AgentEngineRollbackMemoryOperationOrDict = Union[
+ AgentEngineRollbackMemoryOperation, AgentEngineRollbackMemoryOperationDict
+]
+
+
+class UpdateAgentEngineMemoryConfig(_common.BaseModel):
+ """Config for updating agent engine memory."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the memory."""
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the memory."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
+ )
+ revision_expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
+ )
+ revision_ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL.""",
+ )
+ disable_memory_revisions: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Input only. If true, no revision will be created for this request.""",
+ )
+ topics: Optional[list[MemoryTopicId]] = Field(
+ default=None, description="""Optional. The topics of the memory."""
+ )
+ metadata: Optional[dict[str, MemoryMetadataValue]] = Field(
+ default=None,
+ description="""Optional. User-provided metadata for the Memory. This information was provided when creating, updating, or generating the Memory. It was not generated by Memory Bank.""",
+ )
+ memory_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. The user defined ID to use for memory, which will become the final component of the memory resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number.""",
+ )
+ update_mask: Optional[str] = Field(
+ default=None,
+ description="""The update mask to apply. For the `FieldMask` definition, see
+ https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask.""",
+ )
+
+
+class UpdateAgentEngineMemoryConfigDict(TypedDict, total=False):
+ """Config for updating agent engine memory."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The display name of the memory."""
+
+ description: Optional[str]
+ """The description of the memory."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL."""
+
+ expire_time: Optional[datetime.datetime]
+ """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""
+
+ revision_expire_time: Optional[datetime.datetime]
+ """Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""
+
+ revision_ttl: Optional[str]
+ """Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL."""
+
+ disable_memory_revisions: Optional[bool]
+ """Optional. Input only. If true, no revision will be created for this request."""
+
+ topics: Optional[list[MemoryTopicIdDict]]
+ """Optional. The topics of the memory."""
+
+ metadata: Optional[dict[str, MemoryMetadataValueDict]]
+ """Optional. User-provided metadata for the Memory. This information was provided when creating, updating, or generating the Memory. It was not generated by Memory Bank."""
+
+ memory_id: Optional[str]
+ """Optional. The user defined ID to use for memory, which will become the final component of the memory resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number."""
+
+ update_mask: Optional[str]
+ """The update mask to apply. For the `FieldMask` definition, see
+ https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask."""
+
+
+UpdateAgentEngineMemoryConfigOrDict = Union[
+ UpdateAgentEngineMemoryConfig, UpdateAgentEngineMemoryConfigDict
+]
+
+
+class _UpdateAgentEngineMemoryRequestParameters(_common.BaseModel):
+ """Parameters for updating agent engine memories."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine memory to update."""
+ )
+ fact: Optional[str] = Field(
+ default=None,
+ description="""The updated fact of the memory.
+
+ This is the semantic knowledge extracted from the source content.""",
+ )
+ scope: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The updated scope of the memory.
+
+ Memories are isolated within their scope. The scope is defined when
+ creating or generating memories. Up to 5 key-value pairs are accepted,
+ and scope values cannot contain the wildcard character '*'.""",
+ )
+ config: Optional[UpdateAgentEngineMemoryConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _UpdateAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
+ """Parameters for updating agent engine memories."""
+
+ name: Optional[str]
+ """Name of the agent engine memory to update."""
+
+ fact: Optional[str]
+ """The updated fact of the memory.
+
+ This is the semantic knowledge extracted from the source content."""
+
+ scope: Optional[dict[str, str]]
+ """The updated scope of the memory.
+
+ Memories are isolated within their scope. The scope is defined when
+ creating or generating memories. Up to 5 key-value pairs are accepted,
+ and scope values cannot contain the wildcard character '*'."""
+
+ config: Optional[UpdateAgentEngineMemoryConfigDict]
+ """"""
+
+
+_UpdateAgentEngineMemoryRequestParametersOrDict = Union[
+ _UpdateAgentEngineMemoryRequestParameters,
+ _UpdateAgentEngineMemoryRequestParametersDict,
+]
+
+
+class PurgeAgentEngineMemoriesConfig(_common.BaseModel):
+ """Config for purging memories."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+
+
+class PurgeAgentEngineMemoriesConfigDict(TypedDict, total=False):
+ """Config for purging memories."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+
+PurgeAgentEngineMemoriesConfigOrDict = Union[
+ PurgeAgentEngineMemoriesConfig, PurgeAgentEngineMemoriesConfigDict
+]
+
+
+class _PurgeAgentEngineMemoriesRequestParameters(_common.BaseModel):
+ """Parameters for purging agent engine memories."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the Agent Engine to purge memories from."""
+ )
+ filter: Optional[str] = Field(
+ default=None,
+ description="""The standard list filter to determine which memories to purge.
+ More detail in [AIP-160](https://google.aip.dev/160).""",
+ )
+ filter_groups: Optional[list[MemoryConjunctionFilter]] = Field(
+ default=None,
+ description="""Metadata filters that will be applied to the memories'
+ `metadata` using OR logic. Filters are defined using disjunctive normal
+ form (OR of ANDs).
+
+ For example:
+ `filter_groups: [{filters: [{key: "author", value: {string_value: "agent
+ `123"}, op: EQUAL}]}, {filters: [{key: "label", value: {string_value:
+ "travel"}, op: EQUAL}, {key: "author", value: {string_value: "agent 321"},
+ op: EQUAL}]}]`
+
+ would be equivalent to the logical expression:
+ `(metadata.author = "agent 123" OR (metadata.label = "travel" AND
+ metadata.author = "agent 321"))`.
+ """,
+ )
+ force: Optional[bool] = Field(
+ default=None,
+ description="""If true, the memories will actually be purged. If false, the purge request will be validated but not executed.""",
+ )
+ config: Optional[PurgeAgentEngineMemoriesConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _PurgeAgentEngineMemoriesRequestParametersDict(TypedDict, total=False):
+ """Parameters for purging agent engine memories."""
+
+ name: Optional[str]
+ """Name of the Agent Engine to purge memories from."""
+
+ filter: Optional[str]
+ """The standard list filter to determine which memories to purge.
+ More detail in [AIP-160](https://google.aip.dev/160)."""
+
+ filter_groups: Optional[list[MemoryConjunctionFilterDict]]
+ """Metadata filters that will be applied to the memories'
+ `metadata` using OR logic. Filters are defined using disjunctive normal
+ form (OR of ANDs).
+
+ For example:
+ `filter_groups: [{filters: [{key: "author", value: {string_value: "agent
+ `123"}, op: EQUAL}]}, {filters: [{key: "label", value: {string_value:
+ "travel"}, op: EQUAL}, {key: "author", value: {string_value: "agent 321"},
+ op: EQUAL}]}]`
+
+ would be equivalent to the logical expression:
+ `(metadata.author = "agent 123" OR (metadata.label = "travel" AND
+ metadata.author = "agent 321"))`.
+ """
+
+ force: Optional[bool]
+ """If true, the memories will actually be purged. If false, the purge request will be validated but not executed."""
+
+ config: Optional[PurgeAgentEngineMemoriesConfigDict]
+ """"""
+
+
+_PurgeAgentEngineMemoriesRequestParametersOrDict = Union[
+ _PurgeAgentEngineMemoriesRequestParameters,
+ _PurgeAgentEngineMemoriesRequestParametersDict,
+]
+
+
+class PurgeMemoriesResponse(_common.BaseModel):
+ """The response for purging memories."""
+
+ purge_count: Optional[int] = Field(
+ default=None, description="""The number of memories that were purged."""
+ )
+
+
+class PurgeMemoriesResponseDict(TypedDict, total=False):
+ """The response for purging memories."""
+
+ purge_count: Optional[int]
+ """The number of memories that were purged."""
+
+
+PurgeMemoriesResponseOrDict = Union[PurgeMemoriesResponse, PurgeMemoriesResponseDict]
+
+
+class AgentEnginePurgeMemoriesOperation(_common.BaseModel):
+ """Operation that purges memories from an agent engine."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[PurgeMemoriesResponse] = Field(
+ default=None, description="""The response for purging memories."""
+ )
+
+
+class AgentEnginePurgeMemoriesOperationDict(TypedDict, total=False):
+ """Operation that purges memories from an agent engine."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[PurgeMemoriesResponseDict]
+ """The response for purging memories."""
+
+
+AgentEnginePurgeMemoriesOperationOrDict = Union[
+ AgentEnginePurgeMemoriesOperation, AgentEnginePurgeMemoriesOperationDict
+]
+
+
+class GetAgentEngineMemoryRevisionConfig(_common.BaseModel):
+ """Config for getting an Agent Engine Memory Revision."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineMemoryRevisionConfigDict(TypedDict, total=False):
+ """Config for getting an Agent Engine Memory Revision."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineMemoryRevisionConfigOrDict = Union[
+ GetAgentEngineMemoryRevisionConfig, GetAgentEngineMemoryRevisionConfigDict
+]
+
+
+class _GetAgentEngineMemoryRevisionRequestParameters(_common.BaseModel):
+ """Parameters for getting an Agent Engine memory revision."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[GetAgentEngineMemoryRevisionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetAgentEngineMemoryRevisionRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting an Agent Engine memory revision."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[GetAgentEngineMemoryRevisionConfigDict]
+ """"""
+
+
+_GetAgentEngineMemoryRevisionRequestParametersOrDict = Union[
+ _GetAgentEngineMemoryRevisionRequestParameters,
+ _GetAgentEngineMemoryRevisionRequestParametersDict,
+]
+
+
+class IntermediateExtractedMemory(_common.BaseModel):
+ """An extracted memory that is the intermediate result before consolidation."""
+
+ fact: Optional[str] = Field(
+ default=None,
+ description="""Output only. Represents the fact of the extracted memory.""",
+ )
+ context: Optional[str] = Field(
+ default=None,
+ description="""Output only. Represents the explanation of why the information was extracted from the source content.""",
+ )
+ structured_data: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Output only. Represents the structured value of the extracted memory.""",
+ )
+
+
+class IntermediateExtractedMemoryDict(TypedDict, total=False):
+ """An extracted memory that is the intermediate result before consolidation."""
+
+ fact: Optional[str]
+ """Output only. Represents the fact of the extracted memory."""
+
+ context: Optional[str]
+ """Output only. Represents the explanation of why the information was extracted from the source content."""
+
+ structured_data: Optional[dict[str, Any]]
+ """Output only. Represents the structured value of the extracted memory."""
+
+
+IntermediateExtractedMemoryOrDict = Union[
+ IntermediateExtractedMemory, IntermediateExtractedMemoryDict
+]
+
+
+class MemoryRevision(_common.BaseModel):
+ """A memory revision."""
+
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Represents the timestamp when this Memory Revision was created.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Represents the timestamp of when this resource is considered expired.""",
+ )
+ extracted_memories: Optional[list[IntermediateExtractedMemory]] = Field(
+ default=None,
+ description="""Output only. Represents the extracted memories from the source content before consolidation when the memory was updated via GenerateMemories. This information was used to modify an existing Memory via Consolidation.""",
+ )
+ fact: Optional[str] = Field(
+ default=None,
+ description="""Output only. Represents the fact of the Memory Revision. This corresponds to the `fact` field of the parent Memory at the time of revision creation.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Output only. Represents the labels of the Memory Revision. These labels are applied to the MemoryRevision when it is created based on `GenerateMemoriesRequest.revision_labels`.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. Represents the resource name of the Memory Revision. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{memory_revision}`""",
+ )
+ structured_data: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Output only. Represents the structured value of the memory at the time of revision creation.""",
+ )
+
+
+class MemoryRevisionDict(TypedDict, total=False):
+ """A memory revision."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Represents the timestamp when this Memory Revision was created."""
+
+ expire_time: Optional[datetime.datetime]
+ """Output only. Represents the timestamp of when this resource is considered expired."""
+
+ extracted_memories: Optional[list[IntermediateExtractedMemoryDict]]
+ """Output only. Represents the extracted memories from the source content before consolidation when the memory was updated via GenerateMemories. This information was used to modify an existing Memory via Consolidation."""
+
+ fact: Optional[str]
+ """Output only. Represents the fact of the Memory Revision. This corresponds to the `fact` field of the parent Memory at the time of revision creation."""
+
+ labels: Optional[dict[str, str]]
+ """Output only. Represents the labels of the Memory Revision. These labels are applied to the MemoryRevision when it is created based on `GenerateMemoriesRequest.revision_labels`."""
+
+ name: Optional[str]
+ """Identifier. Represents the resource name of the Memory Revision. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{memory_revision}`"""
+
+ structured_data: Optional[dict[str, Any]]
+ """Output only. Represents the structured value of the memory at the time of revision creation."""
+
+
+MemoryRevisionOrDict = Union[MemoryRevision, MemoryRevisionDict]
+
+
+class ListAgentEngineMemoryRevisionsConfig(_common.BaseModel):
+ """Config for listing Agent Engine memory revisions."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListAgentEngineMemoryRevisionsConfigDict(TypedDict, total=False):
+ """Config for listing Agent Engine memory revisions."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListAgentEngineMemoryRevisionsConfigOrDict = Union[
+ ListAgentEngineMemoryRevisionsConfig, ListAgentEngineMemoryRevisionsConfigDict
+]
+
+
+class _ListAgentEngineMemoryRevisionsRequestParameters(_common.BaseModel):
+ """Parameters for listing Agent Engine memory revisions."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the Agent Engine memory"""
+ )
+ config: Optional[ListAgentEngineMemoryRevisionsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineMemoryRevisionsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing Agent Engine memory revisions."""
+
+ name: Optional[str]
+ """Name of the Agent Engine memory"""
+
+ config: Optional[ListAgentEngineMemoryRevisionsConfigDict]
+ """"""
+
+
+_ListAgentEngineMemoryRevisionsRequestParametersOrDict = Union[
+ _ListAgentEngineMemoryRevisionsRequestParameters,
+ _ListAgentEngineMemoryRevisionsRequestParametersDict,
+]
+
+
+class ListAgentEngineMemoryRevisionsResponse(_common.BaseModel):
+ """Response for listing agent engine memory revisions."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ memory_revisions: Optional[list[MemoryRevision]] = Field(
+ default=None, description="""List of memory revisions."""
+ )
+
+
+class ListAgentEngineMemoryRevisionsResponseDict(TypedDict, total=False):
+ """Response for listing agent engine memory revisions."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ memory_revisions: Optional[list[MemoryRevisionDict]]
+ """List of memory revisions."""
+
+
+ListAgentEngineMemoryRevisionsResponseOrDict = Union[
+ ListAgentEngineMemoryRevisionsResponse, ListAgentEngineMemoryRevisionsResponseDict
+]
+
+
+class GetAgentEngineRuntimeRevisionConfig(_common.BaseModel):
+ """Config for getting an Agent Engine Runtime Revision."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineRuntimeRevisionConfigDict(TypedDict, total=False):
+ """Config for getting an Agent Engine Runtime Revision."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineRuntimeRevisionConfigOrDict = Union[
+ GetAgentEngineRuntimeRevisionConfig, GetAgentEngineRuntimeRevisionConfigDict
+]
+
+
+class _GetAgentEngineRuntimeRevisionRequestParameters(_common.BaseModel):
+ """Parameters for getting an agent engine runtime revision."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine runtime revision."""
+ )
+ config: Optional[GetAgentEngineRuntimeRevisionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetAgentEngineRuntimeRevisionRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting an agent engine runtime revision."""
+
+ name: Optional[str]
+ """Name of the agent engine runtime revision."""
+
+ config: Optional[GetAgentEngineRuntimeRevisionConfigDict]
+ """"""
+
+
+_GetAgentEngineRuntimeRevisionRequestParametersOrDict = Union[
+ _GetAgentEngineRuntimeRevisionRequestParameters,
+ _GetAgentEngineRuntimeRevisionRequestParametersDict,
+]
+
+
+class ReasoningEngineRuntimeRevision(_common.BaseModel):
+ """A runtime revision."""
+
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this ReasoningEngineRuntimeRevision was created.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the ReasoningEngineRuntimeRevision. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/runtimeRevisions/{runtime_revision}`""",
+ )
+ spec: Optional[ReasoningEngineSpec] = Field(
+ default=None,
+ description="""Immutable. Configurations of the ReasoningEngineRuntimeRevision. Contains only revision specific fields.""",
+ )
+ state: Optional[State] = Field(
+ default=None, description="""Output only. The state of the revision."""
+ )
+
+
+class ReasoningEngineRuntimeRevisionDict(TypedDict, total=False):
+ """A runtime revision."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this ReasoningEngineRuntimeRevision was created."""
+
+ name: Optional[str]
+ """Identifier. The resource name of the ReasoningEngineRuntimeRevision. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/runtimeRevisions/{runtime_revision}`"""
+
+ spec: Optional[ReasoningEngineSpecDict]
+ """Immutable. Configurations of the ReasoningEngineRuntimeRevision. Contains only revision specific fields."""
+
+ state: Optional[State]
+ """Output only. The state of the revision."""
+
+
+ReasoningEngineRuntimeRevisionOrDict = Union[
+ ReasoningEngineRuntimeRevision, ReasoningEngineRuntimeRevisionDict
+]
+
+
+class ListAgentEngineRuntimeRevisionsConfig(_common.BaseModel):
+ """Config for listing reasoning engine runtime revisions."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListAgentEngineRuntimeRevisionsConfigDict(TypedDict, total=False):
+ """Config for listing reasoning engine runtime revisions."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListAgentEngineRuntimeRevisionsConfigOrDict = Union[
+ ListAgentEngineRuntimeRevisionsConfig, ListAgentEngineRuntimeRevisionsConfigDict
+]
+
+
+class _ListAgentEngineRuntimeRevisionsRequestParameters(_common.BaseModel):
+ """Parameters for listing reasoning engine runtime revisions."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the reasoning engine."""
+ )
+ config: Optional[ListAgentEngineRuntimeRevisionsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineRuntimeRevisionsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing reasoning engine runtime revisions."""
+
+ name: Optional[str]
+ """Name of the reasoning engine."""
+
+ config: Optional[ListAgentEngineRuntimeRevisionsConfigDict]
+ """"""
+
+
+_ListAgentEngineRuntimeRevisionsRequestParametersOrDict = Union[
+ _ListAgentEngineRuntimeRevisionsRequestParameters,
+ _ListAgentEngineRuntimeRevisionsRequestParametersDict,
+]
+
+
+class ListReasoningEnginesRuntimeRevisionsResponse(_common.BaseModel):
+ """Response for listing agent engine runtime revisions."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ reasoning_engine_runtime_revisions: Optional[
+ list[ReasoningEngineRuntimeRevision]
+ ] = Field(
+ default=None, description="""List of reasoning engine runtime revisions."""
+ )
+
+
+class ListReasoningEnginesRuntimeRevisionsResponseDict(TypedDict, total=False):
+ """Response for listing agent engine runtime revisions."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ reasoning_engine_runtime_revisions: Optional[
+ list[ReasoningEngineRuntimeRevisionDict]
+ ]
+ """List of reasoning engine runtime revisions."""
+
+
+ListReasoningEnginesRuntimeRevisionsResponseOrDict = Union[
+ ListReasoningEnginesRuntimeRevisionsResponse,
+ ListReasoningEnginesRuntimeRevisionsResponseDict,
+]
+
+
+class DeleteAgentEngineRuntimeRevisionConfig(_common.BaseModel):
+ """Config for deleting an Agent Engine Runtime Revision."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+
+
+class DeleteAgentEngineRuntimeRevisionConfigDict(TypedDict, total=False):
+ """Config for deleting an Agent Engine Runtime Revision."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+
+DeleteAgentEngineRuntimeRevisionConfigOrDict = Union[
+ DeleteAgentEngineRuntimeRevisionConfig, DeleteAgentEngineRuntimeRevisionConfigDict
+]
+
+
+class _DeleteAgentEngineRuntimeRevisionRequestParameters(_common.BaseModel):
+ """Parameters for deleting agent engine runtime revisions."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine runtime revision to delete.""",
+ )
+ config: Optional[DeleteAgentEngineRuntimeRevisionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteAgentEngineRuntimeRevisionRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting agent engine runtime revisions."""
+
+ name: Optional[str]
+ """Name of the agent engine runtime revision to delete."""
+
+ config: Optional[DeleteAgentEngineRuntimeRevisionConfigDict]
+ """"""
+
+
+_DeleteAgentEngineRuntimeRevisionRequestParametersOrDict = Union[
+ _DeleteAgentEngineRuntimeRevisionRequestParameters,
+ _DeleteAgentEngineRuntimeRevisionRequestParametersDict,
+]
+
+
+class DeleteAgentEngineRuntimeRevisionOperation(_common.BaseModel):
+ """Operation for deleting agent engine runtime revisions."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteAgentEngineRuntimeRevisionOperationDict(TypedDict, total=False):
+ """Operation for deleting agent engine runtime revisions."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteAgentEngineRuntimeRevisionOperationOrDict = Union[
+ DeleteAgentEngineRuntimeRevisionOperation,
+ DeleteAgentEngineRuntimeRevisionOperationDict,
+]
+
+
+class GetDeleteAgentEngineRuntimeRevisionOperationConfig(_common.BaseModel):
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetDeleteAgentEngineRuntimeRevisionOperationConfigDict(TypedDict, total=False):
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetDeleteAgentEngineRuntimeRevisionOperationConfigOrDict = Union[
+ GetDeleteAgentEngineRuntimeRevisionOperationConfig,
+ GetDeleteAgentEngineRuntimeRevisionOperationConfigDict,
+]
+
+
+class _GetDeleteAgentEngineRuntimeRevisionOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation that deletes a agent engine runtime revision."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetDeleteAgentEngineRuntimeRevisionOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetDeleteAgentEngineRuntimeRevisionOperationParametersDict(
+ TypedDict, total=False
+):
+ """Parameters for getting an operation that deletes a agent engine runtime revision."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetDeleteAgentEngineRuntimeRevisionOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetDeleteAgentEngineRuntimeRevisionOperationParametersOrDict = Union[
+ _GetDeleteAgentEngineRuntimeRevisionOperationParameters,
+ _GetDeleteAgentEngineRuntimeRevisionOperationParametersDict,
+]
+
+
+class QueryAgentEngineRuntimeRevisionConfig(_common.BaseModel):
+ """Config for querying agent engine runtime revisions."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ class_method: Optional[str] = Field(
+ default=None, description="""The class method to call."""
+ )
+ input: Optional[dict[str, Any]] = Field(
+ default=None, description="""The input to the class method."""
+ )
+ include_all_fields: Optional[bool] = Field(default=False, description="""""")
+
+
+class QueryAgentEngineRuntimeRevisionConfigDict(TypedDict, total=False):
+ """Config for querying agent engine runtime revisions."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ class_method: Optional[str]
+ """The class method to call."""
+
+ input: Optional[dict[str, Any]]
+ """The input to the class method."""
+
+ include_all_fields: Optional[bool]
+ """"""
+
+
+QueryAgentEngineRuntimeRevisionConfigOrDict = Union[
+ QueryAgentEngineRuntimeRevisionConfig, QueryAgentEngineRuntimeRevisionConfigDict
+]
+
+
+class _QueryAgentEngineRuntimeRevisionRequestParameters(_common.BaseModel):
+ """Parameters for querying agent engine runtime revisions."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine runtime revision."""
+ )
+ config: Optional[QueryAgentEngineRuntimeRevisionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _QueryAgentEngineRuntimeRevisionRequestParametersDict(TypedDict, total=False):
+ """Parameters for querying agent engine runtime revisions."""
+
+ name: Optional[str]
+ """Name of the agent engine runtime revision."""
+
+ config: Optional[QueryAgentEngineRuntimeRevisionConfigDict]
+ """"""
+
+
+_QueryAgentEngineRuntimeRevisionRequestParametersOrDict = Union[
+ _QueryAgentEngineRuntimeRevisionRequestParameters,
+ _QueryAgentEngineRuntimeRevisionRequestParametersDict,
+]
+
+
+class SandboxEnvironmentSpecCodeExecutionEnvironment(_common.BaseModel):
+ """The code execution environment with customized settings."""
+
+ code_language: Optional[Language] = Field(
+ default=None,
+ description="""The coding language supported in this environment.""",
+ )
+ machine_config: Optional[MachineConfig] = Field(
+ default=None,
+ description="""The machine config of the code execution environment.""",
+ )
+
+
+class SandboxEnvironmentSpecCodeExecutionEnvironmentDict(TypedDict, total=False):
+ """The code execution environment with customized settings."""
+
+ code_language: Optional[Language]
+ """The coding language supported in this environment."""
+
+ machine_config: Optional[MachineConfig]
+ """The machine config of the code execution environment."""
+
+
+SandboxEnvironmentSpecCodeExecutionEnvironmentOrDict = Union[
+ SandboxEnvironmentSpecCodeExecutionEnvironment,
+ SandboxEnvironmentSpecCodeExecutionEnvironmentDict,
+]
+
+
+class SandboxEnvironmentSpecComputerUseEnvironment(_common.BaseModel):
+ """The computer use environment with customized settings."""
+
+ pass
+
+
+class SandboxEnvironmentSpecComputerUseEnvironmentDict(TypedDict, total=False):
+ """The computer use environment with customized settings."""
+
+ pass
+
+
+SandboxEnvironmentSpecComputerUseEnvironmentOrDict = Union[
+ SandboxEnvironmentSpecComputerUseEnvironment,
+ SandboxEnvironmentSpecComputerUseEnvironmentDict,
+]
+
+
+class SandboxEnvironmentSpec(_common.BaseModel):
+ """The specification of a sandbox environment."""
+
+ code_execution_environment: Optional[
+ SandboxEnvironmentSpecCodeExecutionEnvironment
+ ] = Field(default=None, description="""Optional. The code execution environment.""")
+ computer_use_environment: Optional[SandboxEnvironmentSpecComputerUseEnvironment] = (
+ Field(default=None, description="""Optional. The computer use environment.""")
+ )
+
+
+class SandboxEnvironmentSpecDict(TypedDict, total=False):
+ """The specification of a sandbox environment."""
+
+ code_execution_environment: Optional[
+ SandboxEnvironmentSpecCodeExecutionEnvironmentDict
+ ]
+ """Optional. The code execution environment."""
+
+ computer_use_environment: Optional[SandboxEnvironmentSpecComputerUseEnvironmentDict]
+ """Optional. The computer use environment."""
+
+
+SandboxEnvironmentSpecOrDict = Union[SandboxEnvironmentSpec, SandboxEnvironmentSpecDict]
+
+
+class CreateAgentEngineSandboxConfig(_common.BaseModel):
+ """Config for creating a Sandbox."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the sandbox."""
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the sandbox."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""The TTL for this resource. The expiration time is computed: now + TTL.""",
+ )
+ sandbox_environment_template: Optional[str] = Field(
+ default=None,
+ description="""The name of the sandbox environment template to create the sandbox from. The sandbox environment template should be in the format:
+ projects/{project}/locations/{location}/agentEngines/{agent_engine}/sandboxEnvironmentTemplates/{sandbox_environment_template}""",
+ )
+ sandbox_environment_snapshot: Optional[str] = Field(
+ default=None,
+ description="""The name of the sandbox environment snapshot to restore the sandbox from. The sandbox environment snapshot should be in the format:
+ projects/{project}/locations/{location}/agentEngines/{agent_engine}/sandboxEnvironmentSnapshots/{sandbox_environment_snapshot}""",
+ )
+ owner: Optional[str] = Field(
+ default=None,
+ description="""Owner information for this sandbox environment. A sandbox can only be restored from a snapshot belonging to the same owner.""",
+ )
+
+
+class CreateAgentEngineSandboxConfigDict(TypedDict, total=False):
+ """Config for creating a Sandbox."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The display name of the sandbox."""
+
+ description: Optional[str]
+ """The description of the sandbox."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+ ttl: Optional[str]
+ """The TTL for this resource. The expiration time is computed: now + TTL."""
+
+ sandbox_environment_template: Optional[str]
+ """The name of the sandbox environment template to create the sandbox from. The sandbox environment template should be in the format:
+ projects/{project}/locations/{location}/agentEngines/{agent_engine}/sandboxEnvironmentTemplates/{sandbox_environment_template}"""
+
+ sandbox_environment_snapshot: Optional[str]
+ """The name of the sandbox environment snapshot to restore the sandbox from. The sandbox environment snapshot should be in the format:
+ projects/{project}/locations/{location}/agentEngines/{agent_engine}/sandboxEnvironmentSnapshots/{sandbox_environment_snapshot}"""
+
+ owner: Optional[str]
+ """Owner information for this sandbox environment. A sandbox can only be restored from a snapshot belonging to the same owner."""
+
+
+CreateAgentEngineSandboxConfigOrDict = Union[
+ CreateAgentEngineSandboxConfig, CreateAgentEngineSandboxConfigDict
+]
+
+
+class _CreateAgentEngineSandboxRequestParameters(_common.BaseModel):
+ """Parameters for creating Agent Engine Sandboxes."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to create the sandbox under.""",
+ )
+ spec: Optional[SandboxEnvironmentSpec] = Field(
+ default=None, description="""The specification of the sandbox."""
+ )
+ config: Optional[CreateAgentEngineSandboxConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating Agent Engine Sandboxes."""
+
+ name: Optional[str]
+ """Name of the agent engine to create the sandbox under."""
+
+ spec: Optional[SandboxEnvironmentSpecDict]
+ """The specification of the sandbox."""
+
+ config: Optional[CreateAgentEngineSandboxConfigDict]
+ """"""
+
+
+_CreateAgentEngineSandboxRequestParametersOrDict = Union[
+ _CreateAgentEngineSandboxRequestParameters,
+ _CreateAgentEngineSandboxRequestParametersDict,
+]
+
+
+class SandboxEnvironmentConnectionInfo(_common.BaseModel):
+ """The connection information of the SandboxEnvironment."""
+
+ load_balancer_hostname: Optional[str] = Field(
+ default=None, description="""Output only. The hostname of the load balancer."""
+ )
+ load_balancer_ip: Optional[str] = Field(
+ default=None,
+ description="""Output only. The IP address of the load balancer.""",
+ )
+ sandbox_internal_ip: Optional[str] = Field(
+ default=None,
+ description="""Output only. The internal IP address of the SandboxEnvironment.""",
+ )
+ sandbox_hostname: Optional[str] = Field(
+ default=None,
+ description="""Output only. The hostname of the SandboxEnvironment.""",
+ )
+ routing_token: Optional[str] = Field(
+ default=None,
+ description="""Output only. The routing token for the SandboxEnvironment.""",
+ )
+
+
+class SandboxEnvironmentConnectionInfoDict(TypedDict, total=False):
+ """The connection information of the SandboxEnvironment."""
+
+ load_balancer_hostname: Optional[str]
+ """Output only. The hostname of the load balancer."""
+
+ load_balancer_ip: Optional[str]
+ """Output only. The IP address of the load balancer."""
+
+ sandbox_internal_ip: Optional[str]
+ """Output only. The internal IP address of the SandboxEnvironment."""
+
+ sandbox_hostname: Optional[str]
+ """Output only. The hostname of the SandboxEnvironment."""
+
+ routing_token: Optional[str]
+ """Output only. The routing token for the SandboxEnvironment."""
+
+
+SandboxEnvironmentConnectionInfoOrDict = Union[
+ SandboxEnvironmentConnectionInfo, SandboxEnvironmentConnectionInfoDict
+]
+
+
+class SandboxEnvironment(_common.BaseModel):
+ """A sandbox environment."""
+
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Expiration time of the sandbox environment.
+ """,
+ )
+ connection_info: Optional[SandboxEnvironmentConnectionInfo] = Field(
+ default=None,
+ description="""Output only. The connection information of the SandboxEnvironment.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. The timestamp when this SandboxEnvironment was created.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Required. The display name of the SandboxEnvironment.""",
+ )
+ name: Optional[str] = Field(
+ default=None, description="""Identifier. The name of the SandboxEnvironment."""
+ )
+ spec: Optional[SandboxEnvironmentSpec] = Field(
+ default=None,
+ description="""Optional. The configuration of the SandboxEnvironment.""",
+ )
+ state: Optional[SandboxState] = Field(
+ default=None,
+ description="""Output only. The runtime state of the SandboxEnvironment.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for the sandbox environment. The expiration time is computed: now + TTL.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. The timestamp when this SandboxEnvironment was most recently updated.""",
+ )
+ latest_sandbox_environment_snapshot: Optional[str] = Field(
+ default=None,
+ description="""Output only. The resource name of the latest snapshot taken for this SandboxEnvironment.""",
+ )
+ owner: Optional[str] = Field(
+ default=None,
+ description="""Optional. Owner information for this sandbox environment. A Sandbox can only be restored from a snapshot that belongs to the same owner. If not set, sandbox will be created as the default owner.""",
+ )
+ sandbox_environment_snapshot: Optional[str] = Field(
+ default=None,
+ description="""Optional. The resource name of the SandboxEnvironmentSnapshot to use for creating this SandboxEnvironment. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sandboxEnvironmentSnapshots/{sandbox_environment_snapshot}`""",
+ )
+ sandbox_environment_template: Optional[str] = Field(
+ default=None,
+ description="""Optional. The name of the SandboxEnvironmentTemplate specified in the parent Agent Engine resource that this SandboxEnvironment is created from. Only one of `sandbox_environment_template` and `spec` should be set.""",
+ )
+
+
+class SandboxEnvironmentDict(TypedDict, total=False):
+ """A sandbox environment."""
+
+ expire_time: Optional[datetime.datetime]
+ """Expiration time of the sandbox environment.
+ """
+
+ connection_info: Optional[SandboxEnvironmentConnectionInfoDict]
+ """Output only. The connection information of the SandboxEnvironment."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. The timestamp when this SandboxEnvironment was created."""
+
+ display_name: Optional[str]
+ """Required. The display name of the SandboxEnvironment."""
+
+ name: Optional[str]
+ """Identifier. The name of the SandboxEnvironment."""
+
+ spec: Optional[SandboxEnvironmentSpecDict]
+ """Optional. The configuration of the SandboxEnvironment."""
+
+ state: Optional[SandboxState]
+ """Output only. The runtime state of the SandboxEnvironment."""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL for the sandbox environment. The expiration time is computed: now + TTL."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. The timestamp when this SandboxEnvironment was most recently updated."""
+
+ latest_sandbox_environment_snapshot: Optional[str]
+ """Output only. The resource name of the latest snapshot taken for this SandboxEnvironment."""
+
+ owner: Optional[str]
+ """Optional. Owner information for this sandbox environment. A Sandbox can only be restored from a snapshot that belongs to the same owner. If not set, sandbox will be created as the default owner."""
+
+ sandbox_environment_snapshot: Optional[str]
+ """Optional. The resource name of the SandboxEnvironmentSnapshot to use for creating this SandboxEnvironment. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sandboxEnvironmentSnapshots/{sandbox_environment_snapshot}`"""
+
+ sandbox_environment_template: Optional[str]
+ """Optional. The name of the SandboxEnvironmentTemplate specified in the parent Agent Engine resource that this SandboxEnvironment is created from. Only one of `sandbox_environment_template` and `spec` should be set."""
+
+
+SandboxEnvironmentOrDict = Union[SandboxEnvironment, SandboxEnvironmentDict]
+
+
+class AgentEngineSandboxOperation(_common.BaseModel):
+ """Operation that has an agent engine sandbox as a response."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[SandboxEnvironment] = Field(
+ default=None, description="""The Agent Engine Sandbox."""
+ )
+
+
+class AgentEngineSandboxOperationDict(TypedDict, total=False):
+ """Operation that has an agent engine sandbox as a response."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[SandboxEnvironmentDict]
+ """The Agent Engine Sandbox."""
+
+
+AgentEngineSandboxOperationOrDict = Union[
+ AgentEngineSandboxOperation, AgentEngineSandboxOperationDict
+]
+
+
+class DeleteAgentEngineSandboxConfig(_common.BaseModel):
+ """Config for deleting an Agent Engine Sandbox."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteAgentEngineSandboxConfigDict(TypedDict, total=False):
+ """Config for deleting an Agent Engine Sandbox."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteAgentEngineSandboxConfigOrDict = Union[
+ DeleteAgentEngineSandboxConfig, DeleteAgentEngineSandboxConfigDict
+]
+
+
+class _DeleteAgentEngineSandboxRequestParameters(_common.BaseModel):
+ """Parameters for deleting agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine sandbox to delete."""
+ )
+ config: Optional[DeleteAgentEngineSandboxConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine sandbox to delete."""
+
+ config: Optional[DeleteAgentEngineSandboxConfigDict]
+ """"""
+
+
+_DeleteAgentEngineSandboxRequestParametersOrDict = Union[
+ _DeleteAgentEngineSandboxRequestParameters,
+ _DeleteAgentEngineSandboxRequestParametersDict,
+]
+
+
+class DeleteAgentEngineSandboxOperation(_common.BaseModel):
+ """Operation for deleting agent engines."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteAgentEngineSandboxOperationDict(TypedDict, total=False):
+ """Operation for deleting agent engines."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteAgentEngineSandboxOperationOrDict = Union[
+ DeleteAgentEngineSandboxOperation, DeleteAgentEngineSandboxOperationDict
+]
+
+
+class Metadata(_common.BaseModel):
+ """Metadata for a chunk."""
+
+ attributes: Optional[dict[str, bytes]] = Field(
+ default=None,
+ description="""Optional. Attributes attached to the data. The keys have semantic conventions and the consumers of the attributes should know how to deserialize the value bytes based on the keys.""",
+ )
+
+
+class MetadataDict(TypedDict, total=False):
+ """Metadata for a chunk."""
+
+ attributes: Optional[dict[str, bytes]]
+ """Optional. Attributes attached to the data. The keys have semantic conventions and the consumers of the attributes should know how to deserialize the value bytes based on the keys."""
+
+
+MetadataOrDict = Union[Metadata, MetadataDict]
+
+
+class Chunk(_common.BaseModel):
+ """A chunk of data."""
+
+ data: Optional[bytes] = Field(
+ default=None, description="""Required. The data in the chunk."""
+ )
+ metadata: Optional[Metadata] = Field(
+ default=None,
+ description="""Optional. Metadata that is associated with the data in the payload.""",
+ )
+ mime_type: Optional[str] = Field(
+ default=None,
+ description="""Required. Mime type of the chunk data. See https://www.iana.org/assignments/media-types/media-types.xhtml for the full list.""",
+ )
+
+
+class ChunkDict(TypedDict, total=False):
+ """A chunk of data."""
+
+ data: Optional[bytes]
+ """Required. The data in the chunk."""
+
+ metadata: Optional[MetadataDict]
+ """Optional. Metadata that is associated with the data in the payload."""
+
+ mime_type: Optional[str]
+ """Required. Mime type of the chunk data. See https://www.iana.org/assignments/media-types/media-types.xhtml for the full list."""
+
+
+ChunkOrDict = Union[Chunk, ChunkDict]
+
+
+class ExecuteCodeAgentEngineSandboxConfig(_common.BaseModel):
+ """Config for executing code in an Agent Engine sandbox."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class ExecuteCodeAgentEngineSandboxConfigDict(TypedDict, total=False):
+ """Config for executing code in an Agent Engine sandbox."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+ExecuteCodeAgentEngineSandboxConfigOrDict = Union[
+ ExecuteCodeAgentEngineSandboxConfig, ExecuteCodeAgentEngineSandboxConfigDict
+]
+
+
+class _ExecuteCodeAgentEngineSandboxRequestParameters(_common.BaseModel):
+ """Parameters for executing code in an agent engine sandbox."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine sandbox to execute code in.""",
+ )
+ inputs: Optional[list[Chunk]] = Field(
+ default=None, description="""Inputs to the code execution."""
+ )
+ config: Optional[ExecuteCodeAgentEngineSandboxConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ExecuteCodeAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
+ """Parameters for executing code in an agent engine sandbox."""
+
+ name: Optional[str]
+ """Name of the agent engine sandbox to execute code in."""
+
+ inputs: Optional[list[ChunkDict]]
+ """Inputs to the code execution."""
+
+ config: Optional[ExecuteCodeAgentEngineSandboxConfigDict]
+ """"""
+
+
+_ExecuteCodeAgentEngineSandboxRequestParametersOrDict = Union[
+ _ExecuteCodeAgentEngineSandboxRequestParameters,
+ _ExecuteCodeAgentEngineSandboxRequestParametersDict,
+]
+
+
+class ExecuteSandboxEnvironmentResponse(_common.BaseModel):
+ """The response for executing a sandbox environment."""
+
+ outputs: Optional[list[Chunk]] = Field(
+ default=None, description="""The outputs from the sandbox environment."""
+ )
+
+
+class ExecuteSandboxEnvironmentResponseDict(TypedDict, total=False):
+ """The response for executing a sandbox environment."""
+
+ outputs: Optional[list[ChunkDict]]
+ """The outputs from the sandbox environment."""
+
+
+ExecuteSandboxEnvironmentResponseOrDict = Union[
+ ExecuteSandboxEnvironmentResponse, ExecuteSandboxEnvironmentResponseDict
+]
+
+
+class GetAgentEngineSandboxConfig(_common.BaseModel):
+ """Config for getting an Agent Engine Memory."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineSandboxConfigDict(TypedDict, total=False):
+ """Config for getting an Agent Engine Memory."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineSandboxConfigOrDict = Union[
+ GetAgentEngineSandboxConfig, GetAgentEngineSandboxConfigDict
+]
+
+
+class _GetAgentEngineSandboxRequestParameters(_common.BaseModel):
+ """Parameters for getting an agent engine sandbox."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine sandbox."""
+ )
+ config: Optional[GetAgentEngineSandboxConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting an agent engine sandbox."""
+
+ name: Optional[str]
+ """Name of the agent engine sandbox."""
+
+ config: Optional[GetAgentEngineSandboxConfigDict]
+ """"""
+
+
+_GetAgentEngineSandboxRequestParametersOrDict = Union[
+ _GetAgentEngineSandboxRequestParameters, _GetAgentEngineSandboxRequestParametersDict
+]
+
+
+class ListAgentEngineSandboxesConfig(_common.BaseModel):
+ """Config for listing agent engine sandboxes."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListAgentEngineSandboxesConfigDict(TypedDict, total=False):
+ """Config for listing agent engine sandboxes."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListAgentEngineSandboxesConfigOrDict = Union[
+ ListAgentEngineSandboxesConfig, ListAgentEngineSandboxesConfigDict
+]
+
+
+class _ListAgentEngineSandboxesRequestParameters(_common.BaseModel):
+ """Parameters for listing agent engine sandboxes."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[ListAgentEngineSandboxesConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineSandboxesRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing agent engine sandboxes."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[ListAgentEngineSandboxesConfigDict]
+ """"""
+
+
+_ListAgentEngineSandboxesRequestParametersOrDict = Union[
+ _ListAgentEngineSandboxesRequestParameters,
+ _ListAgentEngineSandboxesRequestParametersDict,
+]
+
+
+class ListAgentEngineSandboxesResponse(_common.BaseModel):
+ """Response for listing agent engine sandboxes."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ sandbox_environments: Optional[list[SandboxEnvironment]] = Field(
+ default=None, description="""List of agent engine sandboxes."""
+ )
+
+
+class ListAgentEngineSandboxesResponseDict(TypedDict, total=False):
+ """Response for listing agent engine sandboxes."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ sandbox_environments: Optional[list[SandboxEnvironmentDict]]
+ """List of agent engine sandboxes."""
+
+
+ListAgentEngineSandboxesResponseOrDict = Union[
+ ListAgentEngineSandboxesResponse, ListAgentEngineSandboxesResponseDict
+]
+
+
+class _GetAgentEngineSandboxOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation with a sandbox as a response."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetAgentEngineOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetAgentEngineSandboxOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation with a sandbox as a response."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetAgentEngineOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetAgentEngineSandboxOperationParametersOrDict = Union[
+ _GetAgentEngineSandboxOperationParameters,
+ _GetAgentEngineSandboxOperationParametersDict,
+]
+
+
+class SandboxEnvironmentTemplateCustomContainerSpec(_common.BaseModel):
+ """Specification for deploying from a custom container image."""
+
+ image_uri: Optional[str] = Field(
+ default=None,
+ description="""Required. The Artifact Registry Docker image URI (e.g., us-central1-docker.pkg.dev/my-project/my-repo/my-image:tag) of the container image that is to be run on each worker replica.""",
+ )
+
+
+class SandboxEnvironmentTemplateCustomContainerSpecDict(TypedDict, total=False):
+ """Specification for deploying from a custom container image."""
+
+ image_uri: Optional[str]
+ """Required. The Artifact Registry Docker image URI (e.g., us-central1-docker.pkg.dev/my-project/my-repo/my-image:tag) of the container image that is to be run on each worker replica."""
+
+
+SandboxEnvironmentTemplateCustomContainerSpecOrDict = Union[
+ SandboxEnvironmentTemplateCustomContainerSpec,
+ SandboxEnvironmentTemplateCustomContainerSpecDict,
+]
+
+
+class SandboxEnvironmentTemplateNetworkPort(_common.BaseModel):
+ """Represents a network port in a container."""
+
+ port: Optional[int] = Field(
+ default=None,
+ description="""Optional. Port number to expose. This must be a valid port number, between 1 and 65535.""",
+ )
+ protocol: Optional[Protocol] = Field(
+ default=None,
+ description="""Optional. Protocol for port. Defaults to TCP if not specified.""",
+ )
+
+
+class SandboxEnvironmentTemplateNetworkPortDict(TypedDict, total=False):
+ """Represents a network port in a container."""
+
+ port: Optional[int]
+ """Optional. Port number to expose. This must be a valid port number, between 1 and 65535."""
+
+ protocol: Optional[Protocol]
+ """Optional. Protocol for port. Defaults to TCP if not specified."""
+
+
+SandboxEnvironmentTemplateNetworkPortOrDict = Union[
+ SandboxEnvironmentTemplateNetworkPort, SandboxEnvironmentTemplateNetworkPortDict
+]
+
+
+class SandboxEnvironmentTemplateResourceRequirements(_common.BaseModel):
+ """Message to define resource requests and limits (mirroring Kubernetes) for each sandbox instance created from this template."""
+
+ limits: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Optional. The maximum amounts of compute resources allowed. Keys are resource names (e.g., "cpu", "memory"). Values are quantities (e.g., "500m", "1Gi").""",
+ )
+ requests: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Optional. The requested amounts of compute resources. Keys are resource names (e.g., "cpu", "memory"). Values are quantities (e.g., "250m", "512Mi").""",
+ )
+
+
+class SandboxEnvironmentTemplateResourceRequirementsDict(TypedDict, total=False):
+ """Message to define resource requests and limits (mirroring Kubernetes) for each sandbox instance created from this template."""
+
+ limits: Optional[dict[str, str]]
+ """Optional. The maximum amounts of compute resources allowed. Keys are resource names (e.g., "cpu", "memory"). Values are quantities (e.g., "500m", "1Gi")."""
+
+ requests: Optional[dict[str, str]]
+ """Optional. The requested amounts of compute resources. Keys are resource names (e.g., "cpu", "memory"). Values are quantities (e.g., "250m", "512Mi")."""
+
+
+SandboxEnvironmentTemplateResourceRequirementsOrDict = Union[
+ SandboxEnvironmentTemplateResourceRequirements,
+ SandboxEnvironmentTemplateResourceRequirementsDict,
+]
+
+
+class SandboxEnvironmentTemplateCustomContainerEnvironment(_common.BaseModel):
+ """The customized sandbox runtime environment for BYOC."""
+
+ custom_container_spec: Optional[SandboxEnvironmentTemplateCustomContainerSpec] = (
+ Field(
+ default=None,
+ description="""The specification of the custom container environment.""",
+ )
+ )
+ ports: Optional[list[SandboxEnvironmentTemplateNetworkPort]] = Field(
+ default=None, description="""Ports to expose from the container."""
+ )
+ resources: Optional[SandboxEnvironmentTemplateResourceRequirements] = Field(
+ default=None, description="""Resource requests and limits for the container."""
+ )
+
+
+class SandboxEnvironmentTemplateCustomContainerEnvironmentDict(TypedDict, total=False):
+ """The customized sandbox runtime environment for BYOC."""
+
+ custom_container_spec: Optional[SandboxEnvironmentTemplateCustomContainerSpecDict]
+ """The specification of the custom container environment."""
+
+ ports: Optional[list[SandboxEnvironmentTemplateNetworkPortDict]]
+ """Ports to expose from the container."""
+
+ resources: Optional[SandboxEnvironmentTemplateResourceRequirementsDict]
+ """Resource requests and limits for the container."""
+
+
+SandboxEnvironmentTemplateCustomContainerEnvironmentOrDict = Union[
+ SandboxEnvironmentTemplateCustomContainerEnvironment,
+ SandboxEnvironmentTemplateCustomContainerEnvironmentDict,
+]
+
+
+class SandboxEnvironmentTemplateDefaultContainerEnvironment(_common.BaseModel):
+ """The default sandbox runtime environment for default container workloads."""
+
+ default_container_category: Optional[DefaultContainerCategory] = Field(
+ default=None,
+ description="""Required. The category of the default container image.""",
+ )
+
+
+class SandboxEnvironmentTemplateDefaultContainerEnvironmentDict(TypedDict, total=False):
+ """The default sandbox runtime environment for default container workloads."""
+
+ default_container_category: Optional[DefaultContainerCategory]
+ """Required. The category of the default container image."""
+
+
+SandboxEnvironmentTemplateDefaultContainerEnvironmentOrDict = Union[
+ SandboxEnvironmentTemplateDefaultContainerEnvironment,
+ SandboxEnvironmentTemplateDefaultContainerEnvironmentDict,
+]
+
+
+class SandboxEnvironmentTemplateEgressControlConfig(_common.BaseModel):
+ """Configuration for egress control of sandbox instances."""
+
+ internet_access: Optional[bool] = Field(
+ default=None, description="""Optional. Whether to allow internet access."""
+ )
+
+
+class SandboxEnvironmentTemplateEgressControlConfigDict(TypedDict, total=False):
+ """Configuration for egress control of sandbox instances."""
+
+ internet_access: Optional[bool]
+ """Optional. Whether to allow internet access."""
+
+
+SandboxEnvironmentTemplateEgressControlConfigOrDict = Union[
+ SandboxEnvironmentTemplateEgressControlConfig,
+ SandboxEnvironmentTemplateEgressControlConfigDict,
+]
+
+
+class CreateSandboxEnvironmentTemplateConfig(_common.BaseModel):
+ """Config for creating a Sandbox Template."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+ custom_container_environment: Optional[
+ SandboxEnvironmentTemplateCustomContainerEnvironment
+ ] = Field(
+ default=None,
+ description="""The custom container environment for the sandbox template.""",
+ )
+ default_container_environment: Optional[
+ SandboxEnvironmentTemplateDefaultContainerEnvironment
+ ] = Field(
+ default=None,
+ description="""The default container environment for the sandbox template.""",
+ )
+ egress_control_config: Optional[SandboxEnvironmentTemplateEgressControlConfig] = (
+ Field(
+ default=None,
+ description="""The egress control config for the sandbox template.""",
+ )
+ )
+
+
+class CreateSandboxEnvironmentTemplateConfigDict(TypedDict, total=False):
+ """Config for creating a Sandbox Template."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+ custom_container_environment: Optional[
+ SandboxEnvironmentTemplateCustomContainerEnvironmentDict
+ ]
+ """The custom container environment for the sandbox template."""
+
+ default_container_environment: Optional[
+ SandboxEnvironmentTemplateDefaultContainerEnvironmentDict
+ ]
+ """The default container environment for the sandbox template."""
+
+ egress_control_config: Optional[SandboxEnvironmentTemplateEgressControlConfigDict]
+ """The egress control config for the sandbox template."""
+
+
+CreateSandboxEnvironmentTemplateConfigOrDict = Union[
+ CreateSandboxEnvironmentTemplateConfig, CreateSandboxEnvironmentTemplateConfigDict
+]
+
+
+class _CreateSandboxEnvironmentTemplateRequestParameters(_common.BaseModel):
+ """Parameters for creating Sandbox Environment Templates."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to create the template under.""",
+ )
+ config: Optional[CreateSandboxEnvironmentTemplateConfig] = Field(
+ default=None, description=""""""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the sandbox template."""
+ )
+
+
+class _CreateSandboxEnvironmentTemplateRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating Sandbox Environment Templates."""
+
+ name: Optional[str]
+ """Name of the agent engine to create the template under."""
+
+ config: Optional[CreateSandboxEnvironmentTemplateConfigDict]
+ """"""
+
+ display_name: Optional[str]
+ """The display name of the sandbox template."""
+
+
+_CreateSandboxEnvironmentTemplateRequestParametersOrDict = Union[
+ _CreateSandboxEnvironmentTemplateRequestParameters,
+ _CreateSandboxEnvironmentTemplateRequestParametersDict,
+]
+
+
+class SandboxEnvironmentTemplateWarmPoolConfig(_common.BaseModel):
+ """Configuration for a warm pool of sandbox instances."""
+
+ target_instance_count: Optional[int] = Field(
+ default=None,
+ description="""Optional. The target number of pre-warmed instances to maintain.""",
+ )
+
+
+class SandboxEnvironmentTemplateWarmPoolConfigDict(TypedDict, total=False):
+ """Configuration for a warm pool of sandbox instances."""
+
+ target_instance_count: Optional[int]
+ """Optional. The target number of pre-warmed instances to maintain."""
+
+
+SandboxEnvironmentTemplateWarmPoolConfigOrDict = Union[
+ SandboxEnvironmentTemplateWarmPoolConfig,
+ SandboxEnvironmentTemplateWarmPoolConfigDict,
+]
+
+
+class SandboxEnvironmentTemplate(_common.BaseModel):
+ """A sandbox environment template."""
+
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. The timestamp when this SandboxEnvironmentTemplate was created.""",
+ )
+ custom_container_environment: Optional[
+ SandboxEnvironmentTemplateCustomContainerEnvironment
+ ] = Field(
+ default=None,
+ description="""The sandbox environment for custom container workloads.""",
+ )
+ default_container_environment: Optional[
+ SandboxEnvironmentTemplateDefaultContainerEnvironment
+ ] = Field(
+ default=None,
+ description="""The sandbox environment for default container workloads.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Required. The display name of the SandboxEnvironmentTemplate.""",
+ )
+ egress_control_config: Optional[SandboxEnvironmentTemplateEgressControlConfig] = (
+ Field(
+ default=None,
+ description="""Optional. The configuration for egress control of this template.""",
+ )
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the SandboxEnvironmentTemplate. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sandboxEnvironmentTemplates/{sandbox_environment_template}`""",
+ )
+ state: Optional[
+ Literal[
+ "UNSPECIFIED",
+ "PROVISIONING",
+ "ACTIVE",
+ "DEPROVISIONING",
+ "DELETED",
+ "FAILED",
+ ]
+ ] = Field(
+ default=None,
+ description="""Output only. The state of the sandbox environment template.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. The timestamp when this SandboxEnvironmentTemplate was most recently updated.""",
+ )
+ warm_pool_config: Optional[SandboxEnvironmentTemplateWarmPoolConfig] = Field(
+ default=None,
+ description="""Optional. The configuration for the warm pool of this template.""",
+ )
+
+
+class SandboxEnvironmentTemplateDict(TypedDict, total=False):
+ """A sandbox environment template."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. The timestamp when this SandboxEnvironmentTemplate was created."""
+
+ custom_container_environment: Optional[
+ SandboxEnvironmentTemplateCustomContainerEnvironmentDict
+ ]
+ """The sandbox environment for custom container workloads."""
+
+ default_container_environment: Optional[
+ SandboxEnvironmentTemplateDefaultContainerEnvironmentDict
+ ]
+ """The sandbox environment for default container workloads."""
+
+ display_name: Optional[str]
+ """Required. The display name of the SandboxEnvironmentTemplate."""
+
+ egress_control_config: Optional[SandboxEnvironmentTemplateEgressControlConfigDict]
+ """Optional. The configuration for egress control of this template."""
+
+ name: Optional[str]
+ """Identifier. The resource name of the SandboxEnvironmentTemplate. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sandboxEnvironmentTemplates/{sandbox_environment_template}`"""
+
+ state: Optional[
+ Literal[
+ "UNSPECIFIED",
+ "PROVISIONING",
+ "ACTIVE",
+ "DEPROVISIONING",
+ "DELETED",
+ "FAILED",
+ ]
+ ]
+ """Output only. The state of the sandbox environment template."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. The timestamp when this SandboxEnvironmentTemplate was most recently updated."""
+
+ warm_pool_config: Optional[SandboxEnvironmentTemplateWarmPoolConfigDict]
+ """Optional. The configuration for the warm pool of this template."""
+
+
+SandboxEnvironmentTemplateOrDict = Union[
+ SandboxEnvironmentTemplate, SandboxEnvironmentTemplateDict
+]
+
+
+class SandboxEnvironmentTemplateOperation(_common.BaseModel):
+ """Operation that has an agent engine sandbox as a response."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[SandboxEnvironmentTemplate] = Field(
+ default=None, description="""The Agent Engine Sandbox Template."""
+ )
+
+
+class SandboxEnvironmentTemplateOperationDict(TypedDict, total=False):
+ """Operation that has an agent engine sandbox as a response."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[SandboxEnvironmentTemplateDict]
+ """The Agent Engine Sandbox Template."""
+
+
+SandboxEnvironmentTemplateOperationOrDict = Union[
+ SandboxEnvironmentTemplateOperation, SandboxEnvironmentTemplateOperationDict
+]
+
+
+class DeleteSandboxEnvironmentTemplateConfig(_common.BaseModel):
+ """Config for deleting a Sandbox Template."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteSandboxEnvironmentTemplateConfigDict(TypedDict, total=False):
+ """Config for deleting a Sandbox Template."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteSandboxEnvironmentTemplateConfigOrDict = Union[
+ DeleteSandboxEnvironmentTemplateConfig, DeleteSandboxEnvironmentTemplateConfigDict
+]
+
+
+class _DeleteSandboxEnvironmentTemplateRequestParameters(_common.BaseModel):
+ """Parameters for deleting sandbox templates."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the sandbox template to delete."""
+ )
+ config: Optional[DeleteSandboxEnvironmentTemplateConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteSandboxEnvironmentTemplateRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting sandbox templates."""
+
+ name: Optional[str]
+ """Name of the sandbox template to delete."""
+
+ config: Optional[DeleteSandboxEnvironmentTemplateConfigDict]
+ """"""
+
+
+_DeleteSandboxEnvironmentTemplateRequestParametersOrDict = Union[
+ _DeleteSandboxEnvironmentTemplateRequestParameters,
+ _DeleteSandboxEnvironmentTemplateRequestParametersDict,
+]
+
+
+class DeleteSandboxEnvironmentTemplateOperation(_common.BaseModel):
+ """Operation for deleting sandbox templates."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteSandboxEnvironmentTemplateOperationDict(TypedDict, total=False):
+ """Operation for deleting sandbox templates."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteSandboxEnvironmentTemplateOperationOrDict = Union[
+ DeleteSandboxEnvironmentTemplateOperation,
+ DeleteSandboxEnvironmentTemplateOperationDict,
+]
+
+
+class GetSandboxEnvironmentTemplateConfig(_common.BaseModel):
+ """Config for getting a Sandbox Template."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetSandboxEnvironmentTemplateConfigDict(TypedDict, total=False):
+ """Config for getting a Sandbox Template."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetSandboxEnvironmentTemplateConfigOrDict = Union[
+ GetSandboxEnvironmentTemplateConfig, GetSandboxEnvironmentTemplateConfigDict
+]
+
+
+class _GetSandboxEnvironmentTemplateRequestParameters(_common.BaseModel):
+ """Parameters for getting a sandbox template."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the sandbox template."""
+ )
+ config: Optional[GetSandboxEnvironmentTemplateConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetSandboxEnvironmentTemplateRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting a sandbox template."""
+
+ name: Optional[str]
+ """Name of the sandbox template."""
+
+ config: Optional[GetSandboxEnvironmentTemplateConfigDict]
+ """"""
+
+
+_GetSandboxEnvironmentTemplateRequestParametersOrDict = Union[
+ _GetSandboxEnvironmentTemplateRequestParameters,
+ _GetSandboxEnvironmentTemplateRequestParametersDict,
+]
+
+
+class ListSandboxEnvironmentTemplatesConfig(_common.BaseModel):
+ """Config for listing sandbox templates."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.""",
+ )
+
+
+class ListSandboxEnvironmentTemplatesConfigDict(TypedDict, total=False):
+ """Config for listing sandbox templates."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request."""
+
+
+ListSandboxEnvironmentTemplatesConfigOrDict = Union[
+ ListSandboxEnvironmentTemplatesConfig, ListSandboxEnvironmentTemplatesConfigDict
+]
+
+
+class _ListSandboxEnvironmentTemplatesRequestParameters(_common.BaseModel):
+ """Parameters for listing sandbox templates."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[ListSandboxEnvironmentTemplatesConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListSandboxEnvironmentTemplatesRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing sandbox templates."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[ListSandboxEnvironmentTemplatesConfigDict]
+ """"""
+
+
+_ListSandboxEnvironmentTemplatesRequestParametersOrDict = Union[
+ _ListSandboxEnvironmentTemplatesRequestParameters,
+ _ListSandboxEnvironmentTemplatesRequestParametersDict,
+]
+
+
+class ListSandboxEnvironmentTemplatesResponse(_common.BaseModel):
+ """Response for listing sandbox templates."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ sandbox_environment_templates: Optional[list[SandboxEnvironmentTemplate]] = Field(
+ default=None, description="""List of sandbox templates."""
+ )
+
+
+class ListSandboxEnvironmentTemplatesResponseDict(TypedDict, total=False):
+ """Response for listing sandbox templates."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ sandbox_environment_templates: Optional[list[SandboxEnvironmentTemplateDict]]
+ """List of sandbox templates."""
+
+
+ListSandboxEnvironmentTemplatesResponseOrDict = Union[
+ ListSandboxEnvironmentTemplatesResponse, ListSandboxEnvironmentTemplatesResponseDict
+]
+
+
+class _GetSandboxEnvironmentTemplateOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation with a sandbox template as a response."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetAgentEngineOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetSandboxEnvironmentTemplateOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation with a sandbox template as a response."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetAgentEngineOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetSandboxEnvironmentTemplateOperationParametersOrDict = Union[
+ _GetSandboxEnvironmentTemplateOperationParameters,
+ _GetSandboxEnvironmentTemplateOperationParametersDict,
+]
+
+
+class CreateAgentEngineSandboxSnapshotConfig(_common.BaseModel):
+ """Config for creating a Sandbox Environment Snapshot."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the sandbox snapshot."""
+ )
+ owner: Optional[str] = Field(
+ default=None, description="""The owner of the sandbox snapshot."""
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""The TTL for this resource. The expiration time is computed: now + TTL.""",
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+
+
+class CreateAgentEngineSandboxSnapshotConfigDict(TypedDict, total=False):
+ """Config for creating a Sandbox Environment Snapshot."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The display name of the sandbox snapshot."""
+
+ owner: Optional[str]
+ """The owner of the sandbox snapshot."""
+
+ ttl: Optional[str]
+ """The TTL for this resource. The expiration time is computed: now + TTL."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+
+CreateAgentEngineSandboxSnapshotConfigOrDict = Union[
+ CreateAgentEngineSandboxSnapshotConfig, CreateAgentEngineSandboxSnapshotConfigDict
+]
+
+
+class _CreateSandboxEnvironmentSnapshotRequestParameters(_common.BaseModel):
+ """Parameters for creating a sandbox environment snapshot."""
+
+ source_sandbox_environment_name: Optional[str] = Field(
+ default=None, description="""Name of the sandbox environment to snapshot."""
+ )
+ config: Optional[CreateAgentEngineSandboxSnapshotConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateSandboxEnvironmentSnapshotRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating a sandbox environment snapshot."""
+
+ source_sandbox_environment_name: Optional[str]
+ """Name of the sandbox environment to snapshot."""
+
+ config: Optional[CreateAgentEngineSandboxSnapshotConfigDict]
+ """"""
+
+
+_CreateSandboxEnvironmentSnapshotRequestParametersOrDict = Union[
+ _CreateSandboxEnvironmentSnapshotRequestParameters,
+ _CreateSandboxEnvironmentSnapshotRequestParametersDict,
+]
+
+
+class SandboxEnvironmentSnapshot(_common.BaseModel):
+ """A sandbox environment snapshot."""
+
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""The display name of the sandbox environment snapshot.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Expiration time of the sandbox environment snapshot.
+ """,
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. The timestamp when this SandboxEnvironmentSnapshot was created.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the SandboxEnvironmentSnapshot. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sandboxEnvironmentSnapshots/{sandbox_environment_snapshot}`""",
+ )
+ owner: Optional[str] = Field(
+ default=None,
+ description="""Optional. Owner information for this sandbox snapshot. Different owners will have isolations on snapshot storage and identity. If not set, snapshot will be created as the default owner.""",
+ )
+ parent_snapshot: Optional[str] = Field(
+ default=None,
+ description="""Output only. The resource name of the parent SandboxEnvironmentSnapshot. Empty if this is a root Snapshot (the first snapshot from a newly created sandbox). Can be used to reconstruct the whole ancestry tree of snapshots.""",
+ )
+ post_snapshot_action: Optional[PostSnapshotAction] = Field(
+ default=None,
+ description="""Optional. Input only. Action to take on the source SandboxEnvironment after the snapshot is taken. This field is only used in CreateSandboxEnvironmentSnapshotRequest and it is not stored in the resource.""",
+ )
+ size_bytes: Optional[int] = Field(
+ default=None,
+ description="""Optional. Output only. Size of the snapshot data in bytes.""",
+ )
+ source_sandbox_environment: Optional[str] = Field(
+ default=None,
+ description="""Required. The resource name of the source SandboxEnvironment this snapshot was taken from.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for the sandbox environment snapshot. The expiration time is computed: now + TTL.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. The timestamp when this SandboxEnvironment was most recently updated.""",
+ )
+
+
+class SandboxEnvironmentSnapshotDict(TypedDict, total=False):
+ """A sandbox environment snapshot."""
+
+ display_name: Optional[str]
+ """The display name of the sandbox environment snapshot."""
+
+ expire_time: Optional[datetime.datetime]
+ """Expiration time of the sandbox environment snapshot.
+ """
+
+ create_time: Optional[datetime.datetime]
+ """Output only. The timestamp when this SandboxEnvironmentSnapshot was created."""
+
+ name: Optional[str]
+ """Identifier. The resource name of the SandboxEnvironmentSnapshot. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sandboxEnvironmentSnapshots/{sandbox_environment_snapshot}`"""
+
+ owner: Optional[str]
+ """Optional. Owner information for this sandbox snapshot. Different owners will have isolations on snapshot storage and identity. If not set, snapshot will be created as the default owner."""
+
+ parent_snapshot: Optional[str]
+ """Output only. The resource name of the parent SandboxEnvironmentSnapshot. Empty if this is a root Snapshot (the first snapshot from a newly created sandbox). Can be used to reconstruct the whole ancestry tree of snapshots."""
+
+ post_snapshot_action: Optional[PostSnapshotAction]
+ """Optional. Input only. Action to take on the source SandboxEnvironment after the snapshot is taken. This field is only used in CreateSandboxEnvironmentSnapshotRequest and it is not stored in the resource."""
+
+ size_bytes: Optional[int]
+ """Optional. Output only. Size of the snapshot data in bytes."""
+
+ source_sandbox_environment: Optional[str]
+ """Required. The resource name of the source SandboxEnvironment this snapshot was taken from."""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL for the sandbox environment snapshot. The expiration time is computed: now + TTL."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. The timestamp when this SandboxEnvironment was most recently updated."""
+
+
+SandboxEnvironmentSnapshotOrDict = Union[
+ SandboxEnvironmentSnapshot, SandboxEnvironmentSnapshotDict
+]
+
+
+class AgentEngineSandboxSnapshotOperation(_common.BaseModel):
+ """Operation that has an agent engine sandbox snapshot as a response."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[SandboxEnvironmentSnapshot] = Field(
+ default=None, description="""The Agent Engine Sandbox Snapshot."""
+ )
+
+
+class AgentEngineSandboxSnapshotOperationDict(TypedDict, total=False):
+ """Operation that has an agent engine sandbox snapshot as a response."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[SandboxEnvironmentSnapshotDict]
+ """The Agent Engine Sandbox Snapshot."""
+
+
+AgentEngineSandboxSnapshotOperationOrDict = Union[
+ AgentEngineSandboxSnapshotOperation, AgentEngineSandboxSnapshotOperationDict
+]
+
+
+class DeleteSandboxEnvironmentSnapshotConfig(_common.BaseModel):
+ """Config for deleting a Sandbox Environment Snapshot."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteSandboxEnvironmentSnapshotConfigDict(TypedDict, total=False):
+ """Config for deleting a Sandbox Environment Snapshot."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteSandboxEnvironmentSnapshotConfigOrDict = Union[
+ DeleteSandboxEnvironmentSnapshotConfig, DeleteSandboxEnvironmentSnapshotConfigDict
+]
+
+
+class _DeleteSandboxEnvironmentSnapshotRequestParameters(_common.BaseModel):
+ """Parameters for deleting sandbox environment snapshots."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the sandbox environment snapshot to delete.""",
+ )
+ config: Optional[DeleteSandboxEnvironmentSnapshotConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteSandboxEnvironmentSnapshotRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting sandbox environment snapshots."""
+
+ name: Optional[str]
+ """Name of the sandbox environment snapshot to delete."""
+
+ config: Optional[DeleteSandboxEnvironmentSnapshotConfigDict]
+ """"""
+
+
+_DeleteSandboxEnvironmentSnapshotRequestParametersOrDict = Union[
+ _DeleteSandboxEnvironmentSnapshotRequestParameters,
+ _DeleteSandboxEnvironmentSnapshotRequestParametersDict,
+]
+
+
+class DeleteSandboxEnvironmentSnapshotOperation(_common.BaseModel):
+ """Operation for deleting sandbox environment snapshots."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteSandboxEnvironmentSnapshotOperationDict(TypedDict, total=False):
+ """Operation for deleting sandbox environment snapshots."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteSandboxEnvironmentSnapshotOperationOrDict = Union[
+ DeleteSandboxEnvironmentSnapshotOperation,
+ DeleteSandboxEnvironmentSnapshotOperationDict,
+]
+
+
+class GetSandboxEnvironmentSnapshotConfig(_common.BaseModel):
+ """Config for getting a Sandbox Environment Snapshot."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetSandboxEnvironmentSnapshotConfigDict(TypedDict, total=False):
+ """Config for getting a Sandbox Environment Snapshot."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetSandboxEnvironmentSnapshotConfigOrDict = Union[
+ GetSandboxEnvironmentSnapshotConfig, GetSandboxEnvironmentSnapshotConfigDict
+]
+
+
+class _GetSandboxEnvironmentSnapshotRequestParameters(_common.BaseModel):
+ """Parameters for getting a sandbox environment snapshot."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the sandbox environment snapshot."""
+ )
+ config: Optional[GetSandboxEnvironmentSnapshotConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetSandboxEnvironmentSnapshotRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting a sandbox environment snapshot."""
+
+ name: Optional[str]
+ """Name of the sandbox environment snapshot."""
+
+ config: Optional[GetSandboxEnvironmentSnapshotConfigDict]
+ """"""
+
+
+_GetSandboxEnvironmentSnapshotRequestParametersOrDict = Union[
+ _GetSandboxEnvironmentSnapshotRequestParameters,
+ _GetSandboxEnvironmentSnapshotRequestParametersDict,
+]
+
+
+class ListSandboxEnvironmentSnapshotsConfig(_common.BaseModel):
+ """Config for listing sandbox environment snapshots."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.""",
+ )
+
+
+class ListSandboxEnvironmentSnapshotsConfigDict(TypedDict, total=False):
+ """Config for listing sandbox environment snapshots."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request."""
+
+
+ListSandboxEnvironmentSnapshotsConfigOrDict = Union[
+ ListSandboxEnvironmentSnapshotsConfig, ListSandboxEnvironmentSnapshotsConfigDict
+]
+
+
+class _ListSandboxEnvironmentSnapshotsRequestParameters(_common.BaseModel):
+ """Parameters for listing sandbox environment snapshots."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the reasoning engine to list snapshots from.""",
+ )
+ config: Optional[ListSandboxEnvironmentSnapshotsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListSandboxEnvironmentSnapshotsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing sandbox environment snapshots."""
+
+ name: Optional[str]
+ """Name of the reasoning engine to list snapshots from."""
+
+ config: Optional[ListSandboxEnvironmentSnapshotsConfigDict]
+ """"""
+
+
+_ListSandboxEnvironmentSnapshotsRequestParametersOrDict = Union[
+ _ListSandboxEnvironmentSnapshotsRequestParameters,
+ _ListSandboxEnvironmentSnapshotsRequestParametersDict,
+]
+
+
+class ListSandboxEnvironmentSnapshotsResponse(_common.BaseModel):
+ """Response for listing sandbox environment snapshots."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ sandbox_environment_snapshots: Optional[list[SandboxEnvironmentSnapshot]] = Field(
+ default=None, description="""List of sandbox environment snapshots."""
+ )
+
+
+class ListSandboxEnvironmentSnapshotsResponseDict(TypedDict, total=False):
+ """Response for listing sandbox environment snapshots."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ sandbox_environment_snapshots: Optional[list[SandboxEnvironmentSnapshotDict]]
+ """List of sandbox environment snapshots."""
+
+
+ListSandboxEnvironmentSnapshotsResponseOrDict = Union[
+ ListSandboxEnvironmentSnapshotsResponse, ListSandboxEnvironmentSnapshotsResponseDict
+]
+
+
+class _GetAgentEngineSandboxSnapshotOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation with a sandbox snapshot as a response."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetAgentEngineOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetAgentEngineSandboxSnapshotOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation with a sandbox snapshot as a response."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetAgentEngineOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetAgentEngineSandboxSnapshotOperationParametersOrDict = Union[
+ _GetAgentEngineSandboxSnapshotOperationParameters,
+ _GetAgentEngineSandboxSnapshotOperationParametersDict,
+]
+
+
+class CreateAgentEngineSessionConfig(_common.BaseModel):
+ """Config for creating a Session."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the session."""
+ )
+ session_state: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Session state which stores key conversation points.""",
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
+ )
+ session_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. The user defined ID to use for session, which will become the final component of the session resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number.""",
+ )
+
+
+class CreateAgentEngineSessionConfigDict(TypedDict, total=False):
+ """Config for creating a Session."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The display name of the session."""
+
+ session_state: Optional[dict[str, Any]]
+ """Session state which stores key conversation points."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL."""
+
+ expire_time: Optional[datetime.datetime]
+ """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""
+
+ labels: Optional[dict[str, str]]
+ """Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""
+
+ session_id: Optional[str]
+ """Optional. The user defined ID to use for session, which will become the final component of the session resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number."""
+
+
+CreateAgentEngineSessionConfigOrDict = Union[
+ CreateAgentEngineSessionConfig, CreateAgentEngineSessionConfigDict
+]
+
+
+class _CreateAgentEngineSessionRequestParameters(_common.BaseModel):
+ """Parameters for creating Agent Engine Sessions."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine to create the session under.""",
+ )
+ user_id: Optional[str] = Field(
+ default=None, description="""The user ID of the session."""
+ )
+ config: Optional[CreateAgentEngineSessionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateAgentEngineSessionRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating Agent Engine Sessions."""
+
+ name: Optional[str]
+ """Name of the agent engine to create the session under."""
+
+ user_id: Optional[str]
+ """The user ID of the session."""
+
+ config: Optional[CreateAgentEngineSessionConfigDict]
+ """"""
+
+
+_CreateAgentEngineSessionRequestParametersOrDict = Union[
+ _CreateAgentEngineSessionRequestParameters,
+ _CreateAgentEngineSessionRequestParametersDict,
+]
+
+
+class Session(_common.BaseModel):
+ """A session."""
+
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when the session was created.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""Optional. The display name of the session."""
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Timestamp of when this session is considered expired. This is *always* provided on output, regardless of what was sent on input. The minimum value is 24 hours from the time of creation.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the session. Format: 'projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}'.""",
+ )
+ session_state: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional. Session specific memory which stores key conversation points.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for this session. The minimum value is 24 hours.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when the session was updated.""",
+ )
+ user_id: Optional[str] = Field(
+ default=None,
+ description="""Required. Immutable. String id provided by the user""",
+ )
+
+
+class SessionDict(TypedDict, total=False):
+ """A session."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when the session was created."""
+
+ display_name: Optional[str]
+ """Optional. The display name of the session."""
+
+ expire_time: Optional[datetime.datetime]
+ """Optional. Timestamp of when this session is considered expired. This is *always* provided on output, regardless of what was sent on input. The minimum value is 24 hours from the time of creation."""
+
+ labels: Optional[dict[str, str]]
+ """The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""
+
+ name: Optional[str]
+ """Identifier. The resource name of the session. Format: 'projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}'."""
+
+ session_state: Optional[dict[str, Any]]
+ """Optional. Session specific memory which stores key conversation points."""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL for this session. The minimum value is 24 hours."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Timestamp when the session was updated."""
+
+ user_id: Optional[str]
+ """Required. Immutable. String id provided by the user"""
+
+
+SessionOrDict = Union[Session, SessionDict]
+
+
+class AgentEngineSessionOperation(_common.BaseModel):
+ """Operation that has an agent engine session as a response."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[Session] = Field(
+ default=None, description="""The Agent Engine Session."""
+ )
+
+
+class AgentEngineSessionOperationDict(TypedDict, total=False):
+ """Operation that has an agent engine session as a response."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[SessionDict]
+ """The Agent Engine Session."""
+
+
+AgentEngineSessionOperationOrDict = Union[
+ AgentEngineSessionOperation, AgentEngineSessionOperationDict
+]
+
+
+class DeleteAgentEngineSessionConfig(_common.BaseModel):
+ """Config for deleting an Agent Engine Session."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class DeleteAgentEngineSessionConfigDict(TypedDict, total=False):
+ """Config for deleting an Agent Engine Session."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+DeleteAgentEngineSessionConfigOrDict = Union[
+ DeleteAgentEngineSessionConfig, DeleteAgentEngineSessionConfigDict
+]
+
+
+class _DeleteAgentEngineSessionRequestParameters(_common.BaseModel):
+ """Parameters for deleting agent engine sessions."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine session to delete."""
+ )
+ config: Optional[DeleteAgentEngineSessionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _DeleteAgentEngineSessionRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting agent engine sessions."""
+
+ name: Optional[str]
+ """Name of the agent engine session to delete."""
+
+ config: Optional[DeleteAgentEngineSessionConfigDict]
+ """"""
+
+
+_DeleteAgentEngineSessionRequestParametersOrDict = Union[
+ _DeleteAgentEngineSessionRequestParameters,
+ _DeleteAgentEngineSessionRequestParametersDict,
+]
+
+
+class DeleteAgentEngineSessionOperation(_common.BaseModel):
+ """Operation for deleting agent engine sessions."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteAgentEngineSessionOperationDict(TypedDict, total=False):
+ """Operation for deleting agent engine sessions."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteAgentEngineSessionOperationOrDict = Union[
+ DeleteAgentEngineSessionOperation, DeleteAgentEngineSessionOperationDict
+]
+
+
+class GetAgentEngineSessionConfig(_common.BaseModel):
+ """Config for getting an Agent Engine Session."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetAgentEngineSessionConfigDict(TypedDict, total=False):
+ """Config for getting an Agent Engine Session."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetAgentEngineSessionConfigOrDict = Union[
+ GetAgentEngineSessionConfig, GetAgentEngineSessionConfigDict
+]
+
+
+class _GetAgentEngineSessionRequestParameters(_common.BaseModel):
+ """Parameters for getting an agent engine session."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine session."""
+ )
+ config: Optional[GetAgentEngineSessionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetAgentEngineSessionRequestParametersDict(TypedDict, total=False):
+ """Parameters for getting an agent engine session."""
+
+ name: Optional[str]
+ """Name of the agent engine session."""
+
+ config: Optional[GetAgentEngineSessionConfigDict]
+ """"""
+
+
+_GetAgentEngineSessionRequestParametersOrDict = Union[
+ _GetAgentEngineSessionRequestParameters, _GetAgentEngineSessionRequestParametersDict
+]
+
+
+class ListAgentEngineSessionsConfig(_common.BaseModel):
+ """Config for listing agent engine sessions."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListAgentEngineSessionsConfigDict(TypedDict, total=False):
+ """Config for listing agent engine sessions."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListAgentEngineSessionsConfigOrDict = Union[
+ ListAgentEngineSessionsConfig, ListAgentEngineSessionsConfigDict
+]
+
+
+class _ListAgentEngineSessionsRequestParameters(_common.BaseModel):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine."""
+ )
+ config: Optional[ListAgentEngineSessionsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineSessionsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine."""
+
+ config: Optional[ListAgentEngineSessionsConfigDict]
+ """"""
+
+
+_ListAgentEngineSessionsRequestParametersOrDict = Union[
+ _ListAgentEngineSessionsRequestParameters,
+ _ListAgentEngineSessionsRequestParametersDict,
+]
+
+
+class ListReasoningEnginesSessionsResponse(_common.BaseModel):
+ """Response for listing agent engine sessions."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ sessions: Optional[list[Session]] = Field(
+ default=None, description="""List of agent engine sessions."""
+ )
+
+
+class ListReasoningEnginesSessionsResponseDict(TypedDict, total=False):
+ """Response for listing agent engine sessions."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ sessions: Optional[list[SessionDict]]
+ """List of agent engine sessions."""
+
+
+ListReasoningEnginesSessionsResponseOrDict = Union[
+ ListReasoningEnginesSessionsResponse, ListReasoningEnginesSessionsResponseDict
+]
+
+
+class _GetAgentEngineSessionOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation with a session as a response."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetAgentEngineOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetAgentEngineSessionOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation with a session as a response."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetAgentEngineOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetAgentEngineSessionOperationParametersOrDict = Union[
+ _GetAgentEngineSessionOperationParameters,
+ _GetAgentEngineSessionOperationParametersDict,
+]
+
+
+class UpdateAgentEngineSessionConfig(_common.BaseModel):
+ """Config for updating agent engine session."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the session."""
+ )
+ session_state: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Session state which stores key conversation points.""",
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Waits for the operation to complete before returning.""",
+ )
+ ttl: Optional[str] = Field(
+ default=None,
+ description="""Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL.""",
+ )
+ expire_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
+ )
+ session_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. The user defined ID to use for session, which will become the final component of the session resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number.""",
+ )
+ update_mask: Optional[str] = Field(
+ default=None,
+ description="""The update mask to apply. For the `FieldMask` definition, see
+ https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask.""",
+ )
+ user_id: Optional[str] = Field(
+ default=None, description="""User ID of the agent engine session to update."""
+ )
+
+
+class UpdateAgentEngineSessionConfigDict(TypedDict, total=False):
+ """Config for updating agent engine session."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ display_name: Optional[str]
+ """The display name of the session."""
+
+ session_state: Optional[dict[str, Any]]
+ """Session state which stores key conversation points."""
+
+ wait_for_completion: Optional[bool]
+ """Waits for the operation to complete before returning."""
+
+ ttl: Optional[str]
+ """Optional. Input only. The TTL for this resource.
+
+ The expiration time is computed: now + TTL."""
+
+ expire_time: Optional[datetime.datetime]
+ """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""
+
+ labels: Optional[dict[str, str]]
+ """Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""
+
+ session_id: Optional[str]
+ """Optional. The user defined ID to use for session, which will become the final component of the session resource name. If not provided, Vertex AI will generate a value for this ID. This value may be up to 63 characters, and valid characters are `[a-z0-9-]`. The first character must be a letter, and the last character must be a letter or number."""
+
+ update_mask: Optional[str]
+ """The update mask to apply. For the `FieldMask` definition, see
+ https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask."""
+
+ user_id: Optional[str]
+ """User ID of the agent engine session to update."""
+
+
+UpdateAgentEngineSessionConfigOrDict = Union[
+ UpdateAgentEngineSessionConfig, UpdateAgentEngineSessionConfigDict
+]
+
+
+class _UpdateAgentEngineSessionRequestParameters(_common.BaseModel):
+ """Parameters for updating agent engine sessions."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine session to update."""
+ )
+ config: Optional[UpdateAgentEngineSessionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _UpdateAgentEngineSessionRequestParametersDict(TypedDict, total=False):
+ """Parameters for updating agent engine sessions."""
+
+ name: Optional[str]
+ """Name of the agent engine session to update."""
+
+ config: Optional[UpdateAgentEngineSessionConfigDict]
+ """"""
+
+
+_UpdateAgentEngineSessionRequestParametersOrDict = Union[
+ _UpdateAgentEngineSessionRequestParameters,
+ _UpdateAgentEngineSessionRequestParametersDict,
+]
+
+
+class EventActions(_common.BaseModel):
+ """Actions are parts of events that are executed by the agent."""
+
+ artifact_delta: Optional[dict[str, int]] = Field(
+ default=None,
+ description="""Optional. Indicates that the event is updating an artifact. key is the filename, value is the version.""",
+ )
+ escalate: Optional[bool] = Field(
+ default=None,
+ description="""Optional. The agent is escalating to a higher level agent.""",
+ )
+ requested_auth_configs: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional. Will only be set by a tool response indicating tool request euc. Struct key is the function call id since one function call response (from model) could correspond to multiple function calls. Struct value is the required auth config, which can be another struct.""",
+ )
+ skip_summarization: Optional[bool] = Field(
+ default=None,
+ description="""Optional. If true, it won't call model to summarize function response. Only used for function_response event.""",
+ )
+ state_delta: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional. Indicates that the event is updating the state with the given delta.""",
+ )
+ transfer_agent: Optional[str] = Field(
+ default=None,
+ description="""Optional. If set, the event transfers to the specified agent.""",
+ )
+
+
+class EventActionsDict(TypedDict, total=False):
+ """Actions are parts of events that are executed by the agent."""
+
+ artifact_delta: Optional[dict[str, int]]
+ """Optional. Indicates that the event is updating an artifact. key is the filename, value is the version."""
+
+ escalate: Optional[bool]
+ """Optional. The agent is escalating to a higher level agent."""
+
+ requested_auth_configs: Optional[dict[str, Any]]
+ """Optional. Will only be set by a tool response indicating tool request euc. Struct key is the function call id since one function call response (from model) could correspond to multiple function calls. Struct value is the required auth config, which can be another struct."""
+
+ skip_summarization: Optional[bool]
+ """Optional. If true, it won't call model to summarize function response. Only used for function_response event."""
+
+ state_delta: Optional[dict[str, Any]]
+ """Optional. Indicates that the event is updating the state with the given delta."""
+
+ transfer_agent: Optional[str]
+ """Optional. If set, the event transfers to the specified agent."""
+
+
+EventActionsOrDict = Union[EventActions, EventActionsDict]
+
+
+class EventMetadata(_common.BaseModel):
+ """Metadata relating to a LLM response event."""
+
+ grounding_metadata: Optional[genai_types.GroundingMetadata] = Field(
+ default=None,
+ description="""Optional. Metadata returned to client when grounding is enabled.""",
+ )
+ branch: Optional[str] = Field(
+ default=None,
+ description="""Optional. The branch of the event. The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple child agents shouldn't see their siblings' conversation history.""",
+ )
+ custom_metadata: Optional[dict[str, Any]] = Field(
+ default=None, description="""The custom metadata of the LlmResponse."""
+ )
+ interrupted: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Flag indicating that LLM was interrupted when generating the content. Usually it's due to user interruption during a bidi streaming.""",
+ )
+ long_running_tool_ids: Optional[list[str]] = Field(
+ default=None,
+ description="""Optional. Set of ids of the long running function calls. Agent client will know from this field about which function call is long running. Only valid for function call event.""",
+ )
+ partial: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Indicates whether the text content is part of a unfinished text stream. Only used for streaming mode and when the content is plain text.""",
+ )
+ turn_complete: Optional[bool] = Field(
+ default=None,
+ description="""Optional. Indicates whether the response from the model is complete. Only used for streaming mode.""",
+ )
+ input_transcription: Optional[genai_types.Transcription] = Field(
+ default=None, description="""Optional. Audio transcription of user input."""
+ )
+ output_transcription: Optional[genai_types.Transcription] = Field(
+ default=None, description="""Optional. Audio transcription of model output."""
+ )
+
+
+class EventMetadataDict(TypedDict, total=False):
+ """Metadata relating to a LLM response event."""
+
+ grounding_metadata: Optional[genai_types.GroundingMetadataDict]
+ """Optional. Metadata returned to client when grounding is enabled."""
+
+ branch: Optional[str]
+ """Optional. The branch of the event. The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple child agents shouldn't see their siblings' conversation history."""
+
+ custom_metadata: Optional[dict[str, Any]]
+ """The custom metadata of the LlmResponse."""
+
+ interrupted: Optional[bool]
+ """Optional. Flag indicating that LLM was interrupted when generating the content. Usually it's due to user interruption during a bidi streaming."""
+
+ long_running_tool_ids: Optional[list[str]]
+ """Optional. Set of ids of the long running function calls. Agent client will know from this field about which function call is long running. Only valid for function call event."""
+
+ partial: Optional[bool]
+ """Optional. Indicates whether the text content is part of a unfinished text stream. Only used for streaming mode and when the content is plain text."""
+
+ turn_complete: Optional[bool]
+ """Optional. Indicates whether the response from the model is complete. Only used for streaming mode."""
+
+ input_transcription: Optional[genai_types.TranscriptionDict]
+ """Optional. Audio transcription of user input."""
+
+ output_transcription: Optional[genai_types.TranscriptionDict]
+ """Optional. Audio transcription of model output."""
+
+
+EventMetadataOrDict = Union[EventMetadata, EventMetadataDict]
+
+
+class AppendAgentEngineSessionEventConfig(_common.BaseModel):
+ """Config for appending agent engine session event."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ content: Optional[genai_types.Content] = Field(
+ default=None, description="""The content of the session event."""
+ )
+ actions: Optional[EventActions] = Field(
+ default=None,
+ description="""Actions are parts of events that are related to the session event.""",
+ )
+ error_code: Optional[str] = Field(
+ default=None, description="""The error code of the session event."""
+ )
+ error_message: Optional[str] = Field(
+ default=None, description="""The error message of the session event."""
+ )
+ event_metadata: Optional[EventMetadata] = Field(
+ default=None, description="""Metadata relating to the session event."""
+ )
+ raw_event: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Weakly typed raw event data in proto struct format.""",
+ )
+
+
+class AppendAgentEngineSessionEventConfigDict(TypedDict, total=False):
+ """Config for appending agent engine session event."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ content: Optional[genai_types.ContentDict]
+ """The content of the session event."""
+
+ actions: Optional[EventActionsDict]
+ """Actions are parts of events that are related to the session event."""
+
+ error_code: Optional[str]
+ """The error code of the session event."""
+
+ error_message: Optional[str]
+ """The error message of the session event."""
+
+ event_metadata: Optional[EventMetadataDict]
+ """Metadata relating to the session event."""
+
+ raw_event: Optional[dict[str, Any]]
+ """Weakly typed raw event data in proto struct format."""
+
+
+AppendAgentEngineSessionEventConfigOrDict = Union[
+ AppendAgentEngineSessionEventConfig, AppendAgentEngineSessionEventConfigDict
+]
+
+
+class _AppendAgentEngineSessionEventRequestParameters(_common.BaseModel):
+ """Parameters for appending agent engines."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine session."""
+ )
+ author: Optional[str] = Field(
+ default=None, description="""Author of the agent engine session event."""
+ )
+ invocation_id: Optional[str] = Field(
+ default=None, description="""Invocation ID of the agent engine."""
+ )
+ timestamp: Optional[datetime.datetime] = Field(
+ default=None, description="""Timestamp indicating when the event was created."""
+ )
+ config: Optional[AppendAgentEngineSessionEventConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _AppendAgentEngineSessionEventRequestParametersDict(TypedDict, total=False):
+ """Parameters for appending agent engines."""
+
+ name: Optional[str]
+ """Name of the agent engine session."""
+
+ author: Optional[str]
+ """Author of the agent engine session event."""
+
+ invocation_id: Optional[str]
+ """Invocation ID of the agent engine."""
+
+ timestamp: Optional[datetime.datetime]
+ """Timestamp indicating when the event was created."""
+
+ config: Optional[AppendAgentEngineSessionEventConfigDict]
+ """"""
+
+
+_AppendAgentEngineSessionEventRequestParametersOrDict = Union[
+ _AppendAgentEngineSessionEventRequestParameters,
+ _AppendAgentEngineSessionEventRequestParametersDict,
+]
+
+
+class AppendAgentEngineSessionEventResponse(_common.BaseModel):
+ """Response for appending agent engine session event."""
+
+ pass
+
+
+class AppendAgentEngineSessionEventResponseDict(TypedDict, total=False):
+ """Response for appending agent engine session event."""
+
+ pass
+
+
+AppendAgentEngineSessionEventResponseOrDict = Union[
+ AppendAgentEngineSessionEventResponse, AppendAgentEngineSessionEventResponseDict
+]
+
+
+class ListAgentEngineSessionEventsConfig(_common.BaseModel):
+ """Config for listing agent engine session events."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListAgentEngineSessionEventsConfigDict(TypedDict, total=False):
+ """Config for listing agent engine session events."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListAgentEngineSessionEventsConfigOrDict = Union[
+ ListAgentEngineSessionEventsConfig, ListAgentEngineSessionEventsConfigDict
+]
+
+
+class _ListAgentEngineSessionEventsRequestParameters(_common.BaseModel):
+ """Parameters for listing agent engine session events."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Name of the agent engine session."""
+ )
+ config: Optional[ListAgentEngineSessionEventsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListAgentEngineSessionEventsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing agent engine session events."""
+
+ name: Optional[str]
+ """Name of the agent engine session."""
+
+ config: Optional[ListAgentEngineSessionEventsConfigDict]
+ """"""
+
+
+_ListAgentEngineSessionEventsRequestParametersOrDict = Union[
+ _ListAgentEngineSessionEventsRequestParameters,
+ _ListAgentEngineSessionEventsRequestParametersDict,
+]
+
+
+class SessionEvent(_common.BaseModel):
+ """A session event."""
+
+ content: Optional[genai_types.Content] = Field(
+ default=None,
+ description="""Optional. Content of the event provided by the author.""",
+ )
+ actions: Optional[EventActions] = Field(
+ default=None, description="""Optional. Actions executed by the agent."""
+ )
+ author: Optional[str] = Field(
+ default=None,
+ description="""Required. The name of the agent that sent the event, or user.""",
+ )
+ error_code: Optional[str] = Field(
+ default=None,
+ description="""Optional. Error code if the response is an error. Code varies by model.""",
+ )
+ error_message: Optional[str] = Field(
+ default=None,
+ description="""Optional. Error message if the response is an error.""",
+ )
+ event_metadata: Optional[EventMetadata] = Field(
+ default=None, description="""Optional. Metadata relating to this event."""
+ )
+ invocation_id: Optional[str] = Field(
+ default=None,
+ description="""Required. The invocation id of the event, multiple events can have the same invocation id.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the event. Format:`projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}/events/{event}`.""",
+ )
+ timestamp: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Required. Timestamp when the event was created on client side.""",
+ )
+ raw_event: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Optional. Weakly typed raw event data in proto struct format.""",
+ )
+
+
+class SessionEventDict(TypedDict, total=False):
+ """A session event."""
+
+ content: Optional[genai_types.ContentDict]
+ """Optional. Content of the event provided by the author."""
+
+ actions: Optional[EventActionsDict]
+ """Optional. Actions executed by the agent."""
+
+ author: Optional[str]
+ """Required. The name of the agent that sent the event, or user."""
+
+ error_code: Optional[str]
+ """Optional. Error code if the response is an error. Code varies by model."""
+
+ error_message: Optional[str]
+ """Optional. Error message if the response is an error."""
+
+ event_metadata: Optional[EventMetadataDict]
+ """Optional. Metadata relating to this event."""
+
+ invocation_id: Optional[str]
+ """Required. The invocation id of the event, multiple events can have the same invocation id."""
+
+ name: Optional[str]
+ """Identifier. The resource name of the event. Format:`projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}/events/{event}`."""
+
+ timestamp: Optional[datetime.datetime]
+ """Required. Timestamp when the event was created on client side."""
+
+ raw_event: Optional[dict[str, Any]]
+ """Optional. Weakly typed raw event data in proto struct format."""
+
+
+SessionEventOrDict = Union[SessionEvent, SessionEventDict]
+
+
+class ListAgentEngineSessionEventsResponse(_common.BaseModel):
+ """Response for listing agent engine session events."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ session_events: Optional[list[SessionEvent]] = Field(
+ default=None, description="""List of session events."""
+ )
+
+
+class ListAgentEngineSessionEventsResponseDict(TypedDict, total=False):
+ """Response for listing agent engine session events."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ session_events: Optional[list[SessionEventDict]]
+ """List of session events."""
+
+
+ListAgentEngineSessionEventsResponseOrDict = Union[
+ ListAgentEngineSessionEventsResponse, ListAgentEngineSessionEventsResponseDict
+]
+
+
+class GeminiExample(_common.BaseModel):
+ """Represents a Gemini example."""
+
+ model: Optional[str] = Field(
+ default=None, description="""The model used to generate the Gemini example."""
+ )
+ contents: Optional[list[genai_types.Content]] = Field(
+ default=None, description="""Contents of the Gemini example."""
+ )
+ system_instruction: Optional[genai_types.Content] = Field(
+ default=None, description="""System instruction for the Gemini example."""
+ )
+ cached_content: Optional[str] = Field(
+ default=None, description="""Cached content for the Gemini example."""
+ )
+ tools: Optional[list[genai_types.Tool]] = Field(
+ default=None, description="""Tools for the Gemini example."""
+ )
+ tool_config: Optional[genai_types.ToolConfig] = Field(
+ default=None, description="""Tools for the Gemini example."""
+ )
+ safety_settings: Optional[list[genai_types.SafetySetting]] = Field(
+ default=None, description="""Safety settings for the Gemini example."""
+ )
+ generation_config: Optional[genai_types.GenerationConfig] = Field(
+ default=None, description="""Generation config for the Gemini example."""
+ )
+ model_armor_config: Optional[genai_types.ModelArmorConfig] = Field(
+ default=None,
+ description="""Optional. Settings for prompt and response sanitization using the Model Armor service. If supplied, safety_settings must not be supplied.""",
+ )
+
+
+class GeminiExampleDict(TypedDict, total=False):
+ """Represents a Gemini example."""
+
+ model: Optional[str]
+ """The model used to generate the Gemini example."""
+
+ contents: Optional[list[genai_types.ContentDict]]
+ """Contents of the Gemini example."""
+
+ system_instruction: Optional[genai_types.ContentDict]
+ """System instruction for the Gemini example."""
+
+ cached_content: Optional[str]
+ """Cached content for the Gemini example."""
+
+ tools: Optional[list[genai_types.ToolDict]]
+ """Tools for the Gemini example."""
+
+ tool_config: Optional[genai_types.ToolConfigDict]
+ """Tools for the Gemini example."""
+
+ safety_settings: Optional[list[genai_types.SafetySettingDict]]
+ """Safety settings for the Gemini example."""
+
+ generation_config: Optional[genai_types.GenerationConfigDict]
+ """Generation config for the Gemini example."""
+
+ model_armor_config: Optional[genai_types.ModelArmorConfigDict]
+ """Optional. Settings for prompt and response sanitization using the Model Armor service. If supplied, safety_settings must not be supplied."""
+
+
+GeminiExampleOrDict = Union[GeminiExample, GeminiExampleDict]
+
+
+class GeminiTemplateConfig(_common.BaseModel):
+ """Represents a Gemini template config."""
+
+ gemini_example: Optional[GeminiExample] = Field(
+ default=None,
+ description="""Required. The template that will be used for assembling the request to use for downstream applications.""",
+ )
+ field_mapping: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""Required. Map of template parameters to the columns in the dataset table.""",
+ )
+
+
+class GeminiTemplateConfigDict(TypedDict, total=False):
+ """Represents a Gemini template config."""
+
+ gemini_example: Optional[GeminiExampleDict]
+ """Required. The template that will be used for assembling the request to use for downstream applications."""
+
+ field_mapping: Optional[dict[str, str]]
+ """Required. Map of template parameters to the columns in the dataset table."""
+
+
+GeminiTemplateConfigOrDict = Union[GeminiTemplateConfig, GeminiTemplateConfigDict]
+
+
+class GeminiRequestReadConfig(_common.BaseModel):
+ """Represents the config for reading Gemini requests."""
+
+ template_config: Optional[GeminiTemplateConfig] = Field(
+ default=None, description="""Gemini request template with placeholders."""
+ )
+ assembled_request_column_name: Optional[str] = Field(
+ default=None,
+ description="""Column name in the underlying BigQuery table that contains already fully assembled Gemini requests.""",
+ )
+
+ @classmethod
+ def single_turn_template(
+ cls,
+ *,
+ prompt: str,
+ response: Optional[str] = None,
+ system_instruction: Optional[str] = None,
+ model: Optional[str] = None,
+ cached_content: Optional[str] = None,
+ tools: Optional[list[Union[genai_types.Tool, dict[str, Any]]]] = None,
+ tool_config: Optional[Union[genai_types.ToolConfig, dict[str, Any]]] = None,
+ safety_settings: Optional[
+ list[Union[genai_types.SafetySetting, dict[str, Any]]]
+ ] = None,
+ generation_config: Optional[
+ Union[genai_types.GenerationConfig, dict[str, Any]]
+ ] = None,
+ field_mapping: Optional[dict[str, str]] = None,
+ ) -> "GeminiRequestReadConfig":
+ """Constructs a GeminiRequestReadConfig object for single-turn cases.
+
+ Example:
+ read_config = GeminiRequestReadConfig.single_turn_template(
+ prompt="Which flower is this {flower_image}?",
+ response="This is a {label}.",
+ system_instruction="You are a botanical classifier."
+ )
+
+ Args:
+ prompt: Required. User input.
+ response: Optional. Model response to user input.
+ system_instruction: Optional. System instructions for the model.
+ model: Optional. The model to use for the GeminiExample.
+ cached_content: Optional. The cached content to use for the GeminiExample.
+ tools: Optional. The tools to use for the GeminiExample.
+ tool_config: Optional. The tool config to use for the GeminiExample.
+ safety_settings: Optional. The safety settings to use for the GeminiExample.
+ generation_config: Optional. The generation config to use for the GeminiExample.
+ field_mapping: Optional. Mapping of placeholders to dataset columns.
+
+ Returns:
+ A GeminiRequestReadConfig object.
+ """
+ contents = []
+ contents.append(
+ genai_types.Content(
+ role="user",
+ parts=[
+ genai_types.Part.from_text(text=prompt),
+ ],
+ )
+ )
+ if response:
+ contents.append(
+ genai_types.Content(
+ role="model",
+ parts=[
+ genai_types.Part.from_text(text=response),
+ ],
+ )
+ )
+
+ system_instruction_content = None
+ if system_instruction:
+ system_instruction_content = genai_types.Content(
+ parts=[
+ genai_types.Part.from_text(text=system_instruction),
+ ],
+ )
+
+ return cls(
+ template_config=GeminiTemplateConfig(
+ gemini_example=GeminiExample(
+ model=model,
+ contents=contents,
+ system_instruction=system_instruction_content,
+ cached_content=cached_content,
+ tools=tools,
+ tool_config=tool_config,
+ safety_settings=safety_settings,
+ generation_config=generation_config,
+ ),
+ field_mapping=field_mapping,
+ ),
+ )
+
+
+class GeminiRequestReadConfigDict(TypedDict, total=False):
+ """Represents the config for reading Gemini requests."""
+
+ template_config: Optional[GeminiTemplateConfigDict]
+ """Gemini request template with placeholders."""
+
+ assembled_request_column_name: Optional[str]
+ """Column name in the underlying BigQuery table that contains already fully assembled Gemini requests."""
+
+
+GeminiRequestReadConfigOrDict = Union[
+ GeminiRequestReadConfig, GeminiRequestReadConfigDict
+]
+
+
+class AssembleDatasetConfig(_common.BaseModel):
+ """Config for assembling a multimodal dataset resource."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""The timeout for the assemble dataset request in seconds. If not
+ set, the default timeout is 90 seconds.""",
+ )
+
+
+class AssembleDatasetConfigDict(TypedDict, total=False):
+ """Config for assembling a multimodal dataset resource."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ timeout: Optional[int]
+ """The timeout for the assemble dataset request in seconds. If not
+ set, the default timeout is 90 seconds."""
+
+
+AssembleDatasetConfigOrDict = Union[AssembleDatasetConfig, AssembleDatasetConfigDict]
+
+
+class _AssembleDatasetParameters(_common.BaseModel):
+ """Parameters for assembling a multimodal dataset resource."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ gemini_request_read_config: Optional[GeminiRequestReadConfig] = Field(
+ default=None, description=""""""
+ )
+ config: Optional[AssembleDatasetConfig] = Field(default=None, description="""""")
+
+
+class _AssembleDatasetParametersDict(TypedDict, total=False):
+ """Parameters for assembling a multimodal dataset resource."""
+
+ name: Optional[str]
+ """"""
+
+ gemini_request_read_config: Optional[GeminiRequestReadConfigDict]
+ """"""
+
+ config: Optional[AssembleDatasetConfigDict]
+ """"""
+
+
+_AssembleDatasetParametersOrDict = Union[
+ _AssembleDatasetParameters, _AssembleDatasetParametersDict
+]
+
+
+class MultimodalDatasetOperation(_common.BaseModel):
+ """Represents the create dataset operation."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[dict[str, Any]] = Field(
+ default=None, description="""The result of the dataset operation."""
+ )
+
+
+class MultimodalDatasetOperationDict(TypedDict, total=False):
+ """Represents the create dataset operation."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[dict[str, Any]]
+ """The result of the dataset operation."""
+
+
+MultimodalDatasetOperationOrDict = Union[
+ MultimodalDatasetOperation, MultimodalDatasetOperationDict
+]
+
+
+class TuningResourceUsageAssessmentConfig(_common.BaseModel):
+ """Config for tuning resource usage assessment."""
+
+ model_name: Optional[str] = Field(default=None, description="""""")
+
+
+class TuningResourceUsageAssessmentConfigDict(TypedDict, total=False):
+ """Config for tuning resource usage assessment."""
+
+ model_name: Optional[str]
+ """"""
+
+
+TuningResourceUsageAssessmentConfigOrDict = Union[
+ TuningResourceUsageAssessmentConfig, TuningResourceUsageAssessmentConfigDict
+]
+
+
+class TuningValidationAssessmentConfig(_common.BaseModel):
+ """Config for tuning validation assessment."""
+
+ model_name: Optional[str] = Field(default=None, description="""""")
+ dataset_usage: Optional[str] = Field(default=None, description="""""")
+
+
+class TuningValidationAssessmentConfigDict(TypedDict, total=False):
+ """Config for tuning validation assessment."""
+
+ model_name: Optional[str]
+ """"""
+
+ dataset_usage: Optional[str]
+ """"""
+
+
+TuningValidationAssessmentConfigOrDict = Union[
+ TuningValidationAssessmentConfig, TuningValidationAssessmentConfigDict
+]
+
+
+class BatchPredictionResourceUsageAssessmentConfig(_common.BaseModel):
+ """Config for batch prediction resource usage assessment."""
+
+ model_name: Optional[str] = Field(default=None, description="""""")
+
+
+class BatchPredictionResourceUsageAssessmentConfigDict(TypedDict, total=False):
+ """Config for batch prediction resource usage assessment."""
+
+ model_name: Optional[str]
+ """"""
+
+
+BatchPredictionResourceUsageAssessmentConfigOrDict = Union[
+ BatchPredictionResourceUsageAssessmentConfig,
+ BatchPredictionResourceUsageAssessmentConfigDict,
+]
+
+
+class BatchPredictionValidationAssessmentConfig(_common.BaseModel):
+ """Config for batch prediction validation assessment."""
+
+ model_name: Optional[str] = Field(default=None, description="""""")
+
+
+class BatchPredictionValidationAssessmentConfigDict(TypedDict, total=False):
+ """Config for batch prediction validation assessment."""
+
+ model_name: Optional[str]
+ """"""
+
+
+BatchPredictionValidationAssessmentConfigOrDict = Union[
+ BatchPredictionValidationAssessmentConfig,
+ BatchPredictionValidationAssessmentConfigDict,
+]
+
+
+class AssessDatasetConfig(_common.BaseModel):
+ """Config for assessing a multimodal dataset resource."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""The timeout for the assess dataset request in seconds. If not set,
+ the default timeout is 90 seconds.""",
+ )
+
+
+class AssessDatasetConfigDict(TypedDict, total=False):
+ """Config for assessing a multimodal dataset resource."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ timeout: Optional[int]
+ """The timeout for the assess dataset request in seconds. If not set,
+ the default timeout is 90 seconds."""
+
+
+AssessDatasetConfigOrDict = Union[AssessDatasetConfig, AssessDatasetConfigDict]
+
+
+class _AssessDatasetParameters(_common.BaseModel):
+ """Parameters for assessing a multimodal dataset resource."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ gemini_request_read_config: Optional[GeminiRequestReadConfig] = Field(
+ default=None, description=""""""
+ )
+ tuning_resource_usage_assessment_config: Optional[
+ TuningResourceUsageAssessmentConfig
+ ] = Field(default=None, description="""""")
+ tuning_validation_assessment_config: Optional[TuningValidationAssessmentConfig] = (
+ Field(default=None, description="""""")
+ )
+ batch_prediction_resource_usage_assessment_config: Optional[
+ BatchPredictionResourceUsageAssessmentConfig
+ ] = Field(default=None, description="""""")
+ batch_prediction_validation_assessment_config: Optional[
+ BatchPredictionValidationAssessmentConfig
+ ] = Field(default=None, description="""""")
+ config: Optional[AssessDatasetConfig] = Field(default=None, description="""""")
+
+
+class _AssessDatasetParametersDict(TypedDict, total=False):
+ """Parameters for assessing a multimodal dataset resource."""
+
+ name: Optional[str]
+ """"""
+
+ gemini_request_read_config: Optional[GeminiRequestReadConfigDict]
+ """"""
+
+ tuning_resource_usage_assessment_config: Optional[
+ TuningResourceUsageAssessmentConfigDict
+ ]
+ """"""
+
+ tuning_validation_assessment_config: Optional[TuningValidationAssessmentConfigDict]
+ """"""
+
+ batch_prediction_resource_usage_assessment_config: Optional[
+ BatchPredictionResourceUsageAssessmentConfigDict
+ ]
+ """"""
+
+ batch_prediction_validation_assessment_config: Optional[
+ BatchPredictionValidationAssessmentConfigDict
+ ]
+ """"""
+
+ config: Optional[AssessDatasetConfigDict]
+ """"""
+
+
+_AssessDatasetParametersOrDict = Union[
+ _AssessDatasetParameters, _AssessDatasetParametersDict
+]
+
+
+class SchemaTablesDatasetMetadataBigQuerySource(_common.BaseModel):
+ """Represents the BigQuery source for multimodal dataset metadata."""
+
+ uri: Optional[str] = Field(
+ default=None,
+ description="""The URI of the BigQuery table. This accepts the table name with or without the bq:// prefix.""",
+ )
+
+
+class SchemaTablesDatasetMetadataBigQuerySourceDict(TypedDict, total=False):
+ """Represents the BigQuery source for multimodal dataset metadata."""
+
+ uri: Optional[str]
+ """The URI of the BigQuery table. This accepts the table name with or without the bq:// prefix."""
+
+
+SchemaTablesDatasetMetadataBigQuerySourceOrDict = Union[
+ SchemaTablesDatasetMetadataBigQuerySource,
+ SchemaTablesDatasetMetadataBigQuerySourceDict,
+]
+
+
+class SchemaTablesDatasetMetadataInputConfig(_common.BaseModel):
+ """Represents the input config for multimodal dataset metadata."""
+
+ bigquery_source: Optional[SchemaTablesDatasetMetadataBigQuerySource] = Field(
+ default=None,
+ description="""The BigQuery source for multimodal dataset metadata.""",
+ )
+
+
+class SchemaTablesDatasetMetadataInputConfigDict(TypedDict, total=False):
+ """Represents the input config for multimodal dataset metadata."""
+
+ bigquery_source: Optional[SchemaTablesDatasetMetadataBigQuerySourceDict]
+ """The BigQuery source for multimodal dataset metadata."""
+
+
+SchemaTablesDatasetMetadataInputConfigOrDict = Union[
+ SchemaTablesDatasetMetadataInputConfig, SchemaTablesDatasetMetadataInputConfigDict
+]
+
+
+class SchemaTablesDatasetMetadata(_common.BaseModel):
+ """Represents the metadata schema for multimodal dataset metadata."""
+
+ input_config: Optional[SchemaTablesDatasetMetadataInputConfig] = Field(
+ default=None,
+ description="""The input config for multimodal dataset metadata.""",
+ )
+ gemini_request_read_config: Optional[GeminiRequestReadConfig] = Field(
+ default=None,
+ description="""The Gemini request read config for the multimodal dataset.""",
+ )
+
+
+class SchemaTablesDatasetMetadataDict(TypedDict, total=False):
+ """Represents the metadata schema for multimodal dataset metadata."""
+
+ input_config: Optional[SchemaTablesDatasetMetadataInputConfigDict]
+ """The input config for multimodal dataset metadata."""
+
+ gemini_request_read_config: Optional[GeminiRequestReadConfigDict]
+ """The Gemini request read config for the multimodal dataset."""
+
+
+SchemaTablesDatasetMetadataOrDict = Union[
+ SchemaTablesDatasetMetadata, SchemaTablesDatasetMetadataDict
+]
+
+
+class CreateMultimodalDatasetConfig(_common.BaseModel):
+ """Config for creating a dataset resource to store multimodal dataset."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""The timeout for the create dataset request in seconds. If not set,
+ the default timeout is 90 seconds.""",
+ )
+
+
+class CreateMultimodalDatasetConfigDict(TypedDict, total=False):
+ """Config for creating a dataset resource to store multimodal dataset."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ timeout: Optional[int]
+ """The timeout for the create dataset request in seconds. If not set,
+ the default timeout is 90 seconds."""
+
+
+CreateMultimodalDatasetConfigOrDict = Union[
+ CreateMultimodalDatasetConfig, CreateMultimodalDatasetConfigDict
+]
+
+
+class _CreateMultimodalDatasetParameters(_common.BaseModel):
+ """Parameters for creating a dataset resource to store multimodal dataset."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ metadata_schema_uri: Optional[str] = Field(default=None, description="""""")
+ metadata: Optional[SchemaTablesDatasetMetadata] = Field(
+ default=None, description=""""""
+ )
+ description: Optional[str] = Field(default=None, description="""""")
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None, description=""""""
+ )
+ config: Optional[CreateMultimodalDatasetConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateMultimodalDatasetParametersDict(TypedDict, total=False):
+ """Parameters for creating a dataset resource to store multimodal dataset."""
+
+ name: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ metadata_schema_uri: Optional[str]
+ """"""
+
+ metadata: Optional[SchemaTablesDatasetMetadataDict]
+ """"""
+
+ description: Optional[str]
+ """"""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """"""
+
+ config: Optional[CreateMultimodalDatasetConfigDict]
+ """"""
+
+
+_CreateMultimodalDatasetParametersOrDict = Union[
+ _CreateMultimodalDatasetParameters, _CreateMultimodalDatasetParametersDict
+]
+
+
+class _DeleteMultimodalDatasetRequestParameters(_common.BaseModel):
+ """Parameters for deleting a multimodal dataset."""
+
+ name: Optional[str] = Field(
+ default=None, description="""ID of the dataset to be deleted."""
+ )
+ config: Optional[VertexBaseConfig] = Field(default=None, description="""""")
+
+
+class _DeleteMultimodalDatasetRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting a multimodal dataset."""
+
+ name: Optional[str]
+ """ID of the dataset to be deleted."""
+
+ config: Optional[VertexBaseConfigDict]
+ """"""
+
+
+_DeleteMultimodalDatasetRequestParametersOrDict = Union[
+ _DeleteMultimodalDatasetRequestParameters,
+ _DeleteMultimodalDatasetRequestParametersDict,
+]
+
+
+class _GetMultimodalDatasetParameters(_common.BaseModel):
+ """Parameters for getting a multimodal dataset resource."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[VertexBaseConfig] = Field(default=None, description="""""")
+
+
+class _GetMultimodalDatasetParametersDict(TypedDict, total=False):
+ """Parameters for getting a multimodal dataset resource."""
+
+ name: Optional[str]
+ """"""
+
+ config: Optional[VertexBaseConfigDict]
+ """"""
+
+
+_GetMultimodalDatasetParametersOrDict = Union[
+ _GetMultimodalDatasetParameters, _GetMultimodalDatasetParametersDict
+]
+
+
+class MultimodalDataset(_common.BaseModel):
+ """Represents a multimodal dataset."""
+
+ name: Optional[str] = Field(
+ default=None, description="""The ID of the multimodal dataset."""
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""The display name of the multimodal dataset."""
+ )
+ metadata: Optional[SchemaTablesDatasetMetadata] = Field(
+ default=None, description="""The metadata of the multimodal dataset."""
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the multimodal dataset."""
+ )
+
+ @property
+ def read_config(self) -> Optional[GeminiRequestReadConfig]:
+ """Gets the read config from the dataset metadata. Returns None if it's not set."""
+ if self.metadata is None or self.metadata.gemini_request_read_config is None:
+ return None
+ return self.metadata.gemini_request_read_config
+
+ def set_read_config(
+ self,
+ *,
+ read_config: GeminiRequestReadConfigOrDict,
+ ) -> None:
+ """Sets the read config in the dataset metadata."""
+ if isinstance(read_config, dict):
+ read_config = GeminiRequestReadConfig(**read_config)
+
+ if self.metadata is None:
+ self.metadata = SchemaTablesDatasetMetadata()
+ self.metadata.gemini_request_read_config = read_config
+
+ @property
+ def bigquery_uri(
+ self,
+ ) -> Optional[str]:
+ """Gets the bigquery uri from the dataset metadata. Returns None if it's not set."""
+ if (
+ self.metadata is None
+ or self.metadata.input_config is None
+ or self.metadata.input_config.bigquery_source is None
+ ):
+ return None
+ return str(self.metadata.input_config.bigquery_source.uri)
+
+ def set_bigquery_uri(
+ self,
+ bigquery_uri: str,
+ ) -> None:
+ """Sets the bigquery uri in the dataset metadata. Prepends 'bq://' if it's not already present."""
+ if not bigquery_uri.startswith("bq://"):
+ bigquery_uri = f"bq://{bigquery_uri}"
+ metadata = (
+ SchemaTablesDatasetMetadata() if self.metadata is None else self.metadata
+ )
+ input_config = (
+ SchemaTablesDatasetMetadataInputConfig()
+ if metadata.input_config is None
+ else metadata.input_config
+ )
+ bigquery_source = (
+ SchemaTablesDatasetMetadataBigQuerySource()
+ if input_config.bigquery_source is None
+ else input_config.bigquery_source
+ )
+ bigquery_source.uri = bigquery_uri
+ input_config.bigquery_source = bigquery_source
+ metadata.input_config = input_config
+ self.metadata = metadata
+
+ def to_bigframes(
+ self,
+ ) -> "bigframes.pandas.DataFrame": # type: ignore # noqa: F821
+ """Converts the multimodal dataset to a BigFrames dataframe.
+
+ This is the preferred method to inspect the multimodal dataset in a
+ notebook.
+
+ Returns:
+ A BigFrames dataframe.
+ """
+ from .. import _datasets_utils
+
+ bigframes = _datasets_utils._try_import_bigframes()
+
+ if self.bigquery_uri is None:
+ raise ValueError("Multimodal dataset bigquery source uri is not set.")
+ return bigframes.pandas.read_gbq_table(self.bigquery_uri.removeprefix("bq://"))
+
+
+class MultimodalDatasetDict(TypedDict, total=False):
+ """Represents a multimodal dataset."""
+
+ name: Optional[str]
+ """The ID of the multimodal dataset."""
+
+ display_name: Optional[str]
+ """The display name of the multimodal dataset."""
+
+ metadata: Optional[SchemaTablesDatasetMetadataDict]
+ """The metadata of the multimodal dataset."""
+
+ description: Optional[str]
+ """The description of the multimodal dataset."""
+
+
+MultimodalDatasetOrDict = Union[MultimodalDataset, MultimodalDatasetDict]
+
+
+class GetMultimodalDatasetOperationConfig(_common.BaseModel):
+ """Config for getting a multimodal dataset operation."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetMultimodalDatasetOperationConfigDict(TypedDict, total=False):
+ """Config for getting a multimodal dataset operation."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetMultimodalDatasetOperationConfigOrDict = Union[
+ GetMultimodalDatasetOperationConfig, GetMultimodalDatasetOperationConfigDict
+]
+
+
+class _GetMultimodalDatasetOperationParameters(_common.BaseModel):
+ """Parameters for getting a dataset operation."""
+
+ dataset_id: Optional[str] = Field(default=None, description="""""")
+ operation_id: Optional[str] = Field(default=None, description="""""")
+ config: Optional[GetMultimodalDatasetOperationConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetMultimodalDatasetOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting a dataset operation."""
+
+ dataset_id: Optional[str]
+ """"""
+
+ operation_id: Optional[str]
+ """"""
+
+ config: Optional[GetMultimodalDatasetOperationConfigDict]
+ """"""
+
+
+_GetMultimodalDatasetOperationParametersOrDict = Union[
+ _GetMultimodalDatasetOperationParameters,
+ _GetMultimodalDatasetOperationParametersDict,
+]
+
+
+class ListMultimodalDatasetsConfig(_common.BaseModel):
+ """Config for listing multimodal datasets."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListMultimodalDatasetsConfigDict(TypedDict, total=False):
+ """Config for listing multimodal datasets."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListMultimodalDatasetsConfigOrDict = Union[
+ ListMultimodalDatasetsConfig, ListMultimodalDatasetsConfigDict
+]
+
+
+class _ListMultimodalDatasetsRequestParameters(_common.BaseModel):
+ """Parameters for listing multimodal datasets."""
+
+ config: Optional[ListMultimodalDatasetsConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _ListMultimodalDatasetsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing multimodal datasets."""
+
+ config: Optional[ListMultimodalDatasetsConfigDict]
+ """"""
+
+
+_ListMultimodalDatasetsRequestParametersOrDict = Union[
+ _ListMultimodalDatasetsRequestParameters,
+ _ListMultimodalDatasetsRequestParametersDict,
+]
+
+
+class ListMultimodalDatasetsResponse(_common.BaseModel):
+ """Response for listing multimodal datasets."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""The timeout for the list datasets request in seconds. If not set,
+ the default timeout is 90 seconds.""",
+ )
+ datasets: Optional[list[MultimodalDataset]] = Field(
+ default=None,
+ description="""List of datasets for the project.
+ """,
+ )
+
+
+class ListMultimodalDatasetsResponseDict(TypedDict, total=False):
+ """Response for listing multimodal datasets."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ timeout: Optional[int]
+ """The timeout for the list datasets request in seconds. If not set,
+ the default timeout is 90 seconds."""
+
+ datasets: Optional[list[MultimodalDatasetDict]]
+ """List of datasets for the project.
+ """
+
+
+ListMultimodalDatasetsResponseOrDict = Union[
+ ListMultimodalDatasetsResponse, ListMultimodalDatasetsResponseDict
+]
+
+
+class _UpdateMultimodalDatasetParameters(_common.BaseModel):
+ """Parameters for updating a multimodal dataset resource."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ metadata: Optional[SchemaTablesDatasetMetadata] = Field(
+ default=None, description=""""""
+ )
+ description: Optional[str] = Field(default=None, description="""""")
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None, description=""""""
+ )
+ config: Optional[VertexBaseConfig] = Field(default=None, description="""""")
+
+
+class _UpdateMultimodalDatasetParametersDict(TypedDict, total=False):
+ """Parameters for updating a multimodal dataset resource."""
+
+ name: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ metadata: Optional[SchemaTablesDatasetMetadataDict]
+ """"""
+
+ description: Optional[str]
+ """"""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """"""
+
+ config: Optional[VertexBaseConfigDict]
+ """"""
+
+
+_UpdateMultimodalDatasetParametersOrDict = Union[
+ _UpdateMultimodalDatasetParameters, _UpdateMultimodalDatasetParametersDict
+]
+
+
+class SchemaPredictParamsGroundingConfigSourceEntry(_common.BaseModel):
+ """Single source entry for the grounding checking."""
+
+ enterprise_datastore: Optional[str] = Field(
+ default=None,
+ description="""The uri of the Vertex AI Search data source. Deprecated. Use vertex_ai_search_datastore instead.""",
+ )
+ inline_context: Optional[str] = Field(
+ default=None,
+ description="""The grounding text passed inline with the Predict API. It can support up to 1 million bytes.""",
+ )
+ type: Optional[
+ Literal["UNSPECIFIED", "WEB", "ENTERPRISE", "VERTEX_AI_SEARCH", "INLINE"]
+ ] = Field(
+ default=None, description="""The type of the grounding checking source."""
+ )
+ vertex_ai_search_datastore: Optional[str] = Field(
+ default=None, description="""The uri of the Vertex AI Search data source."""
+ )
+
+
+class SchemaPredictParamsGroundingConfigSourceEntryDict(TypedDict, total=False):
+ """Single source entry for the grounding checking."""
+
+ enterprise_datastore: Optional[str]
+ """The uri of the Vertex AI Search data source. Deprecated. Use vertex_ai_search_datastore instead."""
+
+ inline_context: Optional[str]
+ """The grounding text passed inline with the Predict API. It can support up to 1 million bytes."""
+
+ type: Optional[
+ Literal["UNSPECIFIED", "WEB", "ENTERPRISE", "VERTEX_AI_SEARCH", "INLINE"]
+ ]
+ """The type of the grounding checking source."""
+
+ vertex_ai_search_datastore: Optional[str]
+ """The uri of the Vertex AI Search data source."""
+
+
+SchemaPredictParamsGroundingConfigSourceEntryOrDict = Union[
+ SchemaPredictParamsGroundingConfigSourceEntry,
+ SchemaPredictParamsGroundingConfigSourceEntryDict,
+]
+
+
+class SchemaPredictParamsGroundingConfig(_common.BaseModel):
+ """The configuration for grounding checking."""
+
+ disable_attribution: Optional[bool] = Field(
+ default=None,
+ description="""If set, skip finding claim attributions (i.e not generate grounding citation).""",
+ )
+ sources: Optional[list[SchemaPredictParamsGroundingConfigSourceEntry]] = Field(
+ default=None, description="""The sources for the grounding checking."""
+ )
+
+
+class SchemaPredictParamsGroundingConfigDict(TypedDict, total=False):
+ """The configuration for grounding checking."""
+
+ disable_attribution: Optional[bool]
+ """If set, skip finding claim attributions (i.e not generate grounding citation)."""
+
+ sources: Optional[list[SchemaPredictParamsGroundingConfigSourceEntryDict]]
+ """The sources for the grounding checking."""
+
+
+SchemaPredictParamsGroundingConfigOrDict = Union[
+ SchemaPredictParamsGroundingConfig, SchemaPredictParamsGroundingConfigDict
+]
+
+
+class SchemaPromptInstancePromptExecution(_common.BaseModel):
+ """A prompt instance's parameters set that contains a set of variable values."""
+
+ arguments: Optional[dict[str, "SchemaPromptInstanceVariableValue"]] = Field(
+ default=None, description="""Maps variable names to their value."""
+ )
+
+
+class SchemaPromptInstancePromptExecutionDict(TypedDict, total=False):
+ """A prompt instance's parameters set that contains a set of variable values."""
+
+ arguments: Optional[dict[str, "SchemaPromptInstanceVariableValueDict"]]
+ """Maps variable names to their value."""
+
+
+SchemaPromptInstancePromptExecutionOrDict = Union[
+ SchemaPromptInstancePromptExecution, SchemaPromptInstancePromptExecutionDict
+]
+
+
+class SchemaPromptSpecPromptMessage(_common.BaseModel):
+ """Represents a prompt message."""
+
+ generation_config: Optional[genai_types.GenerationConfig] = Field(
+ default=None, description="""Generation config."""
+ )
+ tool_config: Optional[genai_types.FunctionCallingConfig] = Field(
+ default=None,
+ description="""Tool config. This config is shared for all tools provided in the request.""",
+ )
+ tools: Optional[list[genai_types.Tool]] = Field(
+ default=None,
+ description="""A list of `Tools` the model may use to generate the next response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model.""",
+ )
+ safety_settings: Optional[list[genai_types.SafetySetting]] = Field(
+ default=None,
+ description="""Per request settings for blocking unsafe content. Enforced on GenerateContentResponse.candidates.""",
+ )
+ contents: Optional[list[genai_types.Content]] = Field(
+ default=None,
+ description="""The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request.""",
+ )
+ system_instruction: Optional[genai_types.Content] = Field(
+ default=None,
+ description="""The user provided system instructions for the model. Note: only text should be used in parts and content in each part will be in a separate paragraph.""",
+ )
+ variables: Optional[list[dict[str, genai_types.Part]]] = Field(
+ default=None, description=""""""
+ )
+ model: Optional[str] = Field(default=None, description="""The model name.""")
+
+
+class SchemaPromptSpecPromptMessageDict(TypedDict, total=False):
+ """Represents a prompt message."""
+
+ generation_config: Optional[genai_types.GenerationConfigDict]
+ """Generation config."""
+
+ tool_config: Optional[genai_types.FunctionCallingConfigDict]
+ """Tool config. This config is shared for all tools provided in the request."""
+
+ tools: Optional[list[genai_types.ToolDict]]
+ """A list of `Tools` the model may use to generate the next response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model."""
+
+ safety_settings: Optional[list[genai_types.SafetySettingDict]]
+ """Per request settings for blocking unsafe content. Enforced on GenerateContentResponse.candidates."""
+
+ contents: Optional[list[genai_types.ContentDict]]
+ """The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request."""
+
+ system_instruction: Optional[genai_types.ContentDict]
+ """The user provided system instructions for the model. Note: only text should be used in parts and content in each part will be in a separate paragraph."""
+
+ variables: Optional[list[dict[str, genai_types.PartDict]]]
+ """"""
+
+ model: Optional[str]
+ """The model name."""
+
+
+SchemaPromptSpecPromptMessageOrDict = Union[
+ SchemaPromptSpecPromptMessage, SchemaPromptSpecPromptMessageDict
+]
+
+
+class SchemaPromptSpecMultimodalPrompt(_common.BaseModel):
+ """Prompt variation that embeds preambles to prompt string."""
+
+ prompt_message: Optional[SchemaPromptSpecPromptMessage] = Field(
+ default=None, description="""The prompt message."""
+ )
+
+
+class SchemaPromptSpecMultimodalPromptDict(TypedDict, total=False):
+ """Prompt variation that embeds preambles to prompt string."""
+
+ prompt_message: Optional[SchemaPromptSpecPromptMessageDict]
+ """The prompt message."""
+
+
+SchemaPromptSpecMultimodalPromptOrDict = Union[
+ SchemaPromptSpecMultimodalPrompt, SchemaPromptSpecMultimodalPromptDict
+]
+
+
+class SchemaPromptSpecAppBuilderDataLinkedResource(_common.BaseModel):
+ """A linked resource attached to the application by the user."""
+
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""A user-friendly name for the data source shown in the UI.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""The unique resource name of the data source. The format is determined by the 'type' field. For type "SAVED_PROMPT": projects/{project}/locations/{location}/datasets/{dataset} For type "AI_AGENT": projects/{project}/locations/{location}/agents/{agent}""",
+ )
+ type: Optional[str] = Field(
+ default=None,
+ description="""The type of the linked resource. e.g., "SAVED_PROMPT", "AI_AGENT" This string corresponds to the name of the LinkedResourceType enum member. See: google3/cloud/console/web/ai/platform/llm/prompts/build/services/specs_repository_service/linked_resources/linked_resource.ts""",
+ )
+
+
+class SchemaPromptSpecAppBuilderDataLinkedResourceDict(TypedDict, total=False):
+ """A linked resource attached to the application by the user."""
+
+ display_name: Optional[str]
+ """A user-friendly name for the data source shown in the UI."""
+
+ name: Optional[str]
+ """The unique resource name of the data source. The format is determined by the 'type' field. For type "SAVED_PROMPT": projects/{project}/locations/{location}/datasets/{dataset} For type "AI_AGENT": projects/{project}/locations/{location}/agents/{agent}"""
+
+ type: Optional[str]
+ """The type of the linked resource. e.g., "SAVED_PROMPT", "AI_AGENT" This string corresponds to the name of the LinkedResourceType enum member. See: google3/cloud/console/web/ai/platform/llm/prompts/build/services/specs_repository_service/linked_resources/linked_resource.ts"""
+
+
+SchemaPromptSpecAppBuilderDataLinkedResourceOrDict = Union[
+ SchemaPromptSpecAppBuilderDataLinkedResource,
+ SchemaPromptSpecAppBuilderDataLinkedResourceDict,
+]
+
+
+class SchemaPromptSpecAppBuilderData(_common.BaseModel):
+ """Defines data for an application builder."""
+
+ code_repository_state: Optional[str] = Field(
+ default=None,
+ description="""Serialized state of the code repository. This string will typically contain a JSON representation of the UI's CodeRepositoryService state (files, folders, content, and any metadata). The UI is responsible for serialization and deserialization.""",
+ )
+ framework: Optional[Framework] = Field(
+ default=None,
+ description="""Optional. Framework used to build the application.""",
+ )
+ linked_resources: Optional[list[SchemaPromptSpecAppBuilderDataLinkedResource]] = (
+ Field(
+ default=None,
+ description="""Linked resources attached to the application by the user.""",
+ )
+ )
+
+
+class SchemaPromptSpecAppBuilderDataDict(TypedDict, total=False):
+ """Defines data for an application builder."""
+
+ code_repository_state: Optional[str]
+ """Serialized state of the code repository. This string will typically contain a JSON representation of the UI's CodeRepositoryService state (files, folders, content, and any metadata). The UI is responsible for serialization and deserialization."""
+
+ framework: Optional[Framework]
+ """Optional. Framework used to build the application."""
+
+ linked_resources: Optional[list[SchemaPromptSpecAppBuilderDataLinkedResourceDict]]
+ """Linked resources attached to the application by the user."""
+
+
+SchemaPromptSpecAppBuilderDataOrDict = Union[
+ SchemaPromptSpecAppBuilderData, SchemaPromptSpecAppBuilderDataDict
+]
+
+
+class SchemaPromptSpecPartList(_common.BaseModel):
+ """Represents a prompt spec part list."""
+
+ parts: Optional[list[genai_types.Part]] = Field(
+ default=None, description="""A list of elements that can be part of a prompt."""
+ )
+
+
+class SchemaPromptSpecPartListDict(TypedDict, total=False):
+ """Represents a prompt spec part list."""
+
+ parts: Optional[list[genai_types.PartDict]]
+ """A list of elements that can be part of a prompt."""
+
+
+SchemaPromptSpecPartListOrDict = Union[
+ SchemaPromptSpecPartList, SchemaPromptSpecPartListDict
+]
+
+
+class SchemaPromptSpecStructuredPrompt(_common.BaseModel):
+ """Represents a structured prompt."""
+
+ context: Optional[genai_types.Content] = Field(
+ default=None, description="""Preamble: The context of the prompt."""
+ )
+ app_builder_data: Optional[SchemaPromptSpecAppBuilderData] = Field(
+ default=None, description="""Data for app builder use case."""
+ )
+ examples: Optional[list[SchemaPromptSpecPartList]] = Field(
+ default=None,
+ description="""Preamble: A set of examples for expected model response.""",
+ )
+ infill_prefix: Optional[str] = Field(
+ default=None,
+ description="""Preamble: For infill prompt, the prefix before expected model response.""",
+ )
+ infill_suffix: Optional[str] = Field(
+ default=None,
+ description="""Preamble: For infill prompt, the suffix after expected model response.""",
+ )
+ input_prefixes: Optional[list[str]] = Field(
+ default=None,
+ description="""Preamble: The input prefixes before each example input.""",
+ )
+ output_prefixes: Optional[list[str]] = Field(
+ default=None,
+ description="""Preamble: The output prefixes before each example output.""",
+ )
+ prediction_inputs: Optional[list[SchemaPromptSpecPartList]] = Field(
+ default=None,
+ description="""Preamble: The input test data for prediction. Each PartList in this field represents one text-only input set for a single model request.""",
+ )
+ prompt_message: Optional[SchemaPromptSpecPromptMessage] = Field(
+ default=None, description="""The prompt message."""
+ )
+
+
+class SchemaPromptSpecStructuredPromptDict(TypedDict, total=False):
+ """Represents a structured prompt."""
+
+ context: Optional[genai_types.ContentDict]
+ """Preamble: The context of the prompt."""
+
+ app_builder_data: Optional[SchemaPromptSpecAppBuilderDataDict]
+ """Data for app builder use case."""
+
+ examples: Optional[list[SchemaPromptSpecPartListDict]]
+ """Preamble: A set of examples for expected model response."""
+
+ infill_prefix: Optional[str]
+ """Preamble: For infill prompt, the prefix before expected model response."""
+
+ infill_suffix: Optional[str]
+ """Preamble: For infill prompt, the suffix after expected model response."""
+
+ input_prefixes: Optional[list[str]]
+ """Preamble: The input prefixes before each example input."""
+
+ output_prefixes: Optional[list[str]]
+ """Preamble: The output prefixes before each example output."""
+
+ prediction_inputs: Optional[list[SchemaPromptSpecPartListDict]]
+ """Preamble: The input test data for prediction. Each PartList in this field represents one text-only input set for a single model request."""
+
+ prompt_message: Optional[SchemaPromptSpecPromptMessageDict]
+ """The prompt message."""
+
+
+SchemaPromptSpecStructuredPromptOrDict = Union[
+ SchemaPromptSpecStructuredPrompt, SchemaPromptSpecStructuredPromptDict
+]
+
+
+class SchemaPromptSpecReferenceSentencePair(_common.BaseModel):
+ """A pair of sentences used as reference in source and target languages."""
+
+ source_sentence: Optional[str] = Field(
+ default=None, description="""Source sentence in the sentence pair."""
+ )
+ target_sentence: Optional[str] = Field(
+ default=None, description="""Target sentence in the sentence pair."""
+ )
+
+
+class SchemaPromptSpecReferenceSentencePairDict(TypedDict, total=False):
+ """A pair of sentences used as reference in source and target languages."""
+
+ source_sentence: Optional[str]
+ """Source sentence in the sentence pair."""
+
+ target_sentence: Optional[str]
+ """Target sentence in the sentence pair."""
+
+
+SchemaPromptSpecReferenceSentencePairOrDict = Union[
+ SchemaPromptSpecReferenceSentencePair, SchemaPromptSpecReferenceSentencePairDict
+]
+
+
+class SchemaPromptSpecReferenceSentencePairList(_common.BaseModel):
+ """A list of reference sentence pairs."""
+
+ reference_sentence_pairs: Optional[list[SchemaPromptSpecReferenceSentencePair]] = (
+ Field(default=None, description="""Reference sentence pairs.""")
+ )
+
+
+class SchemaPromptSpecReferenceSentencePairListDict(TypedDict, total=False):
+ """A list of reference sentence pairs."""
+
+ reference_sentence_pairs: Optional[list[SchemaPromptSpecReferenceSentencePairDict]]
+ """Reference sentence pairs."""
+
+
+SchemaPromptSpecReferenceSentencePairListOrDict = Union[
+ SchemaPromptSpecReferenceSentencePairList,
+ SchemaPromptSpecReferenceSentencePairListDict,
+]
+
+
+class SchemaPromptSpecTranslationFileInputSource(_common.BaseModel):
+
+ content: Optional[str] = Field(default=None, description="""The file's contents.""")
+ display_name: Optional[str] = Field(
+ default=None, description="""The file's display name."""
+ )
+ mime_type: Optional[str] = Field(
+ default=None, description="""The file's mime type."""
+ )
+
+
+class SchemaPromptSpecTranslationFileInputSourceDict(TypedDict, total=False):
+
+ content: Optional[str]
+ """The file's contents."""
+
+ display_name: Optional[str]
+ """The file's display name."""
+
+ mime_type: Optional[str]
+ """The file's mime type."""
+
+
+SchemaPromptSpecTranslationFileInputSourceOrDict = Union[
+ SchemaPromptSpecTranslationFileInputSource,
+ SchemaPromptSpecTranslationFileInputSourceDict,
+]
+
+
+class SchemaPromptSpecTranslationGcsInputSource(_common.BaseModel):
+
+ input_uri: Optional[str] = Field(
+ default=None,
+ description="""Source data URI. For example, `gs://my_bucket/my_object`.""",
+ )
+
+
+class SchemaPromptSpecTranslationGcsInputSourceDict(TypedDict, total=False):
+
+ input_uri: Optional[str]
+ """Source data URI. For example, `gs://my_bucket/my_object`."""
+
+
+SchemaPromptSpecTranslationGcsInputSourceOrDict = Union[
+ SchemaPromptSpecTranslationGcsInputSource,
+ SchemaPromptSpecTranslationGcsInputSourceDict,
+]
+
+
+class SchemaPromptSpecTranslationSentenceFileInput(_common.BaseModel):
+
+ file_input_source: Optional[SchemaPromptSpecTranslationFileInputSource] = Field(
+ default=None, description="""Inlined file source."""
+ )
+ gcs_input_source: Optional[SchemaPromptSpecTranslationGcsInputSource] = Field(
+ default=None, description="""Cloud Storage file source."""
+ )
+
+
+class SchemaPromptSpecTranslationSentenceFileInputDict(TypedDict, total=False):
+
+ file_input_source: Optional[SchemaPromptSpecTranslationFileInputSourceDict]
+ """Inlined file source."""
+
+ gcs_input_source: Optional[SchemaPromptSpecTranslationGcsInputSourceDict]
+ """Cloud Storage file source."""
+
+
+SchemaPromptSpecTranslationSentenceFileInputOrDict = Union[
+ SchemaPromptSpecTranslationSentenceFileInput,
+ SchemaPromptSpecTranslationSentenceFileInputDict,
+]
+
+
+class SchemaPromptSpecTranslationExample(_common.BaseModel):
+ """The translation example that contains reference sentences from various sources."""
+
+ reference_sentence_pair_lists: Optional[
+ list[SchemaPromptSpecReferenceSentencePairList]
+ ] = Field(default=None, description="""The reference sentences from inline text.""")
+ reference_sentences_file_inputs: Optional[
+ list[SchemaPromptSpecTranslationSentenceFileInput]
+ ] = Field(default=None, description="""The reference sentences from file.""")
+
+
+class SchemaPromptSpecTranslationExampleDict(TypedDict, total=False):
+ """The translation example that contains reference sentences from various sources."""
+
+ reference_sentence_pair_lists: Optional[
+ list[SchemaPromptSpecReferenceSentencePairListDict]
+ ]
+ """The reference sentences from inline text."""
+
+ reference_sentences_file_inputs: Optional[
+ list[SchemaPromptSpecTranslationSentenceFileInputDict]
+ ]
+ """The reference sentences from file."""
+
+
+SchemaPromptSpecTranslationExampleOrDict = Union[
+ SchemaPromptSpecTranslationExample, SchemaPromptSpecTranslationExampleDict
+]
+
+
+class SchemaPromptSpecTranslationOption(_common.BaseModel):
+ """Optional settings for translation prompt."""
+
+ number_of_shots: Optional[int] = Field(
+ default=None, description="""How many shots to use."""
+ )
+
+
+class SchemaPromptSpecTranslationOptionDict(TypedDict, total=False):
+ """Optional settings for translation prompt."""
+
+ number_of_shots: Optional[int]
+ """How many shots to use."""
+
+
+SchemaPromptSpecTranslationOptionOrDict = Union[
+ SchemaPromptSpecTranslationOption, SchemaPromptSpecTranslationOptionDict
+]
+
+
+class SchemaPromptSpecTranslationPrompt(_common.BaseModel):
+ """Prompt variation for Translation use case."""
+
+ example: Optional[SchemaPromptSpecTranslationExample] = Field(
+ default=None, description="""The translation example."""
+ )
+ option: Optional[SchemaPromptSpecTranslationOption] = Field(
+ default=None, description="""The translation option."""
+ )
+ prompt_message: Optional[SchemaPromptSpecPromptMessage] = Field(
+ default=None, description="""The prompt message."""
+ )
+ source_language_code: Optional[str] = Field(
+ default=None, description="""The source language code."""
+ )
+ target_language_code: Optional[str] = Field(
+ default=None, description="""The target language code."""
+ )
+
+
+class SchemaPromptSpecTranslationPromptDict(TypedDict, total=False):
+ """Prompt variation for Translation use case."""
+
+ example: Optional[SchemaPromptSpecTranslationExampleDict]
+ """The translation example."""
+
+ option: Optional[SchemaPromptSpecTranslationOptionDict]
+ """The translation option."""
+
+ prompt_message: Optional[SchemaPromptSpecPromptMessageDict]
+ """The prompt message."""
+
+ source_language_code: Optional[str]
+ """The source language code."""
+
+ target_language_code: Optional[str]
+ """The target language code."""
+
+
+SchemaPromptSpecTranslationPromptOrDict = Union[
+ SchemaPromptSpecTranslationPrompt, SchemaPromptSpecTranslationPromptDict
+]
+
+
+class SchemaPromptApiSchema(_common.BaseModel):
+ """The A2 schema of a prompt."""
+
+ api_schema_version: Optional[str] = Field(
+ default=None,
+ description="""The Schema version that represents changes to the API behavior.""",
+ )
+ executions: Optional[list[SchemaPromptInstancePromptExecution]] = Field(
+ default=None,
+ description="""A list of execution instances for constructing a ready-to-use prompt.""",
+ )
+ multimodal_prompt: Optional[SchemaPromptSpecMultimodalPrompt] = Field(
+ default=None,
+ description="""Multimodal prompt which embeds preambles to prompt string.""",
+ )
+ structured_prompt: Optional[SchemaPromptSpecStructuredPrompt] = Field(
+ default=None,
+ description="""The prompt variation that stores preambles in separate fields.""",
+ )
+ translation_prompt: Optional[SchemaPromptSpecTranslationPrompt] = Field(
+ default=None, description="""The prompt variation for Translation use case."""
+ )
+
+
+class SchemaPromptApiSchemaDict(TypedDict, total=False):
+ """The A2 schema of a prompt."""
+
+ api_schema_version: Optional[str]
+ """The Schema version that represents changes to the API behavior."""
+
+ executions: Optional[list[SchemaPromptInstancePromptExecutionDict]]
+ """A list of execution instances for constructing a ready-to-use prompt."""
+
+ multimodal_prompt: Optional[SchemaPromptSpecMultimodalPromptDict]
+ """Multimodal prompt which embeds preambles to prompt string."""
+
+ structured_prompt: Optional[SchemaPromptSpecStructuredPromptDict]
+ """The prompt variation that stores preambles in separate fields."""
+
+ translation_prompt: Optional[SchemaPromptSpecTranslationPromptDict]
+ """The prompt variation for Translation use case."""
+
+
+SchemaPromptApiSchemaOrDict = Union[SchemaPromptApiSchema, SchemaPromptApiSchemaDict]
+
+
+class SchemaTextPromptDatasetMetadata(_common.BaseModel):
+ """Represents the text prompt dataset metadata."""
+
+ candidate_count: Optional[int] = Field(
+ default=None, description="""Number of candidates."""
+ )
+ gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""The Google Cloud Storage URI that stores the prompt data.""",
+ )
+ grounding_config: Optional[SchemaPredictParamsGroundingConfig] = Field(
+ default=None, description="""Grounding checking configuration."""
+ )
+ has_prompt_variable: Optional[bool] = Field(
+ default=None, description="""Whether the prompt dataset has prompt variable."""
+ )
+ logprobs: Optional[bool] = Field(
+ default=None,
+ description="""Whether or not the user has enabled logit probabilities in the model parameters.""",
+ )
+ max_output_tokens: Optional[int] = Field(
+ default=None,
+ description="""Value of the maximum number of tokens generated set when the dataset was saved.""",
+ )
+ note: Optional[str] = Field(
+ default=None,
+ description="""User-created prompt note. Note size limit is 2KB.""",
+ )
+ prompt_api_schema: Optional[SchemaPromptApiSchema] = Field(
+ default=None,
+ description="""The API schema of the prompt to support both UI and SDK usages.""",
+ )
+ prompt_type: Optional[str] = Field(
+ default=None, description="""Type of the prompt dataset."""
+ )
+ seed_enabled: Optional[bool] = Field(
+ default=None,
+ description="""Seeding enables model to return a deterministic response on a best effort basis. Determinism isn't guaranteed. This field determines whether or not seeding is enabled.""",
+ )
+ seed_value: Optional[int] = Field(
+ default=None, description="""The actual value of the seed."""
+ )
+ stop_sequences: Optional[list[str]] = Field(
+ default=None, description="""Customized stop sequences."""
+ )
+ system_instruction: Optional[str] = Field(
+ default=None,
+ description="""The content of the prompt dataset system instruction.""",
+ )
+ system_instruction_gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""The Google Cloud Storage URI that stores the system instruction, starting with gs://.""",
+ )
+ temperature: Optional[float] = Field(
+ default=None,
+ description="""Temperature value used for sampling set when the dataset was saved. This value is used to tune the degree of randomness.""",
+ )
+ text: Optional[str] = Field(
+ default=None, description="""The content of the prompt dataset."""
+ )
+ top_k: Optional[int] = Field(
+ default=None,
+ description="""Top K value set when the dataset was saved. This value determines how many candidates with highest probability from the vocab would be selected for each decoding step.""",
+ )
+ top_p: Optional[float] = Field(
+ default=None,
+ description="""Top P value set when the dataset was saved. Given topK tokens for decoding, top candidates will be selected until the sum of their probabilities is topP.""",
+ )
+
+
+class SchemaTextPromptDatasetMetadataDict(TypedDict, total=False):
+ """Represents the text prompt dataset metadata."""
+
+ candidate_count: Optional[int]
+ """Number of candidates."""
+
+ gcs_uri: Optional[str]
+ """The Google Cloud Storage URI that stores the prompt data."""
+
+ grounding_config: Optional[SchemaPredictParamsGroundingConfigDict]
+ """Grounding checking configuration."""
+
+ has_prompt_variable: Optional[bool]
+ """Whether the prompt dataset has prompt variable."""
+
+ logprobs: Optional[bool]
+ """Whether or not the user has enabled logit probabilities in the model parameters."""
+
+ max_output_tokens: Optional[int]
+ """Value of the maximum number of tokens generated set when the dataset was saved."""
+
+ note: Optional[str]
+ """User-created prompt note. Note size limit is 2KB."""
+
+ prompt_api_schema: Optional[SchemaPromptApiSchemaDict]
+ """The API schema of the prompt to support both UI and SDK usages."""
+
+ prompt_type: Optional[str]
+ """Type of the prompt dataset."""
+
+ seed_enabled: Optional[bool]
+ """Seeding enables model to return a deterministic response on a best effort basis. Determinism isn't guaranteed. This field determines whether or not seeding is enabled."""
+
+ seed_value: Optional[int]
+ """The actual value of the seed."""
+
+ stop_sequences: Optional[list[str]]
+ """Customized stop sequences."""
+
+ system_instruction: Optional[str]
+ """The content of the prompt dataset system instruction."""
+
+ system_instruction_gcs_uri: Optional[str]
+ """The Google Cloud Storage URI that stores the system instruction, starting with gs://."""
+
+ temperature: Optional[float]
+ """Temperature value used for sampling set when the dataset was saved. This value is used to tune the degree of randomness."""
+
+ text: Optional[str]
+ """The content of the prompt dataset."""
+
+ top_k: Optional[int]
+ """Top K value set when the dataset was saved. This value determines how many candidates with highest probability from the vocab would be selected for each decoding step."""
+
+ top_p: Optional[float]
+ """Top P value set when the dataset was saved. Given topK tokens for decoding, top candidates will be selected until the sum of their probabilities is topP."""
+
+
+SchemaTextPromptDatasetMetadataOrDict = Union[
+ SchemaTextPromptDatasetMetadata, SchemaTextPromptDatasetMetadataDict
+]
+
+
+class CreateDatasetConfig(_common.BaseModel):
+ """Config for creating a dataset resource to store prompts."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class CreateDatasetConfigDict(TypedDict, total=False):
+ """Config for creating a dataset resource to store prompts."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+CreateDatasetConfigOrDict = Union[CreateDatasetConfig, CreateDatasetConfigDict]
+
+
+class _CreateDatasetParameters(_common.BaseModel):
+ """Parameters for creating a dataset resource to store prompts."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ metadata_schema_uri: Optional[str] = Field(default=None, description="""""")
+ metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
+ default=None, description=""""""
+ )
+ description: Optional[str] = Field(default=None, description="""""")
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None, description=""""""
+ )
+ model_reference: Optional[str] = Field(default=None, description="""""")
+ config: Optional[CreateDatasetConfig] = Field(default=None, description="""""")
+
+
+class _CreateDatasetParametersDict(TypedDict, total=False):
+ """Parameters for creating a dataset resource to store prompts."""
+
+ name: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ metadata_schema_uri: Optional[str]
+ """"""
+
+ metadata: Optional[SchemaTextPromptDatasetMetadataDict]
+ """"""
+
+ description: Optional[str]
+ """"""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """"""
+
+ model_reference: Optional[str]
+ """"""
+
+ config: Optional[CreateDatasetConfigDict]
+ """"""
+
+
+_CreateDatasetParametersOrDict = Union[
+ _CreateDatasetParameters, _CreateDatasetParametersDict
+]
+
+
+class DatasetOperation(_common.BaseModel):
+ """Represents the create dataset operation."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[dict[str, Any]] = Field(
+ default=None, description="""The result of the dataset operation."""
+ )
+
+
+class DatasetOperationDict(TypedDict, total=False):
+ """Represents the create dataset operation."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[dict[str, Any]]
+ """The result of the dataset operation."""
+
+
+DatasetOperationOrDict = Union[DatasetOperation, DatasetOperationDict]
+
+
+class CreateDatasetVersionConfig(_common.BaseModel):
+ """Config for creating a dataset version resource to store prompts."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class CreateDatasetVersionConfigDict(TypedDict, total=False):
+ """Config for creating a dataset version resource to store prompts."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+CreateDatasetVersionConfigOrDict = Union[
+ CreateDatasetVersionConfig, CreateDatasetVersionConfigDict
+]
+
+
+class _CreateDatasetVersionParameters(_common.BaseModel):
+ """Represents the create dataset version parameters."""
+
+ dataset_name: Optional[str] = Field(default=None, description="""""")
+ metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
+ default=None, description=""""""
+ )
+ model_reference: Optional[str] = Field(default=None, description="""""")
+ parent: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[CreateDatasetVersionConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _CreateDatasetVersionParametersDict(TypedDict, total=False):
+ """Represents the create dataset version parameters."""
+
+ dataset_name: Optional[str]
+ """"""
+
+ metadata: Optional[SchemaTextPromptDatasetMetadataDict]
+ """"""
+
+ model_reference: Optional[str]
+ """"""
+
+ parent: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ config: Optional[CreateDatasetVersionConfigDict]
+ """"""
+
+
+_CreateDatasetVersionParametersOrDict = Union[
+ _CreateDatasetVersionParameters, _CreateDatasetVersionParametersDict
+]
+
+
+class _GetDatasetParameters(_common.BaseModel):
+ """Parameters for getting a dataset resource to store prompts."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ config: Optional[VertexBaseConfig] = Field(default=None, description="""""")
+
+
+class _GetDatasetParametersDict(TypedDict, total=False):
+ """Parameters for getting a dataset resource to store prompts."""
+
+ name: Optional[str]
+ """"""
+
+ config: Optional[VertexBaseConfigDict]
+ """"""
+
+
+_GetDatasetParametersOrDict = Union[_GetDatasetParameters, _GetDatasetParametersDict]
+
+
+class SavedQuery(_common.BaseModel):
+ """A SavedQuery is a view of the dataset. It references a subset of annotations by problem type and filters."""
+
+ annotation_filter: Optional[str] = Field(
+ default=None,
+ description="""Output only. Filters on the Annotations in the dataset.""",
+ )
+ annotation_spec_count: Optional[int] = Field(
+ default=None,
+ description="""Output only. Number of AnnotationSpecs in the context of the SavedQuery.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this SavedQuery was created.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Required. The user-defined name of the SavedQuery. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
+ )
+ etag: Optional[str] = Field(
+ default=None,
+ description="""Used to perform a consistent read-modify-write update. If not set, a blind "overwrite" update happens.""",
+ )
+ metadata: Optional[Any] = Field(
+ default=None,
+ description="""Some additional information about the SavedQuery.""",
+ )
+ name: Optional[str] = Field(
+ default=None, description="""Output only. Resource name of the SavedQuery."""
+ )
+ problem_type: Optional[str] = Field(
+ default=None,
+ description="""Required. Problem type of the SavedQuery. Allowed values: * IMAGE_CLASSIFICATION_SINGLE_LABEL * IMAGE_CLASSIFICATION_MULTI_LABEL * IMAGE_BOUNDING_POLY * IMAGE_BOUNDING_BOX * TEXT_CLASSIFICATION_SINGLE_LABEL * TEXT_CLASSIFICATION_MULTI_LABEL * TEXT_EXTRACTION * TEXT_SENTIMENT * VIDEO_CLASSIFICATION * VIDEO_OBJECT_TRACKING""",
+ )
+ support_automl_training: Optional[bool] = Field(
+ default=None,
+ description="""Output only. If the Annotations belonging to the SavedQuery can be used for AutoML training.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when SavedQuery was last updated.""",
+ )
+
+
+class SavedQueryDict(TypedDict, total=False):
+ """A SavedQuery is a view of the dataset. It references a subset of annotations by problem type and filters."""
+
+ annotation_filter: Optional[str]
+ """Output only. Filters on the Annotations in the dataset."""
+
+ annotation_spec_count: Optional[int]
+ """Output only. Number of AnnotationSpecs in the context of the SavedQuery."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this SavedQuery was created."""
+
+ display_name: Optional[str]
+ """Required. The user-defined name of the SavedQuery. The name can be up to 128 characters long and can consist of any UTF-8 characters."""
+
+ etag: Optional[str]
+ """Used to perform a consistent read-modify-write update. If not set, a blind "overwrite" update happens."""
+
+ metadata: Optional[Any]
+ """Some additional information about the SavedQuery."""
+
+ name: Optional[str]
+ """Output only. Resource name of the SavedQuery."""
+
+ problem_type: Optional[str]
+ """Required. Problem type of the SavedQuery. Allowed values: * IMAGE_CLASSIFICATION_SINGLE_LABEL * IMAGE_CLASSIFICATION_MULTI_LABEL * IMAGE_BOUNDING_POLY * IMAGE_BOUNDING_BOX * TEXT_CLASSIFICATION_SINGLE_LABEL * TEXT_CLASSIFICATION_MULTI_LABEL * TEXT_EXTRACTION * TEXT_SENTIMENT * VIDEO_CLASSIFICATION * VIDEO_OBJECT_TRACKING"""
+
+ support_automl_training: Optional[bool]
+ """Output only. If the Annotations belonging to the SavedQuery can be used for AutoML training."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Timestamp when SavedQuery was last updated."""
+
+
+SavedQueryOrDict = Union[SavedQuery, SavedQueryDict]
+
+
+class Dataset(_common.BaseModel):
+ """Represents a dataset resource to store prompts."""
+
+ metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
+ default=None,
+ description="""Required. Additional information about the Dataset.""",
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""Customer-managed encryption key spec for a Dataset. If set, this Dataset and all sub-resources of this Dataset will be secured by this key.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this Dataset was created.""",
+ )
+ data_item_count: Optional[int] = Field(
+ default=None,
+ description="""Output only. The number of DataItems in this Dataset. Only apply for non-structured Dataset.""",
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the Dataset."""
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Required. The user-defined name of the Dataset. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
+ )
+ etag: Optional[str] = Field(
+ default=None,
+ description="""Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The labels with user-defined metadata to organize your Datasets. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. No more than 64 user labels can be associated with one Dataset (System labels are excluded). See https://goo.gl/xmQnxf for more information and examples of labels. System reserved label keys are prefixed with "aiplatform.googleapis.com/" and are immutable. Following system labels exist for each Dataset: * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its value is the metadata_schema's title.""",
+ )
+ metadata_artifact: Optional[str] = Field(
+ default=None,
+ description="""Output only. The resource name of the Artifact that was created in MetadataStore when creating the Dataset. The Artifact resource name pattern is `projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}`.""",
+ )
+ metadata_schema_uri: Optional[str] = Field(
+ default=None,
+ description="""Required. Points to a YAML file stored on Google Cloud Storage describing additional information about the Dataset. The schema is defined as an OpenAPI 3.0.2 Schema Object. The schema files that can be used here are found in gs://google-cloud-aiplatform/schema/dataset/metadata/.""",
+ )
+ model_reference: Optional[str] = Field(
+ default=None,
+ description="""Optional. Reference to the public base model last used by the dataset. Only set for prompt datasets.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Output only. Identifier. The resource name of the Dataset. Format: `projects/{project}/locations/{location}/datasets/{dataset}`""",
+ )
+ satisfies_pzi: Optional[bool] = Field(
+ default=None, description="""Output only. Reserved for future use."""
+ )
+ satisfies_pzs: Optional[bool] = Field(
+ default=None, description="""Output only. Reserved for future use."""
+ )
+ saved_queries: Optional[list[SavedQuery]] = Field(
+ default=None,
+ description="""All SavedQueries belong to the Dataset will be returned in List/Get Dataset response. The annotation_specs field will not be populated except for UI cases which will only use annotation_spec_count. In CreateDataset request, a SavedQuery is created together if this field is set, up to one SavedQuery can be set in CreateDatasetRequest. The SavedQuery should not contain any AnnotationSpec.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this Dataset was last updated.""",
+ )
+
+ # TODO(b/448806531): Remove all the overridden _from_response methods once the
+ # ticket is resolved and published.
+ @classmethod
+ def _from_response(
+ cls: typing.Type["Dataset"],
+ *,
+ response: dict[str, object],
+ kwargs: dict[str, object],
+ ) -> "Dataset":
+ """Converts a dictionary response into a Dataset object."""
+
+ response = _camel_key_to_snake(response)
+ result = super()._from_response(response=response, kwargs=kwargs)
+ return result
+
+
+class DatasetDict(TypedDict, total=False):
+ """Represents a dataset resource to store prompts."""
+
+ metadata: Optional[SchemaTextPromptDatasetMetadataDict]
+ """Required. Additional information about the Dataset."""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """Customer-managed encryption key spec for a Dataset. If set, this Dataset and all sub-resources of this Dataset will be secured by this key."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this Dataset was created."""
+
+ data_item_count: Optional[int]
+ """Output only. The number of DataItems in this Dataset. Only apply for non-structured Dataset."""
+
+ description: Optional[str]
+ """The description of the Dataset."""
+
+ display_name: Optional[str]
+ """Required. The user-defined name of the Dataset. The name can be up to 128 characters long and can consist of any UTF-8 characters."""
+
+ etag: Optional[str]
+ """Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens."""
+
+ labels: Optional[dict[str, str]]
+ """The labels with user-defined metadata to organize your Datasets. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. No more than 64 user labels can be associated with one Dataset (System labels are excluded). See https://goo.gl/xmQnxf for more information and examples of labels. System reserved label keys are prefixed with "aiplatform.googleapis.com/" and are immutable. Following system labels exist for each Dataset: * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its value is the metadata_schema's title."""
+
+ metadata_artifact: Optional[str]
+ """Output only. The resource name of the Artifact that was created in MetadataStore when creating the Dataset. The Artifact resource name pattern is `projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}`."""
+
+ metadata_schema_uri: Optional[str]
+ """Required. Points to a YAML file stored on Google Cloud Storage describing additional information about the Dataset. The schema is defined as an OpenAPI 3.0.2 Schema Object. The schema files that can be used here are found in gs://google-cloud-aiplatform/schema/dataset/metadata/."""
+
+ model_reference: Optional[str]
+ """Optional. Reference to the public base model last used by the dataset. Only set for prompt datasets."""
+
+ name: Optional[str]
+ """Output only. Identifier. The resource name of the Dataset. Format: `projects/{project}/locations/{location}/datasets/{dataset}`"""
+
+ satisfies_pzi: Optional[bool]
+ """Output only. Reserved for future use."""
+
+ satisfies_pzs: Optional[bool]
+ """Output only. Reserved for future use."""
+
+ saved_queries: Optional[list[SavedQueryDict]]
+ """All SavedQueries belong to the Dataset will be returned in List/Get Dataset response. The annotation_specs field will not be populated except for UI cases which will only use annotation_spec_count. In CreateDataset request, a SavedQuery is created together if this field is set, up to one SavedQuery can be set in CreateDatasetRequest. The SavedQuery should not contain any AnnotationSpec."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this Dataset was last updated."""
+
+
+DatasetOrDict = Union[Dataset, DatasetDict]
+
+
+class _GetDatasetVersionParameters(_common.BaseModel):
+ """Parameters for getting a dataset resource to store prompts."""
+
+ dataset_id: Optional[str] = Field(default=None, description="""""")
+ dataset_version_id: Optional[str] = Field(default=None, description="""""")
+ config: Optional[VertexBaseConfig] = Field(default=None, description="""""")
+
+
+class _GetDatasetVersionParametersDict(TypedDict, total=False):
+ """Parameters for getting a dataset resource to store prompts."""
+
+ dataset_id: Optional[str]
+ """"""
+
+ dataset_version_id: Optional[str]
+ """"""
+
+ config: Optional[VertexBaseConfigDict]
+ """"""
+
+
+_GetDatasetVersionParametersOrDict = Union[
+ _GetDatasetVersionParameters, _GetDatasetVersionParametersDict
+]
+
+
+class DatasetVersion(_common.BaseModel):
+ """Represents a dataset version resource to store prompts."""
+
+ metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
+ default=None,
+ description="""Required. Output only. Additional information about the DatasetVersion.""",
+ )
+ big_query_dataset_name: Optional[str] = Field(
+ default=None,
+ description="""Output only. Name of the associated BigQuery dataset.""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this DatasetVersion was created.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""The user-defined name of the DatasetVersion. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
+ )
+ etag: Optional[str] = Field(
+ default=None,
+ description="""Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens.""",
+ )
+ model_reference: Optional[str] = Field(
+ default=None,
+ description="""Output only. Reference to the public base model last used by the dataset version. Only set for prompt dataset versions.""",
+ )
+ name: Optional[str] = Field(
+ default=None,
+ description="""Output only. Identifier. The resource name of the DatasetVersion. Format: `projects/{project}/locations/{location}/datasets/{dataset}/datasetVersions/{dataset_version}`""",
+ )
+ satisfies_pzi: Optional[bool] = Field(
+ default=None, description="""Output only. Reserved for future use."""
+ )
+ satisfies_pzs: Optional[bool] = Field(
+ default=None, description="""Output only. Reserved for future use."""
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this DatasetVersion was last updated.""",
+ )
+
+ # TODO(b/448806531): Remove all the overridden _from_response methods once the
+ # ticket is resolved and published.
+ @classmethod
+ def _from_response(
+ cls: typing.Type["DatasetVersion"],
+ *,
+ response: dict[str, object],
+ kwargs: dict[str, object],
+ ) -> "DatasetVersion":
+ """Converts a dictionary response into a DatasetVersion object."""
+
+ response = _camel_key_to_snake(response)
+ result = super()._from_response(response=response, kwargs=kwargs)
+ return result
+
+
+class DatasetVersionDict(TypedDict, total=False):
+ """Represents a dataset version resource to store prompts."""
+
+ metadata: Optional[SchemaTextPromptDatasetMetadataDict]
+ """Required. Output only. Additional information about the DatasetVersion."""
+
+ big_query_dataset_name: Optional[str]
+ """Output only. Name of the associated BigQuery dataset."""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this DatasetVersion was created."""
+
+ display_name: Optional[str]
+ """The user-defined name of the DatasetVersion. The name can be up to 128 characters long and can consist of any UTF-8 characters."""
+
+ etag: Optional[str]
+ """Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens."""
+
+ model_reference: Optional[str]
+ """Output only. Reference to the public base model last used by the dataset version. Only set for prompt dataset versions."""
+
+ name: Optional[str]
+ """Output only. Identifier. The resource name of the DatasetVersion. Format: `projects/{project}/locations/{location}/datasets/{dataset}/datasetVersions/{dataset_version}`"""
+
+ satisfies_pzi: Optional[bool]
+ """Output only. Reserved for future use."""
+
+ satisfies_pzs: Optional[bool]
+ """Output only. Reserved for future use."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this DatasetVersion was last updated."""
+
+
+DatasetVersionOrDict = Union[DatasetVersion, DatasetVersionDict]
+
+
+class GetDatasetOperationConfig(_common.BaseModel):
+ """Config for getting a dataset version operation."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetDatasetOperationConfigDict(TypedDict, total=False):
+ """Config for getting a dataset version operation."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetDatasetOperationConfigOrDict = Union[
+ GetDatasetOperationConfig, GetDatasetOperationConfigDict
+]
+
+
+class _GetDatasetOperationParameters(_common.BaseModel):
+ """Parameters for getting a dataset operation."""
+
+ dataset_id: Optional[str] = Field(default=None, description="""""")
+ operation_id: Optional[str] = Field(default=None, description="""""")
+ config: Optional[GetDatasetOperationConfig] = Field(
+ default=None, description=""""""
+ )
+
+
+class _GetDatasetOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting a dataset operation."""
+
+ dataset_id: Optional[str]
+ """"""
+
+ operation_id: Optional[str]
+ """"""
+
+ config: Optional[GetDatasetOperationConfigDict]
+ """"""
+
+
+_GetDatasetOperationParametersOrDict = Union[
+ _GetDatasetOperationParameters, _GetDatasetOperationParametersDict
+]
+
+
+class ListPromptsConfig(_common.BaseModel):
+ """Config for listing prompt datasets and dataset versions."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None,
+ description="""An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.""",
+ )
+
+
+class ListPromptsConfigDict(TypedDict, total=False):
+ """Config for listing prompt datasets and dataset versions."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported."""
+
+
+ListPromptsConfigOrDict = Union[ListPromptsConfig, ListPromptsConfigDict]
+
+
+class _ListDatasetsRequestParameters(_common.BaseModel):
+ """Parameters for listing prompt datasets."""
+
+ config: Optional[ListPromptsConfig] = Field(default=None, description="""""")
+
+
+class _ListDatasetsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing prompt datasets."""
+
+ config: Optional[ListPromptsConfigDict]
+ """"""
+
+
+_ListDatasetsRequestParametersOrDict = Union[
+ _ListDatasetsRequestParameters, _ListDatasetsRequestParametersDict
+]
+
+
+class ListDatasetsResponse(_common.BaseModel):
+ """Response for listing prompt datasets."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ datasets: Optional[list[Dataset]] = Field(
+ default=None,
+ description="""List of datasets for the project.
+ """,
+ )
+
+ # TODO(b/448806531): Remove all the overridden _from_response methods once the
+ # ticket is resolved and published.
+ @classmethod
+ def _from_response(
+ cls: typing.Type["ListDatasetsResponse"],
+ *,
+ response: dict[str, object],
+ kwargs: dict[str, object],
+ ) -> "ListDatasetsResponse":
+ """Converts a dictionary response into a ListDatasetsResponse object."""
+
+ response = _camel_key_to_snake(response)
+ result = super()._from_response(response=response, kwargs=kwargs)
+ return result
+
+
+class ListDatasetsResponseDict(TypedDict, total=False):
+ """Response for listing prompt datasets."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ datasets: Optional[list[DatasetDict]]
+ """List of datasets for the project.
+ """
+
+
+ListDatasetsResponseOrDict = Union[ListDatasetsResponse, ListDatasetsResponseDict]
+
+
+class _ListDatasetVersionsRequestParameters(_common.BaseModel):
+ """Parameters for listing dataset versions."""
+
+ read_mask: Optional[str] = Field(default=None, description="""""")
+ dataset_id: Optional[str] = Field(default=None, description="""""")
+ config: Optional[ListPromptsConfig] = Field(default=None, description="""""")
+
+
+class _ListDatasetVersionsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing dataset versions."""
+
+ read_mask: Optional[str]
+ """"""
+
+ dataset_id: Optional[str]
+ """"""
+
+ config: Optional[ListPromptsConfigDict]
+ """"""
+
+
+_ListDatasetVersionsRequestParametersOrDict = Union[
+ _ListDatasetVersionsRequestParameters, _ListDatasetVersionsRequestParametersDict
+]
+
+
+class ListDatasetVersionsResponse(_common.BaseModel):
+ """Response for listing prompt datasets."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ dataset_versions: Optional[list[DatasetVersion]] = Field(
+ default=None,
+ description="""List of datasets for the project.
+ """,
+ )
+
+ # TODO(b/448806531): Remove all the overridden _from_response methods once the
+ # ticket is resolved and published.
+ @classmethod
+ def _from_response(
+ cls: typing.Type["ListDatasetVersionsResponse"],
+ *,
+ response: dict[str, object],
+ kwargs: dict[str, object],
+ ) -> "ListDatasetVersionsResponse":
+ """Converts a dictionary response into a ListDatasetVersionsResponse object."""
+
+ response = _camel_key_to_snake(response)
+ result = super()._from_response(response=response, kwargs=kwargs)
+ return result
+
+
+class ListDatasetVersionsResponseDict(TypedDict, total=False):
+ """Response for listing prompt datasets."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ dataset_versions: Optional[list[DatasetVersionDict]]
+ """List of datasets for the project.
+ """
+
+
+ListDatasetVersionsResponseOrDict = Union[
+ ListDatasetVersionsResponse, ListDatasetVersionsResponseDict
+]
+
+
+class DeletePromptConfig(_common.BaseModel):
+ """Config for deleting a prompt."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""Timeout for the delete prompt operation in seconds. Defaults to 90.""",
+ )
+
+
+class DeletePromptConfigDict(TypedDict, total=False):
+ """Config for deleting a prompt."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ timeout: Optional[int]
+ """Timeout for the delete prompt operation in seconds. Defaults to 90."""
+
+
+DeletePromptConfigOrDict = Union[DeletePromptConfig, DeletePromptConfigDict]
+
+
+class _DeleteDatasetRequestParameters(_common.BaseModel):
+ """Parameters for deleting a prompt dataset."""
+
+ prompt_id: Optional[str] = Field(
+ default=None, description="""ID of the prompt dataset to be deleted."""
+ )
+ config: Optional[DeletePromptConfig] = Field(default=None, description="""""")
+
+
+class _DeleteDatasetRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting a prompt dataset."""
+
+ prompt_id: Optional[str]
+ """ID of the prompt dataset to be deleted."""
+
+ config: Optional[DeletePromptConfigDict]
+ """"""
+
+
+_DeleteDatasetRequestParametersOrDict = Union[
+ _DeleteDatasetRequestParameters, _DeleteDatasetRequestParametersDict
+]
+
+
+class DeletePromptOperation(_common.BaseModel):
+ """Operation for deleting prompts."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeletePromptOperationDict(TypedDict, total=False):
+ """Operation for deleting prompts."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeletePromptOperationOrDict = Union[DeletePromptOperation, DeletePromptOperationDict]
+
+
+class _DeletePromptVersionRequestParameters(_common.BaseModel):
+ """Parameters for deleting a prompt version."""
+
+ prompt_id: Optional[str] = Field(
+ default=None, description="""ID of the prompt to be deleted."""
+ )
+ version_id: Optional[str] = Field(
+ default=None,
+ description="""ID of the prompt version to be deleted within the provided prompt_id.""",
+ )
+ config: Optional[DeletePromptConfig] = Field(default=None, description="""""")
+
+
+class _DeletePromptVersionRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting a prompt version."""
+
+ prompt_id: Optional[str]
+ """ID of the prompt to be deleted."""
+
+ version_id: Optional[str]
+ """ID of the prompt version to be deleted within the provided prompt_id."""
+
+ config: Optional[DeletePromptConfigDict]
+ """"""
+
+
+_DeletePromptVersionRequestParametersOrDict = Union[
+ _DeletePromptVersionRequestParameters, _DeletePromptVersionRequestParametersDict
+]
+
+
+class DeletePromptVersionOperation(_common.BaseModel):
+ """Operation for deleting prompt versions."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeletePromptVersionOperationDict(TypedDict, total=False):
+ """Operation for deleting prompt versions."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeletePromptVersionOperationOrDict = Union[
+ DeletePromptVersionOperation, DeletePromptVersionOperationDict
+]
+
+
+class RestoreVersionConfig(_common.BaseModel):
+ """Config for restoring a prompt version."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class RestoreVersionConfigDict(TypedDict, total=False):
+ """Config for restoring a prompt version."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+RestoreVersionConfigOrDict = Union[RestoreVersionConfig, RestoreVersionConfigDict]
+
+
+class _RestoreVersionRequestParameters(_common.BaseModel):
+ """Parameters for restoring a prompt version."""
+
+ dataset_id: Optional[str] = Field(
+ default=None, description="""ID of the prompt dataset to be restored."""
+ )
+ version_id: Optional[str] = Field(
+ default=None, description="""ID of the prompt dataset version to be restored."""
+ )
+ config: Optional[RestoreVersionConfig] = Field(default=None, description="""""")
+
+
+class _RestoreVersionRequestParametersDict(TypedDict, total=False):
+ """Parameters for restoring a prompt version."""
+
+ dataset_id: Optional[str]
+ """ID of the prompt dataset to be restored."""
+
+ version_id: Optional[str]
+ """ID of the prompt dataset version to be restored."""
+
+ config: Optional[RestoreVersionConfigDict]
+ """"""
+
+
+_RestoreVersionRequestParametersOrDict = Union[
+ _RestoreVersionRequestParameters, _RestoreVersionRequestParametersDict
+]
+
+
+class RestoreVersionOperation(_common.BaseModel):
+ """Represents the restore version operation."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class RestoreVersionOperationDict(TypedDict, total=False):
+ """Represents the restore version operation."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+RestoreVersionOperationOrDict = Union[
+ RestoreVersionOperation, RestoreVersionOperationDict
+]
+
+
+class UpdatePromptConfig(_common.BaseModel):
+ """Config for creating a dataset resource to store prompts."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ prompt_display_name: Optional[str] = Field(
+ default=None, description="""The updated display name for the prompt."""
+ )
+ version_display_name: Optional[str] = Field(
+ default=None,
+ description="""The updated display name for the prompt version. If not set, a default name with a timestamp will be used.""",
+ )
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""The timeout for the update_dataset_resource request in seconds. If not set, the default timeout is 90 seconds.""",
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key.""",
+ )
+
+
+class UpdatePromptConfigDict(TypedDict, total=False):
+ """Config for creating a dataset resource to store prompts."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ prompt_display_name: Optional[str]
+ """The updated display name for the prompt."""
+
+ version_display_name: Optional[str]
+ """The updated display name for the prompt version. If not set, a default name with a timestamp will be used."""
+
+ timeout: Optional[int]
+ """The timeout for the update_dataset_resource request in seconds. If not set, the default timeout is 90 seconds."""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key."""
+
+
+UpdatePromptConfigOrDict = Union[UpdatePromptConfig, UpdatePromptConfigDict]
+
+
+class _UpdateDatasetParameters(_common.BaseModel):
+ """Parameters for creating a dataset resource to store prompts."""
+
+ name: Optional[str] = Field(default=None, description="""""")
+ dataset_id: Optional[str] = Field(default=None, description="""""")
+ display_name: Optional[str] = Field(default=None, description="""""")
+ metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
+ default=None, description=""""""
+ )
+ description: Optional[str] = Field(default=None, description="""""")
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None, description=""""""
+ )
+ model_reference: Optional[str] = Field(default=None, description="""""")
+ config: Optional[UpdatePromptConfig] = Field(default=None, description="""""")
+
+
+class _UpdateDatasetParametersDict(TypedDict, total=False):
+ """Parameters for creating a dataset resource to store prompts."""
+
+ name: Optional[str]
+ """"""
+
+ dataset_id: Optional[str]
+ """"""
+
+ display_name: Optional[str]
+ """"""
+
+ metadata: Optional[SchemaTextPromptDatasetMetadataDict]
+ """"""
+
+ description: Optional[str]
+ """"""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """"""
+
+ model_reference: Optional[str]
+ """"""
+
+ config: Optional[UpdatePromptConfigDict]
+ """"""
+
+
+_UpdateDatasetParametersOrDict = Union[
+ _UpdateDatasetParameters, _UpdateDatasetParametersDict
+]
+
+
+class GetSkillConfig(_common.BaseModel):
+ """Config for getting a skill."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetSkillConfigDict(TypedDict, total=False):
+ """Config for getting a skill."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetSkillConfigOrDict = Union[GetSkillConfig, GetSkillConfigDict]
+
+
+class _GetSkillRequestParameters(_common.BaseModel):
+ """Parameters for GetSkillRequest."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The resource name of the Skill to retrieve. Format: projects/{project}/locations/{location}/skills/{skill}""",
+ )
+ config: Optional[GetSkillConfig] = Field(default=None, description="""""")
+
+
+class _GetSkillRequestParametersDict(TypedDict, total=False):
+ """Parameters for GetSkillRequest."""
+
+ name: Optional[str]
+ """The resource name of the Skill to retrieve. Format: projects/{project}/locations/{location}/skills/{skill}"""
+
+ config: Optional[GetSkillConfigDict]
+ """"""
+
+
+_GetSkillRequestParametersOrDict = Union[
+ _GetSkillRequestParameters, _GetSkillRequestParametersDict
+]
+
+
+class Skill(_common.BaseModel):
+ """Represents a Skill resource.
+
+ Patches the type from the discovery document.
+ """
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the Skill. Format: `projects/{project}/locations/{location}/skills/{skill}`""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this Skill was created.""",
+ )
+ update_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this Skill was most recently updated.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Required. Provides the display name of the Skill. This should align with `name` in the `SKILL.md` file.""",
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="""Required. Describes the Skill. Should describe both what the skill does and when to use it. Should include specific keywords that help agents identify relevant tasks. This should align with `description` in the `SKILL.md` file.""",
+ )
+ license: Optional[str] = Field(
+ default=None,
+ description="""Optional. Specifies the license of the Skill. This should be an SPDX license identifier (e.g., "MIT", "Apache-2.0"). See https://spdx.org/licenses/. This should align with `license` in the `SKILL.md` file.""",
+ )
+ compatibility: Optional[str] = Field(
+ default=None,
+ description="""Optional. Specifies the compatibility of the Skill. Indicates environment requirements (intended product, system packages, network access, etc.). This should align with `compatibility` in the `SKILL.md` file.""",
+ )
+ zipped_filesystem: Optional[str] = Field(
+ default=None,
+ description="""Required. Provides the zipped filesystem of the Skill. This should contain the `SKILL.md` file at the root of the zip and optional directories for scripts, references, and assets. Directory should align with the directory structure specified at https://agentskills.io/specification#directory-structure.""",
+ )
+ state: Optional[SkillState] = Field(
+ default=None, description="""Output only. The state of the Skill."""
+ )
+
+
+class SkillDict(TypedDict, total=False):
+ """Represents a Skill resource.
+
+ Patches the type from the discovery document.
+ """
+
+ name: Optional[str]
+ """Identifier. The resource name of the Skill. Format: `projects/{project}/locations/{location}/skills/{skill}`"""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this Skill was created."""
+
+ update_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this Skill was most recently updated."""
+
+ display_name: Optional[str]
+ """Required. Provides the display name of the Skill. This should align with `name` in the `SKILL.md` file."""
+
+ description: Optional[str]
+ """Required. Describes the Skill. Should describe both what the skill does and when to use it. Should include specific keywords that help agents identify relevant tasks. This should align with `description` in the `SKILL.md` file."""
+
+ license: Optional[str]
+ """Optional. Specifies the license of the Skill. This should be an SPDX license identifier (e.g., "MIT", "Apache-2.0"). See https://spdx.org/licenses/. This should align with `license` in the `SKILL.md` file."""
+
+ compatibility: Optional[str]
+ """Optional. Specifies the compatibility of the Skill. Indicates environment requirements (intended product, system packages, network access, etc.). This should align with `compatibility` in the `SKILL.md` file."""
+
+ zipped_filesystem: Optional[str]
+ """Required. Provides the zipped filesystem of the Skill. This should contain the `SKILL.md` file at the root of the zip and optional directories for scripts, references, and assets. Directory should align with the directory structure specified at https://agentskills.io/specification#directory-structure."""
+
+ state: Optional[SkillState]
+ """Output only. The state of the Skill."""
+
+
+SkillOrDict = Union[Skill, SkillDict]
+
+
+class RetrieveSkillsConfig(_common.BaseModel):
+ """Config for retrieving skills."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ top_k: Optional[int] = Field(
+ default=None,
+ description="""Optional. The maximum number of skills to return. The service may
+ return fewer than this value. If unspecified, at most 10 skills will be
+ returned. The maximum value is 100.
+ """,
+ )
+
+
+class RetrieveSkillsConfigDict(TypedDict, total=False):
+ """Config for retrieving skills."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ top_k: Optional[int]
+ """Optional. The maximum number of skills to return. The service may
+ return fewer than this value. If unspecified, at most 10 skills will be
+ returned. The maximum value is 100.
+ """
+
+
+RetrieveSkillsConfigOrDict = Union[RetrieveSkillsConfig, RetrieveSkillsConfigDict]
+
+
+class _RetrieveSkillsRequestParameters(_common.BaseModel):
+ """Parameters for retrieving skills."""
+
+ query: Optional[str] = Field(
+ default=None, description="""Required. The query to find matching skills."""
+ )
+ config: Optional[RetrieveSkillsConfig] = Field(default=None, description="""""")
+
+
+class _RetrieveSkillsRequestParametersDict(TypedDict, total=False):
+ """Parameters for retrieving skills."""
+
+ query: Optional[str]
+ """Required. The query to find matching skills."""
+
+ config: Optional[RetrieveSkillsConfigDict]
+ """"""
+
+
+_RetrieveSkillsRequestParametersOrDict = Union[
+ _RetrieveSkillsRequestParameters, _RetrieveSkillsRequestParametersDict
+]
+
+
+class RetrievedSkill(_common.BaseModel):
+ """A retrieved skill from semantic search."""
+
+ skill_name: Optional[str] = Field(
+ default=None, description="""The resource name of the skill."""
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the skill."""
+ )
+
+
+class RetrievedSkillDict(TypedDict, total=False):
+ """A retrieved skill from semantic search."""
+
+ skill_name: Optional[str]
+ """The resource name of the skill."""
+
+ description: Optional[str]
+ """The description of the skill."""
+
+
+RetrievedSkillOrDict = Union[RetrievedSkill, RetrievedSkillDict]
+
+
+class RetrieveSkillsResponse(_common.BaseModel):
+ """Response for retrieving skills."""
+
+ retrieved_skills: Optional[list[RetrievedSkill]] = Field(
+ default=None, description="""List of retrieved skills ranked by similarity."""
+ )
+
+
+class RetrieveSkillsResponseDict(TypedDict, total=False):
+ """Response for retrieving skills."""
+
+ retrieved_skills: Optional[list[RetrievedSkillDict]]
+ """List of retrieved skills ranked by similarity."""
+
+
+RetrieveSkillsResponseOrDict = Union[RetrieveSkillsResponse, RetrieveSkillsResponseDict]
+
+
+class CreateSkillConfig(_common.BaseModel):
+ """Config for creating a skill."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Whether to wait for the long running operation to complete.""",
+ )
+ local_path: Optional[str] = Field(
+ default=None,
+ description="""Optional. The local path to the directory containing the Skill to
+ be zipped and uploaded.
+ """,
+ )
+ zipped_filesystem: Optional[Any] = Field(
+ default=None, description="""Optional. The zipped filesystem of the Skill."""
+ )
+ skill_id: Optional[str] = Field(
+ default=None,
+ description="""Optional. The ID to use for the Skill, which will become the final
+ component of the Skill's resource name.
+ """,
+ )
+
+
+class CreateSkillConfigDict(TypedDict, total=False):
+ """Config for creating a skill."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Whether to wait for the long running operation to complete."""
+
+ local_path: Optional[str]
+ """Optional. The local path to the directory containing the Skill to
+ be zipped and uploaded.
+ """
+
+ zipped_filesystem: Optional[Any]
+ """Optional. The zipped filesystem of the Skill."""
+
+ skill_id: Optional[str]
+ """Optional. The ID to use for the Skill, which will become the final
+ component of the Skill's resource name.
+ """
+
+
+CreateSkillConfigOrDict = Union[CreateSkillConfig, CreateSkillConfigDict]
+
+
+class _CreateSkillRequestParameters(_common.BaseModel):
+ """Parameters for creating a skill."""
+
+ display_name: Optional[str] = Field(
+ default=None, description="""Required. The display name of the Skill."""
+ )
+ description: Optional[str] = Field(
+ default=None, description="""Required. The description of the Skill."""
+ )
+ config: Optional[CreateSkillConfig] = Field(default=None, description="""""")
+
+
+class _CreateSkillRequestParametersDict(TypedDict, total=False):
+ """Parameters for creating a skill."""
+
+ display_name: Optional[str]
+ """Required. The display name of the Skill."""
+
+ description: Optional[str]
+ """Required. The description of the Skill."""
+
+ config: Optional[CreateSkillConfigDict]
+ """"""
+
+
+_CreateSkillRequestParametersOrDict = Union[
+ _CreateSkillRequestParameters, _CreateSkillRequestParametersDict
+]
+
+
+class SkillOperation(_common.BaseModel):
+ """Operation that has a skill as a response."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[Skill] = Field(
+ default=None, description="""The created Skill."""
+ )
+
+
+class SkillOperationDict(TypedDict, total=False):
+ """Operation that has a skill as a response."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[SkillDict]
+ """The created Skill."""
+
+
+SkillOperationOrDict = Union[SkillOperation, SkillOperationDict]
+
+
+class UpdateSkillConfig(_common.BaseModel):
+ """Config for updating a skill."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Whether to wait for the long running operation to complete.""",
+ )
+ local_path: Optional[str] = Field(
+ default=None,
+ description="""Optional. The local path to the directory containing the Skill to
+ be zipped and uploaded.
+ """,
+ )
+ display_name: Optional[str] = Field(
+ default=None, description="""Optional. The display name of the Skill."""
+ )
+ description: Optional[str] = Field(
+ default=None, description="""Optional. The description of the Skill."""
+ )
+ zipped_filesystem: Optional[Any] = Field(
+ default=None, description="""Optional. The zipped filesystem of the Skill."""
+ )
+ update_mask: Optional[str] = Field(
+ default=None, description="""Optional. The update mask to apply."""
+ )
+
+
+class UpdateSkillConfigDict(TypedDict, total=False):
+ """Config for updating a skill."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Whether to wait for the long running operation to complete."""
+
+ local_path: Optional[str]
+ """Optional. The local path to the directory containing the Skill to
+ be zipped and uploaded.
+ """
+
+ display_name: Optional[str]
+ """Optional. The display name of the Skill."""
+
+ description: Optional[str]
+ """Optional. The description of the Skill."""
+
+ zipped_filesystem: Optional[Any]
+ """Optional. The zipped filesystem of the Skill."""
+
+ update_mask: Optional[str]
+ """Optional. The update mask to apply."""
+
+
+UpdateSkillConfigOrDict = Union[UpdateSkillConfig, UpdateSkillConfigDict]
+
+
+class _UpdateSkillRequestParameters(_common.BaseModel):
+ """Parameters for updating a skill."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Required. The resource name of the Skill to update.""",
+ )
+ config: Optional[UpdateSkillConfig] = Field(default=None, description="""""")
+
+
+class _UpdateSkillRequestParametersDict(TypedDict, total=False):
+ """Parameters for updating a skill."""
+
+ name: Optional[str]
+ """Required. The resource name of the Skill to update."""
+
+ config: Optional[UpdateSkillConfigDict]
+ """"""
+
+
+_UpdateSkillRequestParametersOrDict = Union[
+ _UpdateSkillRequestParameters, _UpdateSkillRequestParametersDict
+]
+
+
+class ListSkillsConfig(_common.BaseModel):
+ """Config for listing skills."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+ filter: Optional[str] = Field(
+ default=None, description="""Optional. The standard list filter."""
+ )
+
+
+class ListSkillsConfigDict(TypedDict, total=False):
+ """Config for listing skills."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+ filter: Optional[str]
+ """Optional. The standard list filter."""
+
+
+ListSkillsConfigOrDict = Union[ListSkillsConfig, ListSkillsConfigDict]
+
+
+class _ListSkillsRequestParameters(_common.BaseModel):
+ """Parameters for listing skills."""
+
+ config: Optional[ListSkillsConfig] = Field(default=None, description="""""")
+
+
+class _ListSkillsRequestParametersDict(TypedDict, total=False):
+ """Parameters for listing skills."""
+
+ config: Optional[ListSkillsConfigDict]
+ """"""
+
+
+_ListSkillsRequestParametersOrDict = Union[
+ _ListSkillsRequestParameters, _ListSkillsRequestParametersDict
+]
+
+
+class ListSkillsResponse(_common.BaseModel):
+ """Response for listing skills."""
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ skills: Optional[list[Skill]] = Field(
+ default=None, description="""List of Skills."""
+ )
+
+
+class ListSkillsResponseDict(TypedDict, total=False):
+ """Response for listing skills."""
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ skills: Optional[list[SkillDict]]
+ """List of Skills."""
+
+
+ListSkillsResponseOrDict = Union[ListSkillsResponse, ListSkillsResponseDict]
+
+
+class DeleteSkillConfig(_common.BaseModel):
+ """Config for deleting a skill."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Whether to wait for the long running operation to complete.""",
+ )
+
+
+class DeleteSkillConfigDict(TypedDict, total=False):
+ """Config for deleting a skill."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ wait_for_completion: Optional[bool]
+ """Whether to wait for the long running operation to complete."""
+
+
+DeleteSkillConfigOrDict = Union[DeleteSkillConfig, DeleteSkillConfigDict]
+
+
+class _DeleteSkillRequestParameters(_common.BaseModel):
+ """Parameters for deleting a skill."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Required. The resource name of the Skill to delete.""",
+ )
+ config: Optional[DeleteSkillConfig] = Field(default=None, description="""""")
+
+
+class _DeleteSkillRequestParametersDict(TypedDict, total=False):
+ """Parameters for deleting a skill."""
+
+ name: Optional[str]
+ """Required. The resource name of the Skill to delete."""
+
+ config: Optional[DeleteSkillConfigDict]
+ """"""
+
+
+_DeleteSkillRequestParametersOrDict = Union[
+ _DeleteSkillRequestParameters, _DeleteSkillRequestParametersDict
+]
+
+
+class DeleteSkillOperation(_common.BaseModel):
+ """Operation for deleting a skill."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+
+
+class DeleteSkillOperationDict(TypedDict, total=False):
+ """Operation for deleting a skill."""
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+
+DeleteSkillOperationOrDict = Union[DeleteSkillOperation, DeleteSkillOperationDict]
+
+
+class GetSkillOperationConfig(_common.BaseModel):
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetSkillOperationConfigDict(TypedDict, total=False):
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetSkillOperationConfigOrDict = Union[
+ GetSkillOperationConfig, GetSkillOperationConfigDict
+]
+
+
+class _GetSkillOperationParameters(_common.BaseModel):
+ """Parameters for getting an operation."""
+
+ operation_name: Optional[str] = Field(
+ default=None, description="""The server-assigned name for the operation."""
+ )
+ config: Optional[GetSkillOperationConfig] = Field(
+ default=None, description="""Used to override the default configuration."""
+ )
+
+
+class _GetSkillOperationParametersDict(TypedDict, total=False):
+ """Parameters for getting an operation."""
+
+ operation_name: Optional[str]
+ """The server-assigned name for the operation."""
+
+ config: Optional[GetSkillOperationConfigDict]
+ """Used to override the default configuration."""
+
+
+_GetSkillOperationParametersOrDict = Union[
+ _GetSkillOperationParameters, _GetSkillOperationParametersDict
+]
+
+
+class GetSkillRevisionConfig(_common.BaseModel):
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetSkillRevisionConfigDict(TypedDict, total=False):
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetSkillRevisionConfigOrDict = Union[GetSkillRevisionConfig, GetSkillRevisionConfigDict]
+
+
+class _GetSkillRevisionRequestParameters(_common.BaseModel):
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The resource name of the Skill Revision to retrieve. Format: projects/{project}/locations/{location}/skills/{skill}/revisions/{revision}""",
+ )
+ config: Optional[GetSkillRevisionConfig] = Field(default=None, description="""""")
+
+
+class _GetSkillRevisionRequestParametersDict(TypedDict, total=False):
+
+ name: Optional[str]
+ """The resource name of the Skill Revision to retrieve. Format: projects/{project}/locations/{location}/skills/{skill}/revisions/{revision}"""
+
+ config: Optional[GetSkillRevisionConfigDict]
+ """"""
+
+
+_GetSkillRevisionRequestParametersOrDict = Union[
+ _GetSkillRevisionRequestParameters, _GetSkillRevisionRequestParametersDict
+]
+
+
+class SkillRevision(_common.BaseModel):
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Identifier. The resource name of the Skill Revision. Format: `projects/{project}/locations/{location}/skills/{skill}/revisions/{revision}`""",
+ )
+ create_time: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Output only. Timestamp when this Skill Revision was created.""",
+ )
+ skill: Optional[Skill] = Field(
+ default=None,
+ description="""Output only. The state of the Skill at this revision. TODO(b/503772996) Use a different proto for skill data included in skill revision""",
+ )
+ state: Optional[SkillState] = Field(
+ default=None, description="""Output only. The state of the Skill Revision."""
+ )
+
+
+class SkillRevisionDict(TypedDict, total=False):
+
+ name: Optional[str]
+ """Identifier. The resource name of the Skill Revision. Format: `projects/{project}/locations/{location}/skills/{skill}/revisions/{revision}`"""
+
+ create_time: Optional[datetime.datetime]
+ """Output only. Timestamp when this Skill Revision was created."""
+
+ skill: Optional[SkillDict]
+ """Output only. The state of the Skill at this revision. TODO(b/503772996) Use a different proto for skill data included in skill revision"""
+
+ state: Optional[SkillState]
+ """Output only. The state of the Skill Revision."""
+
+
+SkillRevisionOrDict = Union[SkillRevision, SkillRevisionDict]
+
+
+class ListSkillRevisionsConfig(_common.BaseModel):
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ page_size: Optional[int] = Field(default=None, description="""""")
+ page_token: Optional[str] = Field(default=None, description="""""")
+
+
+class ListSkillRevisionsConfigDict(TypedDict, total=False):
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ page_size: Optional[int]
+ """"""
+
+ page_token: Optional[str]
+ """"""
+
+
+ListSkillRevisionsConfigOrDict = Union[
+ ListSkillRevisionsConfig, ListSkillRevisionsConfigDict
+]
+
+
+class _ListSkillRevisionsRequestParameters(_common.BaseModel):
+ """Parameters for ListSkillRevisionsRequest."""
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""Required. The name of the Skill to list revisions for.""",
+ )
+ config: Optional[ListSkillRevisionsConfig] = Field(default=None, description="""""")
+
+
+class _ListSkillRevisionsRequestParametersDict(TypedDict, total=False):
+ """Parameters for ListSkillRevisionsRequest."""
+
+ name: Optional[str]
+ """Required. The name of the Skill to list revisions for."""
+
+ config: Optional[ListSkillRevisionsConfigDict]
+ """"""
+
+
+_ListSkillRevisionsRequestParametersOrDict = Union[
+ _ListSkillRevisionsRequestParameters, _ListSkillRevisionsRequestParametersDict
+]
+
+
+class ListSkillRevisionsResponse(_common.BaseModel):
+
+ sdk_http_response: Optional[genai_types.HttpResponse] = Field(
+ default=None, description="""Used to retain the full HTTP response."""
+ )
+ next_page_token: Optional[str] = Field(default=None, description="""""")
+ skill_revisions: Optional[list[SkillRevision]] = Field(
+ default=None, description="""List of Skill Revisions."""
+ )
+
+
+class ListSkillRevisionsResponseDict(TypedDict, total=False):
+
+ sdk_http_response: Optional[genai_types.HttpResponseDict]
+ """Used to retain the full HTTP response."""
+
+ next_page_token: Optional[str]
+ """"""
+
+ skill_revisions: Optional[list[SkillRevisionDict]]
+ """List of Skill Revisions."""
+
+
+ListSkillRevisionsResponseOrDict = Union[
+ ListSkillRevisionsResponse, ListSkillRevisionsResponseDict
+]
+
+
+class PromptOptimizerConfig(_common.BaseModel):
+ """VAPO Prompt Optimizer Config."""
+
+ config_path: Optional[str] = Field(
+ default=None,
+ description="""The gcs path to the config file, e.g. gs://bucket/config.json.""",
+ )
+ service_account: Optional[str] = Field(
+ default=None,
+ description="""The service account to use for the custom job. Cannot be provided at the same time as service_account_project_number.""",
+ )
+ service_account_project_number: Optional[Union[int, str]] = Field(
+ default=None,
+ description="""The project number used to construct the default service account:{service_account_project_number}-compute@developer.gserviceaccount.comCannot be provided at the same time as "service_account".""",
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Whether to wait for the job tocomplete. Ignored for async jobs.""",
+ )
+ optimizer_job_display_name: Optional[str] = Field(
+ default=None,
+ description="""The display name of the optimization job. If not provided, a display name in the format of "vapo-optimizer-{timestamp}" will be used.""",
+ )
+
+
+class PromptOptimizerConfigDict(TypedDict, total=False):
+ """VAPO Prompt Optimizer Config."""
+
+ config_path: Optional[str]
+ """The gcs path to the config file, e.g. gs://bucket/config.json."""
+
+ service_account: Optional[str]
+ """The service account to use for the custom job. Cannot be provided at the same time as service_account_project_number."""
+
+ service_account_project_number: Optional[Union[int, str]]
+ """The project number used to construct the default service account:{service_account_project_number}-compute@developer.gserviceaccount.comCannot be provided at the same time as "service_account"."""
+
+ wait_for_completion: Optional[bool]
+ """Whether to wait for the job tocomplete. Ignored for async jobs."""
+
+ optimizer_job_display_name: Optional[str]
+ """The display name of the optimization job. If not provided, a display name in the format of "vapo-optimizer-{timestamp}" will be used."""
+
+
+PromptOptimizerConfigOrDict = Union[PromptOptimizerConfig, PromptOptimizerConfigDict]
+
+
+class OptimizeResponse(_common.BaseModel):
+ """Response for the optimize_prompt method."""
+
+ raw_text_response: Optional[str] = Field(default=None, description="""""")
+ parsed_response: Optional["ParsedResponseUnion"] = Field(
+ default=None, description=""""""
+ )
+
+
+class OptimizeResponseDict(TypedDict, total=False):
+ """Response for the optimize_prompt method."""
+
+ raw_text_response: Optional[str]
+ """"""
+
+ parsed_response: Optional["ParsedResponseUnionDict"]
+ """"""
+
+
+OptimizeResponseOrDict = Union[OptimizeResponse, OptimizeResponseDict]
+
+
+class ContentMapContents(_common.BaseModel):
+ """Map of placeholder in metric prompt template to contents of model input."""
+
+ contents: Optional[list[genai_types.Content]] = Field(
+ default=None, description="""Contents of the model input."""
+ )
+
+
+class ContentMapContentsDict(TypedDict, total=False):
+ """Map of placeholder in metric prompt template to contents of model input."""
+
+ contents: Optional[list[genai_types.ContentDict]]
+ """Contents of the model input."""
+
+
+ContentMapContentsOrDict = Union[ContentMapContents, ContentMapContentsDict]
+
+
+class EvaluateMethodConfig(_common.BaseModel):
+ """Optional parameters for the evaluate method."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ dataset_schema: Optional[Literal["GEMINI", "FLATTEN", "OPENAI"]] = Field(
+ default=None,
+ description="""The schema to use for the dataset.
+ If not specified, the dataset schema will be inferred from the first
+ example in the dataset.""",
+ )
+ dest: Optional[str] = Field(
+ default=None, description="""The destination path for the evaluation results."""
+ )
+ evaluation_service_qps: Optional[float] = Field(
+ default=None,
+ description="""The rate limit (queries per second) for calls to the
+ evaluation service. Defaults to 10. Increase this value if your
+ project has a higher EvaluateInstances API quota.""",
+ )
+
+
+class EvaluateMethodConfigDict(TypedDict, total=False):
+ """Optional parameters for the evaluate method."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ dataset_schema: Optional[Literal["GEMINI", "FLATTEN", "OPENAI"]]
+ """The schema to use for the dataset.
+ If not specified, the dataset schema will be inferred from the first
+ example in the dataset."""
+
+ dest: Optional[str]
+ """The destination path for the evaluation results."""
+
+ evaluation_service_qps: Optional[float]
+ """The rate limit (queries per second) for calls to the
+ evaluation service. Defaults to 10. Increase this value if your
+ project has a higher EvaluateInstances API quota."""
+
+
+EvaluateMethodConfigOrDict = Union[EvaluateMethodConfig, EvaluateMethodConfigDict]
+
+
+class EvaluateDatasetConfig(_common.BaseModel):
+ """Config for evaluate instances."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class EvaluateDatasetConfigDict(TypedDict, total=False):
+ """Config for evaluate instances."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+EvaluateDatasetConfigOrDict = Union[EvaluateDatasetConfig, EvaluateDatasetConfigDict]
+
+
+class EvaluateDatasetOperation(_common.BaseModel):
+
+ name: Optional[str] = Field(
+ default=None,
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
+ )
+ metadata: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
+ )
+ done: Optional[bool] = Field(
+ default=None,
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
+ )
+ error: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The error result of the operation in case of failure or cancellation.""",
+ )
+ response: Optional[EvaluationDataset] = Field(default=None, description="""""")
+
+
+class EvaluateDatasetOperationDict(TypedDict, total=False):
+
+ name: Optional[str]
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
+
+ metadata: Optional[dict[str, Any]]
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
+
+ done: Optional[bool]
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
+
+ error: Optional[dict[str, Any]]
+ """The error result of the operation in case of failure or cancellation."""
+
+ response: Optional[EvaluationDatasetDict]
+ """"""
+
+
+EvaluateDatasetOperationOrDict = Union[
+ EvaluateDatasetOperation, EvaluateDatasetOperationDict
+]
+
+
+class EvaluateDatasetRequestParameters(_common.BaseModel):
+ """Parameters for batch dataset evaluation."""
+
+ dataset: Optional[EvaluationDataset] = Field(default=None, description="""""")
+ metrics: Optional[list[Metric]] = Field(default=None, description="""""")
+ output_config: Optional[genai_types.OutputConfig] = Field(
+ default=None, description=""""""
+ )
+ autorater_config: Optional[genai_types.AutoraterConfig] = Field(
+ default=None, description=""""""
+ )
+ config: Optional[EvaluateDatasetConfig] = Field(default=None, description="""""")
+
+
+class EvaluateDatasetRequestParametersDict(TypedDict, total=False):
+ """Parameters for batch dataset evaluation."""
+
+ dataset: Optional[EvaluationDatasetDict]
+ """"""
+
+ metrics: Optional[list[MetricDict]]
+ """"""
+
+ output_config: Optional[genai_types.OutputConfigDict]
+ """"""
+
+ autorater_config: Optional[genai_types.AutoraterConfigDict]
+ """"""
+
+ config: Optional[EvaluateDatasetConfigDict]
+ """"""
+
+
+EvaluateDatasetRequestParametersOrDict = Union[
+ EvaluateDatasetRequestParameters, EvaluateDatasetRequestParametersDict
+]
+
+
+class ObservabilityEvalCase(_common.BaseModel):
+ """A single evaluation case instance for data stored in GCP Observability."""
+
+ input_src: Optional[str] = Field(
+ default=None,
+ description="""String containing the GCS reference to the GenAI input content.""",
+ )
+ output_src: Optional[str] = Field(
+ default=None,
+ description="""String containing the GCS reference to the GenAI response content.""",
+ )
+ system_instruction_src: Optional[str] = Field(
+ default=None,
+ description="""An optional string containing the GCS reference to the GenAI system instruction.""",
+ )
+ api_client: Optional[Any] = Field(
+ default=None, description="""The underlying API client."""
+ )
+
+
+class ObservabilityEvalCaseDict(TypedDict, total=False):
+ """A single evaluation case instance for data stored in GCP Observability."""
+
+ input_src: Optional[str]
+ """String containing the GCS reference to the GenAI input content."""
+
+ output_src: Optional[str]
+ """String containing the GCS reference to the GenAI response content."""
+
+ system_instruction_src: Optional[str]
+ """An optional string containing the GCS reference to the GenAI system instruction."""
+
+ api_client: Optional[Any]
+ """The underlying API client."""
+
+
+ObservabilityEvalCaseOrDict = Union[ObservabilityEvalCase, ObservabilityEvalCaseDict]
+
+
+class RubricGroup(_common.BaseModel):
+ """A group of rubrics.
+
+ Used for grouping rubrics based on a metric or a version.
+ """
+
+ group_id: Optional[str] = Field(
+ default=None, description="""Unique identifier for the group."""
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""Human-readable name for the group. This should be unique
+ within a given context if used for display or selection.
+ Example: "Instruction Following V1", "Content Quality - Summarization
+ Task".""",
+ )
+ rubrics: Optional[list[evals_types.Rubric]] = Field(
+ default=None, description="""Rubrics that are part of this group."""
+ )
+
+
+class RubricGroupDict(TypedDict, total=False):
+ """A group of rubrics.
+
+ Used for grouping rubrics based on a metric or a version.
+ """
+
+ group_id: Optional[str]
+ """Unique identifier for the group."""
+
+ display_name: Optional[str]
+ """Human-readable name for the group. This should be unique
+ within a given context if used for display or selection.
+ Example: "Instruction Following V1", "Content Quality - Summarization
+ Task"."""
+
+ rubrics: Optional[list[evals_types.Rubric]]
+ """Rubrics that are part of this group."""
+
+
+RubricGroupOrDict = Union[RubricGroup, RubricGroupDict]
+
+
+class PromptTemplate(_common.BaseModel):
+ """A prompt template for creating prompts with variables."""
+
+ text: Optional[str] = Field(
+ default=None, description="""The prompt template text."""
+ )
+ _VARIABLE_NAME_REGEX: ClassVar[str] = r"\{([_a-zA-Z][_a-zA-Z0-9]*)\}"
+
+ @field_validator("text")
+ @classmethod
+ def text_must_not_be_empty(cls, value: str) -> str:
+ if not value.strip():
+ raise ValueError(
+ "Prompt template text cannot be empty or consist only of" " whitespace."
+ )
+ return value
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def variables(self) -> set[str]:
+ return set(re.findall(self._VARIABLE_NAME_REGEX, self.text))
+
+ def _split_template_by_variables(self) -> list[Tuple[str, str]]:
+ parts = []
+ last_end = 0
+ for match in re.finditer(self._VARIABLE_NAME_REGEX, self.text):
+ start, end = match.span()
+ var_name = match.group(1)
+ if start > last_end and self.text:
+ parts.append(("text", self.text[last_end:start]))
+ parts.append(("var", var_name))
+ last_end = end
+ if last_end < len(self.text) and self.text:
+ parts.append(("text", self.text[last_end:]))
+ return parts
+
+ def _merge_adjacent_text_parts(
+ self, parts: list[genai_types.Part]
+ ) -> list[genai_types.Part]:
+ if not parts:
+ return []
+
+ merged = []
+ current_text_buffer = []
+
+ for part in parts:
+ is_purely_text = part.text is not None and all(
+ getattr(part, field) is None
+ for field in part.model_fields
+ if field != "text"
+ )
+
+ if is_purely_text:
+ current_text_buffer.append(part.text)
+ else:
+ if current_text_buffer:
+ merged.append(genai_types.Part(text="".join(current_text_buffer)))
+ current_text_buffer = []
+ merged.append(part)
+
+ if current_text_buffer:
+ merged.append(genai_types.Part(text="".join(current_text_buffer)))
+
+ return merged
+
+ def _is_multimodal_json_string(
+ self,
+ value: Any,
+ ) -> bool:
+ """Checks if the input value is a multimodal JSON string."""
+ if not isinstance(value, str):
+ return False
+ try:
+ data = json.loads(value)
+ # Check for the specific structure: {"contents": [{"parts": [...]}]}
+ # or {"parts": [...]} if assemble returns a single Content JSON
+ if isinstance(data, dict):
+ if "contents" in data and isinstance(data["contents"], list):
+ if not data["contents"]:
+ return False
+ first_content = data["contents"][0]
+ if isinstance(first_content, dict) and "parts" in first_content:
+ try:
+ genai_types.Content.model_validate(first_content)
+ return True
+ except ValueError:
+ return False
+ # Adding a check if 'data' itself is a Content-like object with parts
+ elif "parts" in data and isinstance(data["parts"], list):
+ try:
+ genai_types.Content.model_validate(data)
+ return True
+ except ValueError:
+ return False
+ return False
+ except json.JSONDecodeError:
+ return False
+
+ def _parse_multimodal_json_string_into_parts(
+ self,
+ value: str,
+ ) -> list[genai_types.Part]:
+ """Parses a multimodal JSON string and returns its list of Parts."""
+ try:
+ content = genai_types.Content.model_validate_json(value)
+ return content.parts if content.parts is not None else [genai_types.Part()]
+ except Exception:
+ return [genai_types.Part(text=value)]
+
+ def assemble(self, **kwargs: Any) -> str:
+ """Assembles the prompt template with the given keyword arguments.
+
+ Supports both text and multimodal content. The `assemble` method
+ substitutes variables from the prompt template text with provided
+ values.
+
+ Key Behaviors of `assemble()`:
+ 1. Variable Substitution: Replaces all defined variables with their
+ corresponding keyword argument values. Raises ValueError if a
+ template
+ variable is missing a value or if an extraneous kwarg is provided.
+ 2. Multimodal Handling:
+ - Detects if any variable's value is a JSON string representing
+ multimodal content (specifically, `{"contents": [{"parts": [...]}]}`
+ or `{"role": "user", "parts": [...]}`).
+ - If multimodal content is detected for a variable, its `Part`
+ objects
+ are extracted and inserted into the assembled sequence.
+ - Text segments from the template and simple text variable values
+ become `Part(text=...)`.
+ 3. Output Format:
+ - If ALL substituted variables were simple text AND the assembled
+ result (after merging adjacent text parts) consists of a single,
+ purely textual `Part`, `assemble()` returns a raw Python string.
+ - Otherwise (if any variable was multimodal, or if the assembly
+ results in multiple parts or non-textual parts), `assemble()`
+ returns
+ a JSON string representing a single `google.genai.types.Content`
+ object with `role="user"` and the assembled parts.
+ 4. Text Part Merging: Consecutively assembled text parts are
+ automatically merged into a single text `Part` to create a more
+ concise list of parts.
+
+ This dual output format (raw string or JSON string of `Content`) allows
+ the downstream inference functions to seamlessly handle both simple text
+ prompts and more complex multimodal prompts generated from the same
+ templating mechanism.
+ """
+ current_variables = self.variables
+ for var_name_in_kwarg in kwargs:
+ if var_name_in_kwarg not in current_variables:
+ raise ValueError(
+ f"Invalid variable name '{var_name_in_kwarg}' provided to"
+ " assemble. Valid variables in template are:"
+ f" {current_variables}"
+ )
+ # Check if all template variables are provided in kwargs
+ for tpl_var in current_variables:
+ if tpl_var not in kwargs:
+ raise ValueError(f"Missing value for template variable '{tpl_var}'.")
+
+ template_segments = self._split_template_by_variables()
+
+ raw_assembled_parts: list[genai_types.Part] = []
+ contains_multimodal_variable_type = False
+
+ for segment_type, segment_value in template_segments:
+ if segment_type == "text":
+ if segment_value:
+ raw_assembled_parts.append(genai_types.Part(text=segment_value))
+ elif segment_type == "var":
+ var_value = kwargs.get(segment_value)
+
+ str_var_value = str(var_value)
+
+ if self._is_multimodal_json_string(str_var_value):
+ multimodal_parts = self._parse_multimodal_json_string_into_parts(
+ str_var_value
+ )
+ if multimodal_parts:
+ contains_multimodal_variable_type = True
+ raw_assembled_parts.extend(multimodal_parts)
+ else:
+ raw_assembled_parts.append(genai_types.Part(text=str_var_value))
+ else:
+ raw_assembled_parts.append(genai_types.Part(text=str_var_value))
+
+ final_assembled_parts = self._merge_adjacent_text_parts(raw_assembled_parts)
+
+ # Condition for returning raw text string:
+ # 1. No multimodal variable was *originally* a multimodal JSON string.
+ # 2. After merging, there's exactly one part.
+ # 3. That single part is purely textual.
+ if (
+ not contains_multimodal_variable_type
+ and len(final_assembled_parts) == 1
+ and final_assembled_parts[0].text is not None
+ and all(
+ getattr(final_assembled_parts[0], field) is None
+ for field in final_assembled_parts[0].model_fields
+ if field not in ["text", "role"]
+ )
+ ):
+ return final_assembled_parts[0].text
+
+ # Otherwise, construct a Content object (as JSON string).
+ final_content_obj = genai_types.Content(parts=final_assembled_parts)
+ return final_content_obj.model_dump_json(exclude_none=True)
+
+ def __str__(self) -> str:
+ return self.text if self.text else ""
+
+ def __repr__(self) -> str:
+ return f"PromptTemplate(text='{self.text}')"
+
+
+class MetricPromptBuilder(PromptTemplate):
+ """Builder class for structured LLM-based metric prompt template."""
+
+ criteria: Optional[dict[str, str]] = Field(
+ None,
+ description="""A dictionary of criteria used to evaluate the model responses.
+ The keys are criterion names, and the values are the corresponding
+ criterion definitions.
+ """,
+ )
+
+ rating_scores: Optional[dict[str, str]] = Field(
+ None,
+ description="""A dictionary mapping of rating score names to their definitions.""",
+ )
+
+ @staticmethod
+ def _get_default_instruction() -> str:
+ """Returns the default instruction for evaluation."""
+ return (
+ "You are an expert evaluator. Your task is to evaluate the quality"
+ " of the responses generated by AI models. We will provide you with"
+ " the user prompt and an AI-generated responses.\nYou should first"
+ " read the user input carefully for analyzing the task, and then"
+ " evaluate the quality of the responses based on the Criteria"
+ " provided in the Evaluation section below.\nYou will assign the"
+ " response a rating following the Rating Scores and Evaluation"
+ " Steps. Give step by step explanations for your rating, and only"
+ " choose ratings from the Rating Scores."
+ )
+
+ instruction: Optional[str] = Field(
+ default_factory=lambda: MetricPromptBuilder._get_default_instruction(),
+ description="""The general instruction to guide the model in performing the evaluation.
+ If not provided, a default instruction for evaluation will be used.
+ """,
+ )
+
+ metric_definition: Optional[str] = Field(
+ None,
+ description="""An optional high-level description of the metric to be evaluated.
+ If not provided, this field will not be included in the prompt template.
+ """,
+ )
+
+ @staticmethod
+ def _get_default_evaluation_steps() -> dict[str, str]:
+ """Returns the default evaluation steps for metric evaluation."""
+ return {
+ "Step 1": (
+ "Assess the response in aspects of all criteria provided. Provide"
+ " assessment according to each criterion."
+ ),
+ "Step 2": (
+ "Score based on the Rating Scores. Give a brief rationale to"
+ " explain your evaluation considering each individual criterion."
+ ),
+ }
+
+ evaluation_steps: Optional[dict[str, str]] = Field(
+ default_factory=lambda: MetricPromptBuilder._get_default_evaluation_steps(),
+ description="""An optional dictionary of evaluation steps.
+ The keys are the names of the evaluation steps, and the values are
+ descriptions of the corresponding evaluation steps. If not provided,
+ default metric evaluation steps will be used.
+ """,
+ )
+
+ few_shot_examples: Optional[list[str]] = Field(
+ None,
+ description="""An optional list of few-shot examples to guide the model's evaluation.
+ These examples demonstrate how to apply the criteria, rating scores,
+ and evaluation steps to assess model responses. Providing few-shot examples
+ can improve the accuracy of the evaluation. If not provided, this field
+ will not be included in the prompt template.
+ """,
+ )
+
+ @staticmethod
+ def _serialize_dict_in_order(elements: Optional[dict[str, str]]) -> str:
+ """Serializes dictionary to ordered string value without brackets."""
+ if elements is None:
+ return ""
+ return "\n".join(f"{key}: {value}" for key, value in sorted(elements.items()))
+
+ @model_validator(mode="before")
+ @classmethod
+ def _prepare_fields_and_construct_text(cls, data: Any) -> Any:
+ """Pydantic model validator (before mode) to prepare and construct prompt text.
+
+ This validator performs the following actions:
+ 1. Apply default logic for fields (instruction, evaluation_steps).
+ 2. Construct the 'text' string from all components.
+ 3. Ensure 'text' is in the data dictionary for PromptTemplate
+ initialization.
+
+ Args:
+ data: Input data for the model, either a dictionary or an existing model
+ instance.
+
+ Returns:
+ Processed data dictionary with the 'text' field constructed.
+ """
+ if not isinstance(data, dict):
+ return data
+
+ if "text" in data:
+ raise ValueError(
+ "The 'text' field is automatically constructed and should not be"
+ " provided manually."
+ )
+
+ if data.get("criteria") is None or data.get("rating_scores") is None:
+ raise ValueError(
+ "Both 'criteria' and 'rating_scores' are required to construct the"
+ "LLM-based metric prompt template text."
+ )
+
+ instruction = data.get("instruction", cls._get_default_instruction())
+ metric_definition = data.get("metric_definition")
+ evaluation_steps = data.get(
+ "evaluation_steps", cls._get_default_evaluation_steps()
+ )
+ criteria = data.get("criteria")
+ rating_scores = data.get("rating_scores")
+ few_shot_examples = data.get("few_shot_examples")
+
+ template_parts = [
+ "# Instruction",
+ instruction,
+ "\n",
+ "# Evaluation",
+ ]
+
+ sections = {
+ "Metric Definition": metric_definition,
+ "Criteria": cls._serialize_dict_in_order(criteria),
+ "Rating Scores": cls._serialize_dict_in_order(rating_scores),
+ "Evaluation Steps": cls._serialize_dict_in_order(evaluation_steps),
+ "Evaluation Examples": (
+ "\n".join(few_shot_examples) if few_shot_examples else None
+ ),
+ }
+
+ for title, content in sections.items():
+ if content:
+ template_parts.extend([f"## {title}", f"{content}\n"])
+
+ template_parts.extend(
+ [
+ "\n",
+ "# User Inputs and AI-generated Response",
+ "## User Prompt",
+ "{prompt}",
+ "\n",
+ "## AI-generated Response",
+ "{response}",
+ ]
+ )
+
+ constructed_text = "\n".join(template_parts)
+
+ data["text"] = constructed_text
+ return data
+
+ def __str__(self) -> str:
+ """Returns the fully constructed prompt template text."""
+ return self.text if self.text else ""
+
+
+class PromptTemplateDict(TypedDict, total=False):
+ """A prompt template for creating prompts with variables."""
+
+ text: Optional[str]
+ """The prompt template text."""
+
+
+PromptTemplateOrDict = Union[PromptTemplate, PromptTemplateDict]
+
+
+class EvalRunInferenceConfig(_common.BaseModel):
+ """Optional parameters for inference."""
+
+ dest: Optional[str] = Field(
+ default=None, description="""The destination path for the inference results."""
+ )
+ prompt_template: Optional[Union[str, PromptTemplate]] = Field(
+ default=None, description="""The prompt template to use for inference."""
+ )
+ generate_content_config: Optional[genai_types.GenerateContentConfig] = Field(
+ default=None, description="""The config for the generate content call."""
+ )
+ user_simulator_config: Optional[evals_types.UserSimulatorConfig] = Field(
+ default=None,
+ description="""Configuration for user simulation in multi-turn agent scraping. If provided, and the dataset contains
+ conversation plans, user simulation will be triggered.""",
+ )
+ allow_cross_region_model: Optional[bool] = Field(
+ default=None,
+ description="""Opt-in flag to authorize cross-region routing for LLM models.""",
+ )
+
+
+class EvalRunInferenceConfigDict(TypedDict, total=False):
+ """Optional parameters for inference."""
+
+ dest: Optional[str]
+ """The destination path for the inference results."""
+
+ prompt_template: Optional[Union[str, PromptTemplateDict]]
+ """The prompt template to use for inference."""
+
+ generate_content_config: Optional[genai_types.GenerateContentConfigDict]
+ """The config for the generate content call."""
+
+ user_simulator_config: Optional[evals_types.UserSimulatorConfig]
+ """Configuration for user simulation in multi-turn agent scraping. If provided, and the dataset contains
+ conversation plans, user simulation will be triggered."""
+
+ allow_cross_region_model: Optional[bool]
+ """Opt-in flag to authorize cross-region routing for LLM models."""
+
+
+EvalRunInferenceConfigOrDict = Union[EvalRunInferenceConfig, EvalRunInferenceConfigDict]
+
+
+class AgentEngine(_common.BaseModel):
+ """An agent engine instance."""
+
+ api_client: Optional[Any] = Field(
+ default=None, description="""The underlying API client."""
+ )
+ api_async_client: Optional[Any] = Field(
+ default=None,
+ description="""The underlying API client for asynchronous operations.""",
+ )
+ api_resource: Optional[ReasoningEngine] = Field(
+ default=None,
+ description="""The underlying API resource (i.e. ReasoningEngine).""",
+ )
+
+ # Allows dynamic binding of methods based on the registered operations.
+ model_config = ConfigDict(extra="allow")
+
+ def __repr__(self) -> str:
+ return (
+ f"AgentEngine(api_resource.name='{self.api_resource.name}')"
+ if self.api_resource is not None
+ else "AgentEngine(api_resource.name=None)"
+ )
+
+ def operation_schemas(self) -> Optional[list[Dict[str, Any]]]:
+ """Returns the schemas of all registered operations for the agent."""
+ if not isinstance(self.api_resource, ReasoningEngine):
+ raise ValueError("api_resource is not initialized.")
+ if not self.api_resource.spec:
+ raise ValueError("api_resource.spec is not initialized.")
+ return self.api_resource.spec.class_methods
+
+ def delete(
+ self,
+ force: bool = False,
+ config: Optional[DeleteAgentEngineConfigOrDict] = None,
+ ) -> None:
+ """Deletes the agent engine.
+
+ Args:
+ force (bool):
+ Optional. If set to True, child resources will also be deleted.
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
+ the Agent Engine has undeleted child resources. Defaults to False.
+ config (DeleteAgentEngineConfig):
+ Optional. Additional configurations for deleting the Agent Engine.
+ """
+ if not isinstance(self.api_resource, ReasoningEngine):
+ raise ValueError("api_resource is not initialized.")
+ self.api_client.delete(name=self.api_resource.name, force=force, config=config) # type: ignore[union-attr]
+
+
+RubricContentProperty = evals_types.RubricContentProperty
+RubricContentPropertyDict = evals_types.RubricContentPropertyDict
+RubricContentPropertyDictOrDict = evals_types.RubricContentPropertyOrDict
+
+RubricContent = evals_types.RubricContent
+RubricContentDict = evals_types.RubricContentDict
+RubricContentDictOrDict = evals_types.RubricContentOrDict
+
+Rubric = evals_types.Rubric
+RubricDict = evals_types.RubricDict
+RubricDictOrDict = evals_types.RubricOrDict
+
+RubricVerdict = evals_types.RubricVerdict
+RubricVerdictDict = evals_types.RubricVerdictDict
+RubricVerdictDictOrDict = evals_types.RubricVerdictOrDict
+
+CandidateResult = evals_types.CandidateResult
+CandidateResultDict = evals_types.CandidateResultDict
+CandidateResultDictOrDict = evals_types.CandidateResultOrDict
+
+Event = evals_types.Event
+EventDict = evals_types.EventDict
+EventDictOrDict = evals_types.EventOrDict
+
+Message = evals_types.Message
+MessageDict = evals_types.MessageDict
+MessageDictOrDict = evals_types.MessageOrDict
+
+Importance = evals_types.Importance
+
+
+class AgentEngineDict(TypedDict, total=False):
+ """An agent engine instance."""
+
+ api_client: Optional[Any]
+ """The underlying API client."""
+
+ api_async_client: Optional[Any]
+ """The underlying API client for asynchronous operations."""
+
+ api_resource: Optional[ReasoningEngineDict]
+ """The underlying API resource (i.e. ReasoningEngine)."""
+
+
+AgentEngineOrDict = Union[AgentEngine, AgentEngineDict]
+
+
+class AgentEngineConfig(_common.BaseModel):
+ """Config for agent engine methods."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ staging_bucket: Optional[str] = Field(
+ default=None,
+ description="""The GCS bucket to use for staging the artifacts needed.
+
+ It must be a valid GCS bucket name, e.g. "gs://bucket-name". It is
+ required if `agent_engine` is specified.""",
+ )
+ requirements: Optional[Any] = Field(
+ default=None,
+ description="""The set of PyPI dependencies needed.
+
+ It can either be the path to a single file (requirements.txt), or an
+ ordered list of strings corresponding to each line of the requirements
+ file.""",
+ )
+ display_name: Optional[str] = Field(
+ default=None,
+ description="""The user-defined name of the Agent Engine.
+
+ The name can be up to 128 characters long and can comprise any UTF-8
+ character.""",
+ )
+ description: Optional[str] = Field(
+ default=None, description="""The description of the Agent Engine."""
+ )
+ gcs_dir_name: Optional[str] = Field(
+ default=None,
+ description="""The GCS bucket directory under `staging_bucket` to use for staging
+ the artifacts needed.""",
+ )
+ extra_packages: Optional[list[str]] = Field(
+ default=None,
+ description="""The set of extra user-provided packages (if any).""",
+ )
+ env_vars: Optional[Any] = Field(
+ default=None,
+ description="""The environment variables to be set when running the Agent Engine.
+
+ If it is a dictionary, the keys are the environment variable names, and
+ the values are the corresponding values.""",
+ )
+ service_account: Optional[str] = Field(
+ default=None,
+ description="""The service account to be used for the Agent Engine.
+
+ If not specified, the default Reasoning Engine P6SA service agent will be used.""",
+ )
+ identity_type: Optional[IdentityType] = Field(
+ default=None, description="""The identity type to use for the Agent Engine."""
+ )
+ context_spec: Optional[ReasoningEngineContextSpec] = Field(
+ default=None,
+ description="""The context spec to be used for the Agent Engine.""",
+ )
+ psc_interface_config: Optional[PscInterfaceConfig] = Field(
+ default=None,
+ description="""The PSC interface config for PSC-I to be used for the Agent Engine.""",
+ )
+ min_instances: Optional[int] = Field(
+ default=None,
+ description="""The minimum number of instances to run for the Agent Engine.
+ Defaults to 1. Range: [0, 10].
+ """,
+ )
+ max_instances: Optional[int] = Field(
+ default=None,
+ description="""The maximum number of instances to run for the Agent Engine.
+ Defaults to 100. Range: [1, 1000].
+ If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
+ """,
+ )
+ resource_limits: Optional[dict[str, str]] = Field(
+ default=None,
+ description="""The resource limits to be applied to the Agent Engine.
+ Required keys: 'cpu' and 'memory'.
+ Supported values for 'cpu': '1', '2', '4', '6', '8'.
+ Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
+ """,
+ )
+ container_concurrency: Optional[int] = Field(
+ default=None,
+ description="""The container concurrency to be used for the Agent Engine.
+ Recommended value: 2 * cpu + 1. Defaults to 9.
+ """,
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""The encryption spec to be used for the Agent Engine.""",
+ )
+ labels: Optional[dict[str, str]] = Field(
+ default=None, description="""The labels to be used for the Agent Engine."""
+ )
+ agent_server_mode: Optional[AgentServerMode] = Field(
+ default=None, description="""The agent server mode to use for deployment."""
+ )
+ class_methods: Optional[list[dict[str, Any]]] = Field(
+ default=None,
+ description="""The class methods to be used for the Agent Engine.
+ If specified, they'll override the class methods that are autogenerated by
+ default. By default, methods are generated by inspecting the agent object
+ and generating a corresponding method for each method defined on the
+ agent class.
+ """,
+ )
+ source_packages: Optional[list[str]] = Field(
+ default=None,
+ description="""The user-provided paths to the source packages (if any).
+ If specified, the files in the source packages will be packed into a
+ a tarball file, uploaded to Agent Engine's API, and deployed to the
+ Agent Engine.
+ The following fields will be ignored:
+ - agent
+ - extra_packages
+ - staging_bucket
+ - requirements
+ The following fields will be used to install and use the agent from the
+ source packages:
+ - entrypoint_module (required)
+ - entrypoint_object (required)
+ - requirements_file (optional)
+ - class_methods (required)
+ """,
+ )
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfig
+ ] = Field(
+ default=None,
+ description="""Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect. This includes the repository, revision, and directory to use.""",
+ )
+ entrypoint_module: Optional[str] = Field(
+ default=None,
+ description="""The entrypoint module to be used for the Agent Engine
+ This field only used when source_packages is specified.""",
+ )
+ entrypoint_object: Optional[str] = Field(
+ default=None,
+ description="""The entrypoint object to be used for the Agent Engine.
+ This field only used when source_packages is specified.""",
+ )
+ requirements_file: Optional[str] = Field(
+ default=None,
+ description="""The user-provided path to the requirements file (if any).
+ This field is only used when source_packages is specified.
+ If not specified, agent engine will find and use the `requirements.txt` in
+ the source package.
+ """,
+ )
+ agent_framework: Optional[
+ Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
+ ] = Field(
+ default=None,
+ description="""The agent framework to be used for the Agent Engine.
+ The OSS agent framework used to develop the agent.
+ Currently supported values: "google-adk", "langchain", "langgraph",
+ "ag2", "llama-index", "custom".
+ If not specified:
+ - If `agent` is specified, the agent framework will be auto-detected.
+ - If `source_packages` is specified, the agent framework will
+ default to "custom".""",
+ )
+ python_version: Optional[Literal["3.10", "3.11", "3.12", "3.13", "3.14"]] = Field(
+ default=None,
+ description="""The Python version to be used for the Agent Engine.
+ If not specified, it will use the current Python version of the environment.
+ Supported versions: "3.10", "3.11", "3.12", "3.13", "3.14".
+ """,
+ )
+ build_options: Optional[dict[str, list[str]]] = Field(
+ default=None,
+ description="""The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ """,
+ )
+ image_spec: Optional[ReasoningEngineSpecSourceCodeSpecImageSpec] = Field(
+ default=None, description="""The image spec for the Agent Engine."""
+ )
+ agent_config_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSource
+ ] = Field(
+ default=None, description="""The agent config source for the Agent Engine."""
+ )
+ container_spec: Optional[ReasoningEngineSpecContainerSpec] = Field(
+ default=None, description="""The container spec for the Agent Engine."""
+ )
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfig
+ ] = Field(
+ default=None,
+ description="""Agent Gateway configuration for a Reasoning Engine deployment.""",
+ )
+ keep_alive_probe: Optional[KeepAliveProbe] = Field(
+ default=None,
+ description="""Optional. Specifies the configuration for keep-alive probe.
+ Contains configuration on a specified endpoint that a deployment host
+ should use to keep the container alive based on the probe settings.""",
+ )
+ traffic_config: Optional[ReasoningEngineTrafficConfig] = Field(
+ default=None, description="""The traffic config for the Agent Engine."""
+ )
+
+
+class AgentEngineConfigDict(TypedDict, total=False):
+ """Config for agent engine methods."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ staging_bucket: Optional[str]
+ """The GCS bucket to use for staging the artifacts needed.
+
+ It must be a valid GCS bucket name, e.g. "gs://bucket-name". It is
+ required if `agent_engine` is specified."""
+
+ requirements: Optional[Any]
+ """The set of PyPI dependencies needed.
+
+ It can either be the path to a single file (requirements.txt), or an
+ ordered list of strings corresponding to each line of the requirements
+ file."""
+
+ display_name: Optional[str]
+ """The user-defined name of the Agent Engine.
+
+ The name can be up to 128 characters long and can comprise any UTF-8
+ character."""
+
+ description: Optional[str]
+ """The description of the Agent Engine."""
+
+ gcs_dir_name: Optional[str]
+ """The GCS bucket directory under `staging_bucket` to use for staging
+ the artifacts needed."""
+
+ extra_packages: Optional[list[str]]
+ """The set of extra user-provided packages (if any)."""
+
+ env_vars: Optional[Any]
+ """The environment variables to be set when running the Agent Engine.
+
+ If it is a dictionary, the keys are the environment variable names, and
+ the values are the corresponding values."""
+
+ service_account: Optional[str]
+ """The service account to be used for the Agent Engine.
+
+ If not specified, the default Reasoning Engine P6SA service agent will be used."""
+
+ identity_type: Optional[IdentityType]
+ """The identity type to use for the Agent Engine."""
+
+ context_spec: Optional[ReasoningEngineContextSpecDict]
+ """The context spec to be used for the Agent Engine."""
+
+ psc_interface_config: Optional[PscInterfaceConfigDict]
+ """The PSC interface config for PSC-I to be used for the Agent Engine."""
+
+ min_instances: Optional[int]
+ """The minimum number of instances to run for the Agent Engine.
+ Defaults to 1. Range: [0, 10].
+ """
+
+ max_instances: Optional[int]
+ """The maximum number of instances to run for the Agent Engine.
+ Defaults to 100. Range: [1, 1000].
+ If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
+ """
+
+ resource_limits: Optional[dict[str, str]]
+ """The resource limits to be applied to the Agent Engine.
+ Required keys: 'cpu' and 'memory'.
+ Supported values for 'cpu': '1', '2', '4', '6', '8'.
+ Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
+ """
+
+ container_concurrency: Optional[int]
+ """The container concurrency to be used for the Agent Engine.
+ Recommended value: 2 * cpu + 1. Defaults to 9.
+ """
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """The encryption spec to be used for the Agent Engine."""
+
+ labels: Optional[dict[str, str]]
+ """The labels to be used for the Agent Engine."""
+
+ agent_server_mode: Optional[AgentServerMode]
+ """The agent server mode to use for deployment."""
+
+ class_methods: Optional[list[dict[str, Any]]]
+ """The class methods to be used for the Agent Engine.
+ If specified, they'll override the class methods that are autogenerated by
+ default. By default, methods are generated by inspecting the agent object
+ and generating a corresponding method for each method defined on the
+ agent class.
+ """
+
+ source_packages: Optional[list[str]]
+ """The user-provided paths to the source packages (if any).
+ If specified, the files in the source packages will be packed into a
+ a tarball file, uploaded to Agent Engine's API, and deployed to the
+ Agent Engine.
+ The following fields will be ignored:
+ - agent
+ - extra_packages
+ - staging_bucket
+ - requirements
+ The following fields will be used to install and use the agent from the
+ source packages:
+ - entrypoint_module (required)
+ - entrypoint_object (required)
+ - requirements_file (optional)
+ - class_methods (required)
+ """
+
+ developer_connect_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
+ ]
+ """Specifies the configuration for fetching source code from a Git repository that is managed by Developer Connect. This includes the repository, revision, and directory to use."""
+
+ entrypoint_module: Optional[str]
+ """The entrypoint module to be used for the Agent Engine
+ This field only used when source_packages is specified."""
+
+ entrypoint_object: Optional[str]
+ """The entrypoint object to be used for the Agent Engine.
+ This field only used when source_packages is specified."""
+
+ requirements_file: Optional[str]
+ """The user-provided path to the requirements file (if any).
+ This field is only used when source_packages is specified.
+ If not specified, agent engine will find and use the `requirements.txt` in
+ the source package.
+ """
+
+ agent_framework: Optional[
+ Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
+ ]
+ """The agent framework to be used for the Agent Engine.
+ The OSS agent framework used to develop the agent.
+ Currently supported values: "google-adk", "langchain", "langgraph",
+ "ag2", "llama-index", "custom".
+ If not specified:
+ - If `agent` is specified, the agent framework will be auto-detected.
+ - If `source_packages` is specified, the agent framework will
+ default to "custom"."""
+
+ python_version: Optional[Literal["3.10", "3.11", "3.12", "3.13", "3.14"]]
+ """The Python version to be used for the Agent Engine.
+ If not specified, it will use the current Python version of the environment.
+ Supported versions: "3.10", "3.11", "3.12", "3.13", "3.14".
+ """
+
+ build_options: Optional[dict[str, list[str]]]
+ """The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ """
+
+ image_spec: Optional[ReasoningEngineSpecSourceCodeSpecImageSpecDict]
+ """The image spec for the Agent Engine."""
+
+ agent_config_source: Optional[
+ ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict
+ ]
+ """The agent config source for the Agent Engine."""
+
+ container_spec: Optional[ReasoningEngineSpecContainerSpecDict]
+ """The container spec for the Agent Engine."""
+
+ agent_gateway_config: Optional[
+ ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
+ ]
+ """Agent Gateway configuration for a Reasoning Engine deployment."""
+
+ keep_alive_probe: Optional[KeepAliveProbeDict]
+ """Optional. Specifies the configuration for keep-alive probe.
+ Contains configuration on a specified endpoint that a deployment host
+ should use to keep the container alive based on the probe settings."""
+
+ traffic_config: Optional[ReasoningEngineTrafficConfigDict]
+ """The traffic config for the Agent Engine."""
+
+
+AgentEngineConfigOrDict = Union[AgentEngineConfig, AgentEngineConfigDict]
+
+
+class RunQueryJobAgentEngineConfig(_common.BaseModel):
+ """Config for checking a query job on an agent engine."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ query: Optional[str] = Field(
+ default=None, description="""The query to send to the agent engine."""
+ )
+ output_gcs_uri: Optional[str] = Field(
+ default=None,
+ description="""The GCS URI to use for the output.
+ If it is a file, the system use this file to store the response.
+ If it represents a directory, the system automatically generate a file
+ for the response.
+ In both cases, the input query will be stored in the same directory under
+ the same file name prefix as the output file.""",
+ )
+
+
+class RunQueryJobAgentEngineConfigDict(TypedDict, total=False):
+ """Config for checking a query job on an agent engine."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ query: Optional[str]
+ """The query to send to the agent engine."""
+
+ output_gcs_uri: Optional[str]
+ """The GCS URI to use for the output.
+ If it is a file, the system use this file to store the response.
+ If it represents a directory, the system automatically generate a file
+ for the response.
+ In both cases, the input query will be stored in the same directory under
+ the same file name prefix as the output file."""
+
+
+RunQueryJobAgentEngineConfigOrDict = Union[
+ RunQueryJobAgentEngineConfig, RunQueryJobAgentEngineConfigDict
+]
+
+
+class RunQueryJobResult(_common.BaseModel):
+ """Result of running a query job."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ job_name: Optional[str] = Field(
+ default=None,
+ description="""Name of the agent engine operation to later check for status.""",
+ )
+ input_gcs_uri: Optional[str] = Field(
+ default=None, description="""The GCS URI of the input file."""
+ )
+ output_gcs_uri: Optional[str] = Field(
+ default=None, description="""The GCS URI of the output file."""
+ )
+
+
+class RunQueryJobResultDict(TypedDict, total=False):
+ """Result of running a query job."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ job_name: Optional[str]
+ """Name of the agent engine operation to later check for status."""
+
+ input_gcs_uri: Optional[str]
+ """The GCS URI of the input file."""
+
+ output_gcs_uri: Optional[str]
+ """The GCS URI of the output file."""
+
+
+RunQueryJobResultOrDict = Union[RunQueryJobResult, RunQueryJobResultDict]
+
+
+class CheckQueryJobResponse(_common.BaseModel):
+ """Response from LRO."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ output_gcs_uri: Optional[str] = Field(
+ default=None, description="""The GCS URI of the output file."""
+ )
+
+
+class CheckQueryJobResponseDict(TypedDict, total=False):
+ """Response from LRO."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ output_gcs_uri: Optional[str]
+ """The GCS URI of the output file."""
+
+
+CheckQueryJobResponseOrDict = Union[CheckQueryJobResponse, CheckQueryJobResponseDict]
+
+
+class AssembleDataset(_common.BaseModel):
+ """Represents the assembled dataset."""
+
+ bigquery_destination: Optional[str] = Field(
+ default=None,
+ description="""The BigQuery destination of the assembled dataset.""",
+ )
+
+
+class AssembleDatasetDict(TypedDict, total=False):
+ """Represents the assembled dataset."""
+
+ bigquery_destination: Optional[str]
+ """The BigQuery destination of the assembled dataset."""
+
+
+AssembleDatasetOrDict = Union[AssembleDataset, AssembleDatasetDict]
+
+
+class BatchPredictionResourceUsageAssessmentResult(_common.BaseModel):
+ """Result of batch prediction resource usage assessment."""
+
+ token_count: Optional[int] = Field(
+ default=None, description="""Number of tokens in the dataset."""
+ )
+ audio_token_count: Optional[int] = Field(
+ default=None, description="""Number of audio tokens in the dataset."""
+ )
+
+
+class BatchPredictionResourceUsageAssessmentResultDict(TypedDict, total=False):
+ """Result of batch prediction resource usage assessment."""
+
+ token_count: Optional[int]
+ """Number of tokens in the dataset."""
+
+ audio_token_count: Optional[int]
+ """Number of audio tokens in the dataset."""
+
+
+BatchPredictionResourceUsageAssessmentResultOrDict = Union[
+ BatchPredictionResourceUsageAssessmentResult,
+ BatchPredictionResourceUsageAssessmentResultDict,
+]
+
+
+class BatchPredictionValidationAssessmentResult(_common.BaseModel):
+ """Result of batch prediction validation assessment."""
+
+ errors: Optional[list[str]] = Field(
+ default=None, description="""The list of errors found in the dataset."""
+ )
+
+
+class BatchPredictionValidationAssessmentResultDict(TypedDict, total=False):
+ """Result of batch prediction validation assessment."""
+
+ errors: Optional[list[str]]
+ """The list of errors found in the dataset."""
+
+
+BatchPredictionValidationAssessmentResultOrDict = Union[
+ BatchPredictionValidationAssessmentResult,
+ BatchPredictionValidationAssessmentResultDict,
+]
+
+
+class TuningResourceUsageAssessmentResult(_common.BaseModel):
+ """Result of tuning resource usage assessment."""
+
+ token_count: Optional[int] = Field(
+ default=None, description="""The number of tokens in the dataset."""
+ )
+ billable_character_count: Optional[int] = Field(
+ default=None,
+ description="""The number of billable characters in the dataset.""",
+ )
+
+
+class TuningResourceUsageAssessmentResultDict(TypedDict, total=False):
+ """Result of tuning resource usage assessment."""
+
+ token_count: Optional[int]
+ """The number of tokens in the dataset."""
+
+ billable_character_count: Optional[int]
+ """The number of billable characters in the dataset."""
+
+
+TuningResourceUsageAssessmentResultOrDict = Union[
+ TuningResourceUsageAssessmentResult, TuningResourceUsageAssessmentResultDict
+]
+
+
+class TuningValidationAssessmentResult(_common.BaseModel):
+ """The result of a tuning validation assessment."""
+
+ errors: Optional[list[str]] = Field(
+ default=None, description="""The list of errors found in the dataset."""
+ )
+
+
+class TuningValidationAssessmentResultDict(TypedDict, total=False):
+ """The result of a tuning validation assessment."""
+
+ errors: Optional[list[str]]
+ """The list of errors found in the dataset."""
+
+
+TuningValidationAssessmentResultOrDict = Union[
+ TuningValidationAssessmentResult, TuningValidationAssessmentResultDict
+]
+
+
+class Prompt(_common.BaseModel):
+ """Represents a prompt."""
+
+ prompt_data: Optional["PromptData"] = Field(default=None, description="""""")
+ _dataset: Optional["Dataset"] = PrivateAttr(default=None)
+ _dataset_version: Optional["DatasetVersion"] = PrivateAttr(default=None)
+
+ @property
+ def dataset(self) -> "Dataset":
+ return self._dataset # type: ignore[return-value]
+
+ @property
+ def dataset_version(self) -> "DatasetVersion":
+ return self._dataset_version # type: ignore[return-value]
+
+ @property
+ def prompt_id(self) -> Optional[str]:
+ """Returns the ID associated with the prompt resource."""
+ if self._dataset and self._dataset.name:
+ return self._dataset.name.split("/")[-1]
+ elif not self._dataset and (
+ self._dataset_version and self._dataset_version.name
+ ):
+ return self._dataset_version.name.split("datasets/")[1].split("/")[0]
+ return None
+
+ @property
+ def version_id(self) -> Optional[str]:
+ """Returns the ID associated with the prompt version resource."""
+ if self._dataset_version and self._dataset_version.name:
+ return self._dataset_version.name.split("/")[-1]
+ return None
+
+ def assemble_contents(self) -> list[genai_types.Content]:
+ """Transforms a Prompt object into a list with a single genai_types.Content object.
+
+ This method replaces the variables in the prompt template with the values provided in prompt.prompt_data.variables.
+ If no variables are provided, prompt.prompt_data.contents is returned as is. Only single-turn prompts are supported.
+
+ This can be used to call generate_content() in the Gen AI SDK.
+
+ Example usage:
+
+ my_prompt = types.Prompt(
+ prompt_data=types.PromptData(
+ model="gemini-2.0-flash-001",
+ contents=[
+ genai_types.Content(
+ parts=[
+ genai_types.Part(text="Hello {name}!"),
+ ],
+ ),
+ ],
+ variables=[
+ {
+ "name": genai_types.Part(text="Alice"),
+ },
+ ],
+ ),
+ )
+
+ from google import genai
+
+ genai_client = genai.Client(vertexai=True, project="my-project", location="us-central1")
+ genai_client.models.generate_content(
+ model=my_prompt.prompt_data.model,
+ contents=my_prompt.assemble_contents(),
+ )
+
+ Returns:
+ A list with a single Content object that can be used to call
+ generate_content().
+ """
+ if not self.prompt_data or not self.prompt_data.contents:
+ return []
+
+ if not self.prompt_data.variables:
+ return self.prompt_data.contents
+
+ if len(self.prompt_data.contents) > 1:
+ raise ValueError(
+ "Multiple contents are not supported. Use assemble_contents() for a prompt with a single Content item."
+ )
+
+ parts_to_process = self.prompt_data.contents[0].parts
+ if parts_to_process is None:
+ return []
+ if not isinstance(parts_to_process, list):
+ parts_to_process = [parts_to_process]
+
+ has_placeholders = False
+ variable_regex = r"\{.*?\}"
+ for item in parts_to_process:
+ part = (
+ item
+ if isinstance(item, genai_types.Part)
+ else genai_types.Part(text=str(item))
+ )
+ if part.text and re.search(variable_regex, part.text):
+ has_placeholders = True
+ break
+
+ if not has_placeholders:
+ return [genai_types.Content(parts=parts_to_process)]
+
+ all_rendered_parts: list[genai_types.Part] = []
+
+ for var_dict in self.prompt_data.variables:
+ for template_item in parts_to_process:
+ template_part = (
+ template_item
+ if isinstance(template_item, genai_types.Part)
+ else genai_types.Part(text=str(template_item))
+ )
+ if template_part.text:
+ rendered_text = template_part.text
+
+ for key, value in var_dict.items():
+ placeholder = f"{{{key}}}"
+ replacement_text = None
+
+ if isinstance(value, str):
+ replacement_text = value
+ elif isinstance(value, genai_types.Part):
+ if value.text:
+ replacement_text = value.text
+ else:
+ all_rendered_parts.append(value)
+ if (
+ replacement_text is not None
+ and placeholder in rendered_text
+ ):
+ rendered_text = rendered_text.replace(
+ placeholder, replacement_text
+ )
+ all_rendered_parts.append(genai_types.Part(text=rendered_text))
+ else:
+ all_rendered_parts.append(template_part)
+ return [genai_types.Content(parts=all_rendered_parts, role="user")]
+
+
+PromptData = SchemaPromptSpecPromptMessage
+PromptDataDict = SchemaPromptSpecPromptMessageDict
+PromptDataOrDict = Union[PromptData, PromptDataDict]
+
+ParsedResponseUnion = Union[
+ prompts_types.ParsedResponse, prompts_types.ParsedResponseFewShot
+]
+ParsedResponseUnionDict = Union[
+ prompts_types.ParsedResponseDict, prompts_types.ParsedResponseFewShotDict
+]
+
+
+class PromptDict(TypedDict, total=False):
+ """Represents a prompt."""
+
+ prompt_data: Optional["PromptDataDict"]
+ """"""
+
+
+PromptOrDict = Union[Prompt, PromptDict]
+
+
+class SchemaPromptInstanceVariableValue(_common.BaseModel):
+ """Represents a prompt instance variable."""
+
+ part_list: Optional[SchemaPromptSpecPartList] = Field(
+ default=None, description="""The parts of the variable value."""
+ )
+
+
+class SchemaPromptInstanceVariableValueDict(TypedDict, total=False):
+ """Represents a prompt instance variable."""
+
+ part_list: Optional[SchemaPromptSpecPartListDict]
+ """The parts of the variable value."""
+
+
+SchemaPromptInstanceVariableValueOrDict = Union[
+ SchemaPromptInstanceVariableValue, SchemaPromptInstanceVariableValueDict
+]
+
+
+class CreatePromptConfig(_common.BaseModel):
+ """Config for creating a prompt."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ prompt_display_name: Optional[str] = Field(
+ default=None,
+ description="""The display name for the prompt. If not set, a default name with a timestamp will be used.""",
+ )
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds.""",
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key.""",
+ )
+ version_display_name: Optional[str] = Field(
+ default=None,
+ description="""The display name for the prompt version. If not set, a default name with a timestamp will be used.""",
+ )
+
+
+class CreatePromptConfigDict(TypedDict, total=False):
+ """Config for creating a prompt."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ prompt_display_name: Optional[str]
+ """The display name for the prompt. If not set, a default name with a timestamp will be used."""
+
+ timeout: Optional[int]
+ """The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds."""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key."""
+
+ version_display_name: Optional[str]
+ """The display name for the prompt version. If not set, a default name with a timestamp will be used."""
+
+
+CreatePromptConfigOrDict = Union[CreatePromptConfig, CreatePromptConfigDict]
+
+
+class CreatePromptVersionConfig(_common.BaseModel):
+ """Config for creating a prompt version."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+ version_display_name: Optional[str] = Field(
+ default=None,
+ description="""The display name for the prompt version. If not set, a default name with a timestamp will be used.""",
+ )
+ timeout: Optional[int] = Field(
+ default=90,
+ description="""The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds.""",
+ )
+ prompt_display_name: Optional[str] = Field(
+ default=None,
+ description="""The display name for the prompt. If not set, a default name with a timestamp will be used.""",
+ )
+ encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
+ default=None,
+ description="""Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key.""",
+ )
+
+
+class CreatePromptVersionConfigDict(TypedDict, total=False):
+ """Config for creating a prompt version."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+ version_display_name: Optional[str]
+ """The display name for the prompt version. If not set, a default name with a timestamp will be used."""
+
+ timeout: Optional[int]
+ """The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds."""
+
+ prompt_display_name: Optional[str]
+ """The display name for the prompt. If not set, a default name with a timestamp will be used."""
+
+ encryption_spec: Optional[genai_types.EncryptionSpecDict]
+ """Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key."""
+
+
+CreatePromptVersionConfigOrDict = Union[
+ CreatePromptVersionConfig, CreatePromptVersionConfigDict
+]
+
+
+class GetPromptConfig(_common.BaseModel):
+ """Config for getting a prompt."""
+
+ http_options: Optional[genai_types.HttpOptions] = Field(
+ default=None, description="""Used to override HTTP request options."""
+ )
+
+
+class GetPromptConfigDict(TypedDict, total=False):
+ """Config for getting a prompt."""
+
+ http_options: Optional[genai_types.HttpOptionsDict]
+ """Used to override HTTP request options."""
+
+
+GetPromptConfigOrDict = Union[GetPromptConfig, GetPromptConfigDict]
+
+
+class PromptRef(_common.BaseModel):
+ """Reference to a prompt."""
+
+ prompt_id: Optional[str] = Field(default=None, description="""""")
+ model: Optional[str] = Field(default=None, description="""""")
+
+
+class PromptRefDict(TypedDict, total=False):
+ """Reference to a prompt."""
+
+ prompt_id: Optional[str]
+ """"""
+
+ model: Optional[str]
+ """"""
+
+
+PromptRefOrDict = Union[PromptRef, PromptRefDict]
+
+
+class PromptVersionRef(_common.BaseModel):
+ """Reference to a prompt version."""
+
+ prompt_id: Optional[str] = Field(default=None, description="""""")
+ version_id: Optional[str] = Field(default=None, description="""""")
+ model: Optional[str] = Field(default=None, description="""""")
+
+
+class PromptVersionRefDict(TypedDict, total=False):
+ """Reference to a prompt version."""
+
+ prompt_id: Optional[str]
+ """"""
+
+ version_id: Optional[str]
+ """"""
+
+ model: Optional[str]
+ """"""
+
+
+PromptVersionRefOrDict = Union[PromptVersionRef, PromptVersionRefDict]
+
+
+class OptimizeJobConfig(_common.BaseModel):
+ """VAPO Prompt Optimizer Config."""
+
+ config_path: Optional[str] = Field(
+ default=None,
+ description="""The gcs path to the config file, e.g. gs://bucket/config.json.""",
+ )
+ service_account: Optional[str] = Field(
+ default=None,
+ description="""The service account to use for the custom job. Cannot be provided at the same time as service_account_project_number.""",
+ )
+ service_account_project_number: Optional[Union[int, str]] = Field(
+ default=None,
+ description="""The project number used to construct the default service account:{service_account_project_number}-compute@developer.gserviceaccount.comCannot be provided at the same time as "service_account".""",
+ )
+ wait_for_completion: Optional[bool] = Field(
+ default=True,
+ description="""Whether to wait for the job tocomplete. Ignored for async jobs.""",
+ )
+ optimizer_job_display_name: Optional[str] = Field(
+ default=None,
+ description="""The display name of the optimization job. If not provided, a display name in the format of "vapo-optimizer-{timestamp}" will be used.""",
+ )
+
+
+class OptimizeJobConfigDict(TypedDict, total=False):
+ """VAPO Prompt Optimizer Config."""
+
+ config_path: Optional[str]
+ """The gcs path to the config file, e.g. gs://bucket/config.json."""
+
+ service_account: Optional[str]
+ """The service account to use for the custom job. Cannot be provided at the same time as service_account_project_number."""
+
+ service_account_project_number: Optional[Union[int, str]]
+ """The project number used to construct the default service account:{service_account_project_number}-compute@developer.gserviceaccount.comCannot be provided at the same time as "service_account"."""
+
+ wait_for_completion: Optional[bool]
+ """Whether to wait for the job tocomplete. Ignored for async jobs."""
+
+ optimizer_job_display_name: Optional[str]
+ """The display name of the optimization job. If not provided, a display name in the format of "vapo-optimizer-{timestamp}" will be used."""
+
+
+OptimizeJobConfigOrDict = Union[OptimizeJobConfig, OptimizeJobConfigDict]
+
+
+class AgentEngineRuntimeRevision(_common.BaseModel):
+ """An agent engine runtime revision instance."""
+
+ api_client: Optional[Any] = Field(
+ default=None, description="""The underlying API client."""
+ )
+ api_async_client: Optional[Any] = Field(
+ default=None,
+ description="""The underlying API client for asynchronous operations.""",
+ )
+ api_resource: Optional[ReasoningEngineRuntimeRevision] = Field(
+ default=None,
+ description="""The underlying API resource (i.e. ReasoningEngineRuntimeRevision).""",
+ )
+
+ # Allows dynamic binding of methods based on the registered operations.
+ model_config = ConfigDict(extra="allow")
+
+ def __repr__(self) -> str:
+ return (
+ f"AgentEngineRuntimeRevision(api_resource.name='{self.api_resource.name}')"
+ if self.api_resource is not None
+ else "AgentEngineRuntimeRevision(api_resource.name=None)"
+ )
+
+ def operation_schemas(self) -> Optional[list[Dict[str, Any]]]:
+ """Returns the schemas of all registered operations for the agent."""
+ if not isinstance(self.api_resource, ReasoningEngineRuntimeRevision):
+ raise ValueError("api_resource is not initialized.")
+ if not self.api_resource.spec:
+ raise ValueError("api_resource.spec is not initialized.")
+ return self.api_resource.spec.class_methods
+
+ def delete(
+ self,
+ config: Optional[DeleteAgentEngineRuntimeRevisionConfigOrDict] = None,
+ ) -> None:
+ """Deletes the agent engine runtime revision.
+
+ Args:
+ config (DeleteAgentEngineRuntimeRevisionConfig):
+ Optional. Additional configurations for deleting the Agent Engine Runtime Revision.
+ """
+ if not isinstance(self.api_resource, ReasoningEngineRuntimeRevision):
+ raise ValueError("api_resource is not initialized.")
+ self.api_client.delete(name=self.api_resource.name, config=config) # type: ignore[union-attr]
+
+
+class AgentEngineRuntimeRevisionDict(TypedDict, total=False):
+ """An agent engine runtime revision instance."""
+
+ api_client: Optional[Any]
+ """The underlying API client."""
+
+ api_async_client: Optional[Any]
+ """The underlying API client for asynchronous operations."""
+
+ api_resource: Optional[ReasoningEngineRuntimeRevisionDict]
+ """The underlying API resource (i.e. ReasoningEngineRuntimeRevision)."""
+
+
+AgentEngineRuntimeRevisionOrDict = Union[
+ AgentEngineRuntimeRevision, AgentEngineRuntimeRevisionDict
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/evals.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/evals.py
new file mode 100644
index 0000000000000000000000000000000000000000..4454c00c7590a514d86e0432a6c50c6d8574ee10
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/evals.py
@@ -0,0 +1,977 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+import datetime
+from typing import Any, Optional, Union
+from google.genai import _common
+from google.genai import types as genai_types
+from pydantic import Field
+from typing_extensions import TypedDict
+
+
+class Importance(_common.CaseInSensitiveEnum):
+ """Importance level of the rubric."""
+
+ IMPORTANCE_UNSPECIFIED = "IMPORTANCE_UNSPECIFIED"
+ """Importance is not specified."""
+ HIGH = "HIGH"
+ """High importance."""
+ MEDIUM = "MEDIUM"
+ """Medium importance."""
+ LOW = "LOW"
+ """Low importance."""
+
+
+class AgentConfig(_common.BaseModel):
+ """Represents configuration for an Agent."""
+
+ agent_id: Optional[str] = Field(
+ default=None,
+ description="""Unique identifier of the agent.
+ This ID is used to refer to this agent, e.g., in AgentEvent.author, or in
+ the `sub_agents` field. It must be unique within the `agents` map.""",
+ )
+ agent_type: Optional[str] = Field(
+ default=None,
+ description="""The type or class of the agent (e.g., "LlmAgent", "RouterAgent",
+ "ToolUseAgent"). Useful for the autorater to understand the expected
+ behavior of the agent.""",
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="""A high-level description of the agent's role and responsibilities.
+ Critical for evaluating if the agent is routing tasks correctly.""",
+ )
+ instruction: Optional[str] = Field(
+ default=None,
+ description="""The instructions for the LLM model, guiding the agent's behavior.
+ Can be static or dynamic. Dynamic instructions can contain placeholders
+ like {variable_name} that will be resolved at runtime using the
+ `AgentEvent.state_delta` field.""",
+ )
+ tools: Optional[list[genai_types.Tool]] = Field(
+ default=None, description="""The list of tools available to this agent."""
+ )
+ sub_agents: Optional[list[str]] = Field(
+ default=None,
+ description="""The list of valid agent IDs that this agent can delegate to.
+ This defines the directed edges in the multi-agent system graph topology.""",
+ )
+
+ @staticmethod
+ def _get_tool_declarations_from_agent(agent: Any) -> genai_types.ToolListUnion:
+ """Gets tool declarations from an agent.
+
+ Args:
+ agent: The agent to get the tool declarations from. Data type is google.adk.agents.LLMAgent type.
+
+ Returns:
+ The tool declarations of the agent.
+ """
+ tool_declarations: genai_types.ToolListUnion = []
+ for tool in agent.tools:
+ # ADK tools (e.g. AgentTool) provide their own declaration via
+ # _get_declaration(). Use it when available to avoid calling
+ # typing.get_type_hints() on tool instances whose classes use
+ # `from __future__ import annotations`, which causes NameError.
+ if hasattr(tool, "_get_declaration") and callable(tool._get_declaration):
+ declaration = tool._get_declaration()
+ if declaration is not None:
+ tool_declarations.append({"function_declarations": [declaration]})
+ continue
+
+ tool_declarations.append(
+ {
+ "function_declarations": [
+ genai_types.FunctionDeclaration.from_callable_with_api_option(
+ callable=tool
+ )
+ ]
+ }
+ )
+ return tool_declarations
+
+ @classmethod
+ def from_agent(cls, agent: Any) -> "AgentConfig":
+ """Creates an AgentConfig from an ADK agent.
+
+ Args:
+ agent: The agent to get the agent info from, data type is google.adk.agents.LLMAgent type.
+
+ Returns:
+ An AgentConfig populated with the agent's metadata for evaluation.
+ """
+ agent_id = getattr(agent, "name", None)
+ if not agent_id:
+ raise ValueError(f"Agent {agent} must have a name.")
+ return cls( # pytype: disable=missing-parameter
+ agent_id=agent_id,
+ agent_type=agent.__class__.__name__,
+ description=getattr(agent, "description", None),
+ instruction=getattr(agent, "instruction", None),
+ tools=AgentConfig._get_tool_declarations_from_agent(agent),
+ sub_agents=[
+ str(getattr(sub_agent, "name"))
+ for sub_agent in getattr(agent, "sub_agents", [])
+ if getattr(sub_agent, "name", None) is not None
+ ],
+ )
+
+
+class AgentConfigDict(TypedDict, total=False):
+ """Represents configuration for an Agent."""
+
+ agent_id: Optional[str]
+ """Unique identifier of the agent.
+ This ID is used to refer to this agent, e.g., in AgentEvent.author, or in
+ the `sub_agents` field. It must be unique within the `agents` map."""
+
+ agent_type: Optional[str]
+ """The type or class of the agent (e.g., "LlmAgent", "RouterAgent",
+ "ToolUseAgent"). Useful for the autorater to understand the expected
+ behavior of the agent."""
+
+ description: Optional[str]
+ """A high-level description of the agent's role and responsibilities.
+ Critical for evaluating if the agent is routing tasks correctly."""
+
+ instruction: Optional[str]
+ """The instructions for the LLM model, guiding the agent's behavior.
+ Can be static or dynamic. Dynamic instructions can contain placeholders
+ like {variable_name} that will be resolved at runtime using the
+ `AgentEvent.state_delta` field."""
+
+ tools: Optional[list[genai_types.ToolDict]]
+ """The list of tools available to this agent."""
+
+ sub_agents: Optional[list[str]]
+ """The list of valid agent IDs that this agent can delegate to.
+ This defines the directed edges in the multi-agent system graph topology."""
+
+
+AgentConfigOrDict = Union[AgentConfig, AgentConfigDict]
+
+
+class AgentEvent(_common.BaseModel):
+ """A single event in the execution trace."""
+
+ author: Optional[str] = Field(
+ default=None,
+ description="""The ID of the agent or entity that generated this event.
+ Use "user" to denote events generated by the end-user.""",
+ )
+ content: Optional[genai_types.Content] = Field(
+ default=None, description="""The content of the event."""
+ )
+ event_time: Optional[datetime.datetime] = Field(
+ default=None, description="""The timestamp when the event occurred."""
+ )
+ state_delta: Optional[dict[str, Any]] = Field(
+ default=None,
+ description="""The change in the session state caused by this event.
+ This is a key-value map of fields that were modified or added by the event.""",
+ )
+ active_tools: Optional[list[genai_types.Tool]] = Field(
+ default=None,
+ description="""The list of tools that were active/available to the agent at the
+ time of this event. This overrides the `AgentConfig.tools` if set.""",
+ )
+
+
+class AgentEventDict(TypedDict, total=False):
+ """A single event in the execution trace."""
+
+ author: Optional[str]
+ """The ID of the agent or entity that generated this event.
+ Use "user" to denote events generated by the end-user."""
+
+ content: Optional[genai_types.ContentDict]
+ """The content of the event."""
+
+ event_time: Optional[datetime.datetime]
+ """The timestamp when the event occurred."""
+
+ state_delta: Optional[dict[str, Any]]
+ """The change in the session state caused by this event.
+ This is a key-value map of fields that were modified or added by the event."""
+
+ active_tools: Optional[list[genai_types.ToolDict]]
+ """The list of tools that were active/available to the agent at the
+ time of this event. This overrides the `AgentConfig.tools` if set."""
+
+
+AgentEventOrDict = Union[AgentEvent, AgentEventDict]
+
+
+class ConversationTurn(_common.BaseModel):
+ """Represents a single turn/invocation in the conversation."""
+
+ turn_index: Optional[int] = Field(
+ default=None,
+ description="""The 0-based index of the turn in the conversation sequence.""",
+ )
+ turn_id: Optional[str] = Field(
+ default=None, description="""A unique identifier for the turn."""
+ )
+ events: Optional[list[AgentEvent]] = Field(
+ default=None,
+ description="""The list of events that occurred during this turn.""",
+ )
+
+
+class ConversationTurnDict(TypedDict, total=False):
+ """Represents a single turn/invocation in the conversation."""
+
+ turn_index: Optional[int]
+ """The 0-based index of the turn in the conversation sequence."""
+
+ turn_id: Optional[str]
+ """A unique identifier for the turn."""
+
+ events: Optional[list[AgentEventDict]]
+ """The list of events that occurred during this turn."""
+
+
+ConversationTurnOrDict = Union[ConversationTurn, ConversationTurnDict]
+
+
+class AgentData(_common.BaseModel):
+ """Represents data specific to multi-turn agent evaluations."""
+
+ agents: Optional[dict[str, AgentConfig]] = Field(
+ default=None,
+ description="""A map containing the static configurations for each agent in the system.
+ Key: agent_id (matches the `author` field in events).
+ Value: The static configuration of the agent.""",
+ )
+ turns: Optional[list[ConversationTurn]] = Field(
+ default=None,
+ description="""A chronological list of conversation turns.
+ Each turn represents a logical execution cycle (e.g., User Input -> Agent
+ Response).""",
+ )
+
+ @classmethod
+ def get_agents_map(cls, agent: Any) -> dict[str, AgentConfig]:
+ """Recursively gets all agent configs from an agent and its sub-agents.
+
+ Args:
+ agent: The agent to get the agent info from, data type is google.adk.agents.LLMAgent type.
+
+ Returns:
+ A dict mapping agent_id to AgentConfig.
+ """
+ agent_config = AgentConfig.from_agent(agent)
+ agent_id = agent_config.agent_id
+ if not agent_id:
+ raise ValueError(f"Agent {agent} must have a name.")
+ agents_map = {agent_id: agent_config}
+
+ for sub_agent in getattr(agent, "sub_agents", []):
+ agents_map.update(cls.get_agents_map(sub_agent))
+
+ return agents_map
+
+ @classmethod
+ def from_session(cls, agent: Any, session_history: list[Any]) -> "AgentData":
+ """Creates an AgentData object from a session history.
+
+ Segments the flat list of session events into ConversationTurns. A new turn
+ is initiated by a User message.
+
+ Args:
+ agent: The agent instance used in the session.
+ session_history: A list of raw events/messages from the session.
+
+ Returns:
+ An AgentData object containing the segmented history and agent config.
+ """
+ agents_map = cls.get_agents_map(agent)
+ agent_id = agent.name
+
+ turns: list[ConversationTurn] = []
+ current_turn_events: list[AgentEvent] = []
+
+ for event in session_history:
+ is_user = False
+ if isinstance(event, dict):
+ if event.get("role") == "user":
+ is_user = True
+ elif (
+ isinstance(event.get("content"), dict)
+ and event["content"].get("role") == "user"
+ ):
+ is_user = True
+ elif hasattr(event, "role") and event.role == "user":
+ is_user = True
+
+ if is_user and current_turn_events:
+ turns.append(
+ ConversationTurn( # pytype: disable=missing-parameter
+ turn_index=len(turns),
+ turn_id=f"turn_{len(turns)}",
+ events=current_turn_events,
+ )
+ )
+ current_turn_events = []
+
+ author = "user" if is_user else agent_id
+
+ content = None
+ if isinstance(event, dict):
+ if "content" in event:
+ raw_content = event["content"]
+ if isinstance(raw_content, genai_types.Content):
+ content = raw_content
+ elif isinstance(raw_content, dict):
+ try:
+ content = genai_types.Content.model_validate(raw_content)
+ except Exception as e:
+ raise ValueError(
+ f"Failed to validate Content from dictionary in session history: {raw_content}"
+ ) from e
+ elif isinstance(raw_content, str):
+ content = genai_types.Content(
+ parts=[genai_types.Part(text=raw_content)]
+ )
+ elif "parts" in event:
+ try:
+ content = genai_types.Content.model_validate(event)
+ except Exception as e:
+ raise ValueError(
+ f"Failed to validate Content from event with 'parts': {event}"
+ ) from e
+ elif hasattr(event, "content") and isinstance(
+ event.content, genai_types.Content
+ ):
+ content = event.content
+
+ agent_event = AgentEvent( # pytype: disable=missing-parameter
+ author=author,
+ content=content,
+ )
+ current_turn_events.append(agent_event)
+
+ if current_turn_events:
+ turns.append(
+ ConversationTurn( # pytype: disable=missing-parameter
+ turn_index=len(turns),
+ turn_id=f"turn_{len(turns)}",
+ events=current_turn_events,
+ )
+ )
+
+ return cls(agents=agents_map, turns=turns) # pytype: disable=missing-parameter
+
+
+class AgentDataDict(TypedDict, total=False):
+ """Represents data specific to multi-turn agent evaluations."""
+
+ agents: Optional[dict[str, AgentConfigDict]]
+ """A map containing the static configurations for each agent in the system.
+ Key: agent_id (matches the `author` field in events).
+ Value: The static configuration of the agent."""
+
+ turns: Optional[list[ConversationTurnDict]]
+ """A chronological list of conversation turns.
+ Each turn represents a logical execution cycle (e.g., User Input -> Agent
+ Response)."""
+
+
+AgentDataOrDict = Union[AgentData, AgentDataDict]
+
+
+class AgentInfo(_common.BaseModel):
+ """The agent info of an agent system, used for agent evaluation."""
+
+ name: Optional[str] = Field(
+ default=None, description="""Agent candidate name, used as an identifier."""
+ )
+ agents: Optional[dict[str, AgentConfig]] = Field(
+ default=None,
+ description="""A map containing the static configurations for each agent in the system.
+ Key: agent_id (matches the `author` field in events).
+ Value: The static configuration of the agent.""",
+ )
+ root_agent_id: Optional[str] = Field(
+ default=None, description="""The agent ID of the root agent."""
+ )
+
+ @classmethod
+ def load_from_agent(cls, agent: Any) -> "AgentInfo":
+ """Loads agent info from an ADK agent.
+
+ Args:
+ agent: The root agent to get the agent info from, data type is google.adk.agents.LLMAgent type.
+
+ Returns:
+ The agent info of the agent system.
+
+ Example:
+ ```
+ from agentplatform._genai import types
+
+ agent_info = types.evals.AgentInfo.load_from_agent(agent=my_agent)
+ ```
+ """
+ agent_name = getattr(agent, "name", None)
+ if not agent_name:
+ raise ValueError(f"Agent {agent} must have a name.")
+ return cls( # pytype: disable=missing-parameter
+ name=agent_name,
+ agents=AgentData.get_agents_map(agent),
+ root_agent_id=agent_name,
+ )
+
+
+class AgentInfoDict(TypedDict, total=False):
+ """The agent info of an agent system, used for agent evaluation."""
+
+ name: Optional[str]
+ """Agent candidate name, used as an identifier."""
+
+ agents: Optional[dict[str, AgentConfigDict]]
+ """A map containing the static configurations for each agent in the system.
+ Key: agent_id (matches the `author` field in events).
+ Value: The static configuration of the agent."""
+
+ root_agent_id: Optional[str]
+ """The agent ID of the root agent."""
+
+
+AgentInfoOrDict = Union[AgentInfo, AgentInfoDict]
+
+
+class SessionInput(_common.BaseModel):
+ """This field is experimental and may change in future versions.
+
+ Input to initialize a session and run an agent, used for agent evaluation.
+ """
+
+ user_id: Optional[str] = Field(default=None, description="""The user id.""")
+ state: Optional[dict[str, str]] = Field(
+ default=None, description="""The state of the session."""
+ )
+ app_name: Optional[str] = Field(
+ default=None,
+ description="""The name of the app, used for local ADK agent run Runner and Session.""",
+ )
+
+
+class SessionInputDict(TypedDict, total=False):
+ """This field is experimental and may change in future versions.
+
+ Input to initialize a session and run an agent, used for agent evaluation.
+ """
+
+ user_id: Optional[str]
+ """The user id."""
+
+ state: Optional[dict[str, str]]
+ """The state of the session."""
+
+ app_name: Optional[str]
+ """The name of the app, used for local ADK agent run Runner and Session."""
+
+
+SessionInputOrDict = Union[SessionInput, SessionInputDict]
+
+
+class UserScenario(_common.BaseModel):
+ """User scenario to help simulate multi-turn agent run results."""
+
+ starting_prompt: Optional[str] = Field(
+ default=None,
+ description="""The prompt that starts the conversation between the simulated user and the agent under test.""",
+ )
+ conversation_plan: Optional[str] = Field(
+ default=None,
+ description="""The plan for the conversation, used to drive the multi-turn agent run and generate the simulated agent evaluation dataset.""",
+ )
+
+
+class UserScenarioDict(TypedDict, total=False):
+ """User scenario to help simulate multi-turn agent run results."""
+
+ starting_prompt: Optional[str]
+ """The prompt that starts the conversation between the simulated user and the agent under test."""
+
+ conversation_plan: Optional[str]
+ """The plan for the conversation, used to drive the multi-turn agent run and generate the simulated agent evaluation dataset."""
+
+
+UserScenarioOrDict = Union[UserScenario, UserScenarioDict]
+
+
+class UserScenarioGenerationConfig(_common.BaseModel):
+ """User scenario generation configuration."""
+
+ model_name: Optional[str] = Field(
+ default=None,
+ description="""The model name to use for user scenario generation.""",
+ )
+ count: Optional[int] = Field(
+ default=None,
+ description="""The number of user scenarios to generate. The maximum number of scenarios that can be generated is 100.""",
+ )
+ generation_instruction: Optional[str] = Field(
+ default=None,
+ description="""Instruction to guide the conversation scenario generation.""",
+ )
+ environment_context: Optional[str] = Field(
+ default=None,
+ description="""Environment context to drive simulation. For example, for a QA agent, this could be the docs queried by the tools.""",
+ )
+
+
+class UserScenarioGenerationConfigDict(TypedDict, total=False):
+ """User scenario generation configuration."""
+
+ model_name: Optional[str]
+ """The model name to use for user scenario generation."""
+
+ count: Optional[int]
+ """The number of user scenarios to generate. The maximum number of scenarios that can be generated is 100."""
+
+ generation_instruction: Optional[str]
+ """Instruction to guide the conversation scenario generation."""
+
+ environment_context: Optional[str]
+ """Environment context to drive simulation. For example, for a QA agent, this could be the docs queried by the tools."""
+
+
+UserScenarioGenerationConfigOrDict = Union[
+ UserScenarioGenerationConfig, UserScenarioGenerationConfigDict
+]
+
+
+class UserSimulatorConfig(_common.BaseModel):
+ """Configuration for a user simulator.
+
+ Uses an LLM to generate multi-turn messages that simulate a user.
+ """
+
+ model_name: Optional[str] = Field(
+ default=None,
+ description="""The model name to get next user message for multi-turn agent run.""",
+ )
+ model_configuration: Optional[genai_types.GenerateContentConfig] = Field(
+ default=None, description="""The configuration for the model."""
+ )
+ max_turn: Optional[int] = Field(
+ default=None,
+ description="""Maximum number of invocations allowed by the multi-turn agent
+ running. This property allows us to stop a run-off conversation
+ where the agent and the user simulator get into a never ending loop.
+ The initial fixed prompt is also counted as an invocation.""",
+ )
+
+
+class UserSimulatorConfigDict(TypedDict, total=False):
+ """Configuration for a user simulator.
+
+ Uses an LLM to generate multi-turn messages that simulate a user.
+ """
+
+ model_name: Optional[str]
+ """The model name to get next user message for multi-turn agent run."""
+
+ model_configuration: Optional[genai_types.GenerateContentConfigDict]
+ """The configuration for the model."""
+
+ max_turn: Optional[int]
+ """Maximum number of invocations allowed by the multi-turn agent
+ running. This property allows us to stop a run-off conversation
+ where the agent and the user simulator get into a never ending loop.
+ The initial fixed prompt is also counted as an invocation."""
+
+
+UserSimulatorConfigOrDict = Union[UserSimulatorConfig, UserSimulatorConfigDict]
+
+
+class Event(_common.BaseModel):
+ """Represents an event in a conversation between agents and users.
+
+ It is used to store the content of the conversation, as well as the actions
+ taken by the agents like function calls, function responses, intermediate NL
+ responses etc.
+ """
+
+ event_id: Optional[str] = Field(
+ default=None, description="""Unique identifier for the agent event."""
+ )
+ content: Optional[genai_types.Content] = Field(
+ default=None, description="""Content of the event."""
+ )
+ creation_timestamp: Optional[datetime.datetime] = Field(
+ default=None, description="""The creation timestamp of the event."""
+ )
+ author: Optional[str] = Field(
+ default=None, description="""Name of the entity that produced the event."""
+ )
+
+
+class EventDict(TypedDict, total=False):
+ """Represents an event in a conversation between agents and users.
+
+ It is used to store the content of the conversation, as well as the actions
+ taken by the agents like function calls, function responses, intermediate NL
+ responses etc.
+ """
+
+ event_id: Optional[str]
+ """Unique identifier for the agent event."""
+
+ content: Optional[genai_types.ContentDict]
+ """Content of the event."""
+
+ creation_timestamp: Optional[datetime.datetime]
+ """The creation timestamp of the event."""
+
+ author: Optional[str]
+ """Name of the entity that produced the event."""
+
+
+EventOrDict = Union[Event, EventDict]
+
+
+class Message(_common.BaseModel):
+ """Represents a single message turn in a conversation."""
+
+ turn_id: Optional[str] = Field(
+ default=None, description="""Unique identifier for the message turn."""
+ )
+ content: Optional[genai_types.Content] = Field(
+ default=None, description="""Content of the message, including function call."""
+ )
+ creation_timestamp: Optional[datetime.datetime] = Field(
+ default=None,
+ description="""Timestamp indicating when the message was created.""",
+ )
+ author: Optional[str] = Field(
+ default=None, description="""Name of the entity that produced the message."""
+ )
+
+
+class MessageDict(TypedDict, total=False):
+ """Represents a single message turn in a conversation."""
+
+ turn_id: Optional[str]
+ """Unique identifier for the message turn."""
+
+ content: Optional[genai_types.ContentDict]
+ """Content of the message, including function call."""
+
+ creation_timestamp: Optional[datetime.datetime]
+ """Timestamp indicating when the message was created."""
+
+ author: Optional[str]
+ """Name of the entity that produced the message."""
+
+
+MessageOrDict = Union[Message, MessageDict]
+
+
+class Events(_common.BaseModel):
+ """This field is experimental and will be removed in future versions.
+
+ Represents a list of events for an agent.
+ """
+
+ event: Optional[list[genai_types.Content]] = Field(
+ default=None, description="""A list of events."""
+ )
+
+
+class EventsDict(TypedDict, total=False):
+ """This field is experimental and will be removed in future versions.
+
+ Represents a list of events for an agent.
+ """
+
+ event: Optional[list[genai_types.ContentDict]]
+ """A list of events."""
+
+
+EventsOrDict = Union[Events, EventsDict]
+
+
+class InstanceDataContents(_common.BaseModel):
+ """This field is experimental and will be removed in future versions.
+
+ List of standard Content messages from Gemini API.
+ """
+
+ contents: Optional[list[genai_types.Content]] = Field(
+ default=None, description="""Repeated contents."""
+ )
+
+
+class InstanceDataContentsDict(TypedDict, total=False):
+ """This field is experimental and will be removed in future versions.
+
+ List of standard Content messages from Gemini API.
+ """
+
+ contents: Optional[list[genai_types.ContentDict]]
+ """Repeated contents."""
+
+
+InstanceDataContentsOrDict = Union[InstanceDataContents, InstanceDataContentsDict]
+
+
+class InstanceData(_common.BaseModel):
+ """This field is experimental and will be removed in future versions.
+
+ Instance data used to populate placeholders in a metric prompt template.
+ """
+
+ text: Optional[str] = Field(default=None, description="""Text data.""")
+ contents: Optional[InstanceDataContents] = Field(
+ default=None, description="""List of Gemini content data."""
+ )
+
+
+class InstanceDataDict(TypedDict, total=False):
+ """This field is experimental and will be removed in future versions.
+
+ Instance data used to populate placeholders in a metric prompt template.
+ """
+
+ text: Optional[str]
+ """Text data."""
+
+ contents: Optional[InstanceDataContentsDict]
+ """List of Gemini content data."""
+
+
+InstanceDataOrDict = Union[InstanceData, InstanceDataDict]
+
+
+class Tools(_common.BaseModel):
+ """This field is experimental and will be removed in future versions.
+
+ Represents a list of tools for an agent.
+ """
+
+ tool: Optional[list[genai_types.Tool]] = Field(
+ default=None,
+ description="""List of tools: each tool can have multiple function declarations.""",
+ )
+
+
+class ToolsDict(TypedDict, total=False):
+ """This field is experimental and will be removed in future versions.
+
+ Represents a list of tools for an agent.
+ """
+
+ tool: Optional[list[genai_types.ToolDict]]
+ """List of tools: each tool can have multiple function declarations."""
+
+
+ToolsOrDict = Union[Tools, ToolsDict]
+
+
+class RubricContentProperty(_common.BaseModel):
+ """Defines criteria based on a specific property."""
+
+ description: Optional[str] = Field(
+ default=None,
+ description="""Description of the property being evaluated.
+ Example: "The model's response is grammatically correct." """,
+ )
+
+
+class RubricContentPropertyDict(TypedDict, total=False):
+ """Defines criteria based on a specific property."""
+
+ description: Optional[str]
+ """Description of the property being evaluated.
+ Example: "The model's response is grammatically correct." """
+
+
+RubricContentPropertyOrDict = Union[RubricContentProperty, RubricContentPropertyDict]
+
+
+class RubricContent(_common.BaseModel):
+ """Content of the rubric, defining the testable criteria."""
+
+ property: Optional[RubricContentProperty] = Field(
+ default=None,
+ description="""Evaluation criteria based on a specific property.""",
+ )
+
+
+class RubricContentDict(TypedDict, total=False):
+ """Content of the rubric, defining the testable criteria."""
+
+ property: Optional[RubricContentPropertyDict]
+ """Evaluation criteria based on a specific property."""
+
+
+RubricContentOrDict = Union[RubricContent, RubricContentDict]
+
+
+class Rubric(_common.BaseModel):
+ """Message representing a single testable criterion for evaluation.
+
+ One input prompt could have multiple rubrics.
+ """
+
+ rubric_id: Optional[str] = Field(
+ default=None,
+ description="""Required. Unique identifier for the rubric.
+ This ID is used to refer to this rubric, e.g., in RubricVerdict.""",
+ )
+ content: Optional[RubricContent] = Field(
+ default=None,
+ description="""Required. The actual testable criteria for the rubric.""",
+ )
+ type: Optional[str] = Field(
+ default=None,
+ description="""Optional. A type designator for the rubric, which can inform how it's
+ evaluated or interpreted by systems or users.
+ It's recommended to use consistent, well-defined, upper snake_case strings.
+ Examples: "SUMMARIZATION_QUALITY", "SAFETY_HARMFUL_CONTENT",
+ "INSTRUCTION_ADHERENCE".""",
+ )
+ importance: Optional[Importance] = Field(
+ default=None,
+ description="""Optional. The relative importance of this rubric.""",
+ )
+
+
+class RubricDict(TypedDict, total=False):
+ """Message representing a single testable criterion for evaluation.
+
+ One input prompt could have multiple rubrics.
+ """
+
+ rubric_id: Optional[str]
+ """Required. Unique identifier for the rubric.
+ This ID is used to refer to this rubric, e.g., in RubricVerdict."""
+
+ content: Optional[RubricContentDict]
+ """Required. The actual testable criteria for the rubric."""
+
+ type: Optional[str]
+ """Optional. A type designator for the rubric, which can inform how it's
+ evaluated or interpreted by systems or users.
+ It's recommended to use consistent, well-defined, upper snake_case strings.
+ Examples: "SUMMARIZATION_QUALITY", "SAFETY_HARMFUL_CONTENT",
+ "INSTRUCTION_ADHERENCE"."""
+
+ importance: Optional[Importance]
+ """Optional. The relative importance of this rubric."""
+
+
+RubricOrDict = Union[Rubric, RubricDict]
+
+
+class RubricVerdict(_common.BaseModel):
+ """Represents the verdict of an evaluation against a single rubric."""
+
+ evaluated_rubric: Optional[Rubric] = Field(
+ default=None,
+ description="""Required. The full rubric definition that was evaluated.
+ Storing this ensures the verdict is self-contained and understandable,
+ especially if the original rubric definition changes or was dynamically
+ generated.""",
+ )
+ verdict: Optional[bool] = Field(
+ default=None,
+ description="""Required. Outcome of the evaluation against the rubric, represented as a
+ boolean. `true` indicates a "Pass", `false` indicates a "Fail".""",
+ )
+ reasoning: Optional[str] = Field(
+ default=None,
+ description="""Optional. Human-readable reasoning or explanation for the verdict.
+ This can include specific examples or details from the evaluated content
+ that justify the given verdict.""",
+ )
+
+
+class RubricVerdictDict(TypedDict, total=False):
+ """Represents the verdict of an evaluation against a single rubric."""
+
+ evaluated_rubric: Optional[RubricDict]
+ """Required. The full rubric definition that was evaluated.
+ Storing this ensures the verdict is self-contained and understandable,
+ especially if the original rubric definition changes or was dynamically
+ generated."""
+
+ verdict: Optional[bool]
+ """Required. Outcome of the evaluation against the rubric, represented as a
+ boolean. `true` indicates a "Pass", `false` indicates a "Fail"."""
+
+ reasoning: Optional[str]
+ """Optional. Human-readable reasoning or explanation for the verdict.
+ This can include specific examples or details from the evaluated content
+ that justify the given verdict."""
+
+
+RubricVerdictOrDict = Union[RubricVerdict, RubricVerdictDict]
+
+
+class CandidateResult(_common.BaseModel):
+ """Result for a single candidate."""
+
+ candidate: Optional[str] = Field(
+ default=None,
+ description="""The candidate that is being evaluated. The value is the same as the candidate name in the EvaluationRequest.""",
+ )
+ metric: Optional[str] = Field(
+ default=None, description="""The metric that was evaluated."""
+ )
+ score: Optional[float] = Field(
+ default=None, description="""The score of the metric."""
+ )
+ explanation: Optional[str] = Field(
+ default=None, description="""The explanation for the metric."""
+ )
+ rubric_verdicts: Optional[list[RubricVerdict]] = Field(
+ default=None, description="""The rubric verdicts for the metric."""
+ )
+ additional_results: Optional[dict[str, Any]] = Field(
+ default=None, description="""Additional results for the metric."""
+ )
+
+
+class CandidateResultDict(TypedDict, total=False):
+ """Result for a single candidate."""
+
+ candidate: Optional[str]
+ """The candidate that is being evaluated. The value is the same as the candidate name in the EvaluationRequest."""
+
+ metric: Optional[str]
+ """The metric that was evaluated."""
+
+ score: Optional[float]
+ """The score of the metric."""
+
+ explanation: Optional[str]
+ """The explanation for the metric."""
+
+ rubric_verdicts: Optional[list[RubricVerdictDict]]
+ """The rubric verdicts for the metric."""
+
+ additional_results: Optional[dict[str, Any]]
+ """Additional results for the metric."""
+
+
+CandidateResultOrDict = Union[CandidateResult, CandidateResultDict]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/prompt_optimizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/prompt_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..52c6c3058f9e932dac5d835dea05f4c8667c4877
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/prompt_optimizer.py
@@ -0,0 +1,107 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+from typing import Optional, Union
+from google.genai import _common
+from pydantic import Field
+from typing_extensions import TypedDict
+
+
+class ApplicableGuideline(_common.BaseModel):
+ """Applicable guideline for the optimize_prompt method."""
+
+ applicable_guideline: Optional[str] = Field(default=None, description="""""")
+ suggested_improvement: Optional[str] = Field(default=None, description="""""")
+ text_before_change: Optional[str] = Field(default=None, description="""""")
+ text_after_change: Optional[str] = Field(default=None, description="""""")
+
+
+class ApplicableGuidelineDict(TypedDict, total=False):
+ """Applicable guideline for the optimize_prompt method."""
+
+ applicable_guideline: Optional[str]
+ """"""
+
+ suggested_improvement: Optional[str]
+ """"""
+
+ text_before_change: Optional[str]
+ """"""
+
+ text_after_change: Optional[str]
+ """"""
+
+
+ApplicableGuidelineOrDict = Union[ApplicableGuideline, ApplicableGuidelineDict]
+
+
+class ParsedResponse(_common.BaseModel):
+ """Response for the optimize_prompt method."""
+
+ optimization_type: Optional[str] = Field(default=None, description="""""")
+ applicable_guidelines: Optional[list[ApplicableGuideline]] = Field(
+ default=None, description=""""""
+ )
+ original_prompt: Optional[str] = Field(default=None, description="""""")
+ suggested_prompt: Optional[str] = Field(default=None, description="""""")
+
+
+class ParsedResponseDict(TypedDict, total=False):
+ """Response for the optimize_prompt method."""
+
+ optimization_type: Optional[str]
+ """"""
+
+ applicable_guidelines: Optional[list[ApplicableGuidelineDict]]
+ """"""
+
+ original_prompt: Optional[str]
+ """"""
+
+ suggested_prompt: Optional[str]
+ """"""
+
+
+ParsedResponseOrDict = Union[ParsedResponse, ParsedResponseDict]
+
+
+class ParsedResponseFewShot(_common.BaseModel):
+ """Response for the optimize_prompt method."""
+
+ suggested_modifications: Optional[list[ApplicableGuideline]] = Field(
+ default=None, description=""""""
+ )
+ original_system_instructions: Optional[str] = Field(
+ default=None, description=""""""
+ )
+ new_system_instructions: Optional[str] = Field(default=None, description="""""")
+
+
+class ParsedResponseFewShotDict(TypedDict, total=False):
+ """Response for the optimize_prompt method."""
+
+ suggested_modifications: Optional[list[ApplicableGuidelineDict]]
+ """"""
+
+ original_system_instructions: Optional[str]
+ """"""
+
+ new_system_instructions: Optional[str]
+ """"""
+
+
+ParsedResponseFewShotOrDict = Union[ParsedResponseFewShot, ParsedResponseFewShotDict]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/prompts.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/prompts.py
new file mode 100644
index 0000000000000000000000000000000000000000..52c6c3058f9e932dac5d835dea05f4c8667c4877
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/types/prompts.py
@@ -0,0 +1,107 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Code generated by the Google Gen AI SDK generator DO NOT EDIT.
+
+from typing import Optional, Union
+from google.genai import _common
+from pydantic import Field
+from typing_extensions import TypedDict
+
+
+class ApplicableGuideline(_common.BaseModel):
+ """Applicable guideline for the optimize_prompt method."""
+
+ applicable_guideline: Optional[str] = Field(default=None, description="""""")
+ suggested_improvement: Optional[str] = Field(default=None, description="""""")
+ text_before_change: Optional[str] = Field(default=None, description="""""")
+ text_after_change: Optional[str] = Field(default=None, description="""""")
+
+
+class ApplicableGuidelineDict(TypedDict, total=False):
+ """Applicable guideline for the optimize_prompt method."""
+
+ applicable_guideline: Optional[str]
+ """"""
+
+ suggested_improvement: Optional[str]
+ """"""
+
+ text_before_change: Optional[str]
+ """"""
+
+ text_after_change: Optional[str]
+ """"""
+
+
+ApplicableGuidelineOrDict = Union[ApplicableGuideline, ApplicableGuidelineDict]
+
+
+class ParsedResponse(_common.BaseModel):
+ """Response for the optimize_prompt method."""
+
+ optimization_type: Optional[str] = Field(default=None, description="""""")
+ applicable_guidelines: Optional[list[ApplicableGuideline]] = Field(
+ default=None, description=""""""
+ )
+ original_prompt: Optional[str] = Field(default=None, description="""""")
+ suggested_prompt: Optional[str] = Field(default=None, description="""""")
+
+
+class ParsedResponseDict(TypedDict, total=False):
+ """Response for the optimize_prompt method."""
+
+ optimization_type: Optional[str]
+ """"""
+
+ applicable_guidelines: Optional[list[ApplicableGuidelineDict]]
+ """"""
+
+ original_prompt: Optional[str]
+ """"""
+
+ suggested_prompt: Optional[str]
+ """"""
+
+
+ParsedResponseOrDict = Union[ParsedResponse, ParsedResponseDict]
+
+
+class ParsedResponseFewShot(_common.BaseModel):
+ """Response for the optimize_prompt method."""
+
+ suggested_modifications: Optional[list[ApplicableGuideline]] = Field(
+ default=None, description=""""""
+ )
+ original_system_instructions: Optional[str] = Field(
+ default=None, description=""""""
+ )
+ new_system_instructions: Optional[str] = Field(default=None, description="""""")
+
+
+class ParsedResponseFewShotDict(TypedDict, total=False):
+ """Response for the optimize_prompt method."""
+
+ suggested_modifications: Optional[list[ApplicableGuidelineDict]]
+ """"""
+
+ original_system_instructions: Optional[str]
+ """"""
+
+ new_system_instructions: Optional[str]
+ """"""
+
+
+ParsedResponseFewShotOrDict = Union[ParsedResponseFewShot, ParsedResponseFewShotDict]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf515cd7c9866274eaa76710a71be59ca25cf542
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__init__.py
@@ -0,0 +1,424 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Classes and functions for working with agent engines."""
+
+from typing import Dict, Iterable, Optional, Sequence, Union
+
+from google.cloud.aiplatform import base
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform import utils as aip_utils
+from google.cloud.aiplatform_v1 import types as aip_types
+
+# We just want to re-export certain classes
+# pylint: disable=g-multiple-import,g-importing-member
+from agentplatform.agent_engines._agent_engines import (
+ _AgentEngineInterface,
+ AgentEngine,
+ Cloneable,
+ ModuleAgent,
+ OperationRegistrable,
+ Queryable,
+ AsyncQueryable,
+ StreamQueryable,
+ AsyncStreamQueryable,
+)
+from agentplatform.agent_engines.templates.adk import (
+ AdkApp,
+)
+from agentplatform.agent_engines.templates.ag2 import (
+ AG2Agent,
+)
+from agentplatform.agent_engines.templates.langchain import (
+ LangchainAgent,
+)
+from agentplatform.agent_engines.templates.langgraph import (
+ LanggraphAgent,
+)
+
+
+_LOGGER = base.Logger(__name__)
+
+
+def get(resource_name: str) -> AgentEngine:
+ """Retrieves an Agent Engine resource.
+
+ Args:
+ resource_name (str):
+ Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456" or
+ "456" when project and location are initialized or passed.
+ """
+ return AgentEngine(resource_name)
+
+
+def create(
+ agent_engine: Optional[_AgentEngineInterface] = None,
+ *,
+ requirements: Optional[Union[str, Sequence[str]]] = None,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ gcs_dir_name: Optional[str] = None,
+ extra_packages: Optional[Sequence[str]] = None,
+ env_vars: Optional[
+ Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
+ ] = None,
+ build_options: Optional[Dict[str, Sequence[str]]] = None,
+ service_account: Optional[str] = None,
+ psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[Dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+ encryption_spec: Optional[aip_types.EncryptionSpec] = None,
+) -> AgentEngine:
+ """Creates a new Agent Engine.
+
+ The Agent Engine will be an instance of the `agent_engine` that
+ was passed in, running remotely on Vertex AI.
+
+ Sample ``src_dir`` contents (e.g. ``./user_src_dir``):
+
+ .. code-block:: python
+
+ user_src_dir/
+ |-- main.py
+ |-- requirements.txt
+ |-- user_code/
+ | |-- utils.py
+ | |-- ...
+ |-- installation_scripts/
+ | |-- install_package.sh
+ | |-- ...
+ |-- ...
+
+ To build an Agent Engine with the above files, run:
+
+ .. code-block:: python
+
+ remote_agent = agent_engines.create(
+ agent_engine=local_agent,
+ requirements=[
+ # I.e. the PyPI dependencies listed in requirements.txt
+ "google-cloud-aiplatform==1.25.0",
+ "langchain==0.0.242",
+ ...
+ ],
+ extra_packages=[
+ "./user_src_dir/main.py", # a single file
+ "./user_src_dir/user_code", # a directory
+ ...
+ ],
+ build_options={
+ "installation": [
+ "./user_src_dir/installation_scripts/install_package.sh",
+ ...
+ ],
+ },
+ )
+
+ Args:
+ agent_engine (AgentEngineInterface):
+ Required. The Agent Engine to be created.
+ requirements (Union[str, Sequence[str]]):
+ Optional. The set of PyPI dependencies needed. It can either be
+ the path to a single file (requirements.txt), or an ordered list
+ of strings corresponding to each line of the requirements file.
+ display_name (str):
+ Optional. The user-defined name of the Agent Engine.
+ The name can be up to 128 characters long and can comprise any
+ UTF-8 character.
+ description (str):
+ Optional. The description of the Agent Engine.
+ gcs_dir_name (str):
+ Optional. The GCS bucket directory under `staging_bucket` to
+ use for staging the artifacts needed.
+ extra_packages (Sequence[str]):
+ Optional. The set of extra user-provided packages (if any).
+ env_vars (Union[Sequence[str], Dict[str, Union[str, SecretRef]]]):
+ Optional. The environment variables to be set when running the
+ Agent Engine. If it is a list of strings, each string should be
+ a valid key to `os.environ`. If it is a dictionary, the keys are
+ the environment variable names, and the values are the
+ corresponding values.
+ build_options (Dict[str, Sequence[str]]):
+ Optional. The build options for the Agent Engine. This includes
+ options such as installation scripts.
+ service_account (str):
+ Optional. The service account to be used for the Agent Engine. If
+ not specified, the default reasoning engine service agent service
+ account will be used.
+ psc_interface_config (PscInterfaceConfig):
+ Optional. The PSC interface config for the Agent Engine. If not
+ specified, the default PSC interface config will be used.
+ min_instances (int):
+ Optional. The minimum number of instances to run the Agent Engine.
+ If not specified, the default value will be used.
+ max_instances (int):
+ Optional. The maximum number of instances to run the Agent Engine.
+ If not specified, the default value will be used.
+ resource_limits (Dict[str, str]):
+ Optional. The resource limits for the Agent Engine. If not
+ specified, the default value will be used.
+ container_concurrency (int):
+ Optional. The container concurrency for the Agent Engine. If not
+ specified, the default value will be used.
+ encryption_spec (EncryptionSpec):
+ Optional. The encryption spec for the Agent Engine. If not
+ specified, the default encryption spec will be used.
+
+ Returns:
+ AgentEngine: The Agent Engine that was created.
+
+ Raises:
+ ValueError: If the `project` was not set using `agentplatform.init`.
+ ValueError: If the `location` was not set using `agentplatform.init`.
+ ValueError: If the `staging_bucket` was not set using agentplatform.init.
+ ValueError: If the `staging_bucket` does not start with "gs://".
+ FileNotFoundError: If `extra_packages` includes a file or directory
+ that does not exist.
+ IOError: If requirements is a string that corresponds to a
+ nonexistent file.
+ """
+ return AgentEngine.create(
+ agent_engine=agent_engine,
+ requirements=requirements,
+ display_name=display_name,
+ description=description,
+ gcs_dir_name=gcs_dir_name,
+ extra_packages=extra_packages,
+ env_vars=env_vars,
+ build_options=build_options,
+ service_account=service_account,
+ psc_interface_config=psc_interface_config,
+ min_instances=min_instances,
+ max_instances=max_instances,
+ resource_limits=resource_limits,
+ container_concurrency=container_concurrency,
+ encryption_spec=encryption_spec,
+ )
+
+
+def list(*, filter: str = "") -> Iterable[AgentEngine]:
+ """List all instances of Agent Engine matching the filter.
+
+ Example Usage:
+
+ .. code-block:: python
+ import agentplatform
+ from agentplatform import agent_engines
+
+ agentplatform.init(project="my_project", location="us-central1")
+ agent_engines.list(filter='display_name="My Custom Agent"')
+
+ Args:
+ filter (str):
+ Optional. An expression for filtering the results of the request.
+ For field names both snake_case and camelCase are supported.
+
+ Returns:
+ Iterable[AgentEngine]: An iterable of Agent Engines matching the filter.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=aip_utils.AgentEngineClientWithOverride,
+ )
+ for agent in api_client.list_reasoning_engines(
+ request=aip_types.ListReasoningEnginesRequest(
+ parent=initializer.global_config.common_location_path(),
+ filter=filter,
+ )
+ ):
+ yield AgentEngine(agent.name)
+
+
+def delete(
+ resource_name: str,
+ *,
+ force: bool = False,
+ **kwargs,
+) -> None:
+ """Delete an Agent Engine resource.
+
+ Args:
+ resource_name (str):
+ Required. The name of the Agent Engine to be deleted. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
+ force (bool):
+ Optional. If set to True, child resources will also be deleted.
+ Otherwise, the request will fail with FAILED_PRECONDITION error
+ when the Agent Engine has undeleted child resources. Defaults to
+ False.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ delete_reasoning_engine method.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=aip_utils.AgentEngineClientWithOverride,
+ )
+ _LOGGER.info(f"Deleting AgentEngine resource: {resource_name}")
+ operation_future = api_client.delete_reasoning_engine(
+ request=aip_types.DeleteReasoningEngineRequest(
+ name=resource_name,
+ force=force,
+ **(kwargs or {}),
+ )
+ )
+ _LOGGER.info(f"Delete AgentEngine backing LRO: {operation_future.operation.name}")
+ operation_future.result()
+ _LOGGER.info(f"AgentEngine resource deleted: {resource_name}")
+
+
+def update(
+ resource_name: str,
+ *,
+ agent_engine: Optional[Union[Queryable, OperationRegistrable]] = None,
+ requirements: Optional[Union[str, Sequence[str]]] = None,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ gcs_dir_name: Optional[str] = None,
+ extra_packages: Optional[Sequence[str]] = None,
+ env_vars: Optional[
+ Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
+ ] = None,
+ build_options: Optional[Dict[str, Sequence[str]]] = None,
+ service_account: Optional[str] = None,
+ psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[Dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+ encryption_spec: Optional[aip_types.EncryptionSpec] = None,
+) -> "AgentEngine":
+ """Updates an existing Agent Engine.
+
+ This method updates the configuration of a deployed Agent Engine, identified
+ by its resource name. Unlike the `create` function which requires an
+ `agent_engine` object, all arguments in this method are optional. This
+ method allows you to modify individual aspects of the configuration by
+ providing any of the optional arguments.
+
+ Args:
+ resource_name (str):
+ Required. The name of the Agent Engine to be updated. Format:
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
+ agent_engine (AgentEngineInterface):
+ Optional. The instance to be used as the updated Agent Engine. If it
+ is not specified, the existing instance will be used.
+ requirements (Union[str, Sequence[str]]):
+ Optional. The set of PyPI dependencies needed. It can either be
+ the path to a single file (requirements.txt), or an ordered list
+ of strings corresponding to each line of the requirements file.
+ If it is not specified, the existing requirements will be used.
+ If it is set to an empty string or list, the existing
+ requirements will be removed.
+ display_name (str):
+ Optional. The user-defined name of the Agent Engine.
+ The name can be up to 128 characters long and can comprise any
+ UTF-8 character.
+ description (str):
+ Optional. The description of the Agent Engine.
+ gcs_dir_name (str):
+ Optional. The GCS bucket directory under `staging_bucket` to
+ use for staging the artifacts needed.
+ extra_packages (Sequence[str]):
+ Optional. The set of extra user-provided packages (if any). If
+ it is not specified, the existing extra packages will be used.
+ If it is set to an empty list, the existing extra packages will
+ be removed.
+ env_vars (Union[Sequence[str], Dict[str, Union[str, SecretRef]]]):
+ Optional. The environment variables to be set when running the
+ Agent Engine. If it is a list of strings, each string should be
+ a valid key to `os.environ`. If it is a dictionary, the keys are
+ the environment variable names, and the values are the
+ corresponding values.
+ build_options (Dict[str, Sequence[str]]):
+ Optional. The build options for the Agent Engine. This includes
+ options such as installation scripts.
+ service_account (str):
+ Optional. The service account to be used for the Agent Engine. If
+ not specified, the default reasoning engine service agent service
+ account will be used.
+ min_instances (int):
+ Optional. The minimum number of instances to run the Agent Engine.
+ If not specified, the default value will be used.
+ max_instances (int):
+ Optional. The maximum number of instances to run the Agent Engine.
+ If not specified, the default value will be used.
+ resource_limits (Dict[str, str]):
+ Optional. The resource limits for the Agent Engine. If not
+ specified, the default value will be used.
+ container_concurrency (int):
+ Optional. The container concurrency for the Agent Engine. If not
+ specified, the default value will be used.
+ encryption_spec (EncryptionSpec):
+ Optional. The encryption spec for the Agent Engine. If not
+ specified, the default encryption spec will be used.
+
+ Returns:
+ AgentEngine: The Agent Engine that was updated.
+
+ Raises:
+ ValueError: If the `staging_bucket` was not set using agentplatform.init.
+ ValueError: If the `staging_bucket` does not start with "gs://".
+ FileNotFoundError: If `extra_packages` includes a file or directory
+ that does not exist.
+ ValueError: if none of `display_name`, `description`,
+ `requirements`, `extra_packages`, `agent_engine`, or `build_options`
+ were specified.
+ IOError: If requirements is a string that corresponds to a
+ nonexistent file.
+ """
+ agent = get(resource_name)
+ return agent.update(
+ agent_engine=agent_engine,
+ requirements=requirements,
+ display_name=display_name,
+ description=description,
+ gcs_dir_name=gcs_dir_name,
+ extra_packages=extra_packages,
+ env_vars=env_vars,
+ build_options=build_options,
+ service_account=service_account,
+ psc_interface_config=psc_interface_config,
+ min_instances=min_instances,
+ max_instances=max_instances,
+ resource_limits=resource_limits,
+ container_concurrency=container_concurrency,
+ encryption_spec=encryption_spec,
+ )
+
+
+__all__ = (
+ # Resources
+ "AgentEngine",
+ # Protocols
+ "Cloneable",
+ "OperationRegistrable",
+ "Queryable",
+ "AsyncQueryable",
+ "StreamQueryable",
+ "AsyncStreamQueryable",
+ # Methods
+ "create",
+ "delete",
+ "get",
+ "list",
+ "update",
+ # Templates
+ "AdkApp",
+ "ModuleAgent",
+ "LangchainAgent",
+ "LanggraphAgent",
+ "AG2Agent",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d1bd81716db742997b17f353fd9a323cd3c7630
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/_agent_engines.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/_agent_engines.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5733700e96792a9a42629f7ed90234f83d384a64
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/_agent_engines.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a23f5c5a823e48370526c10a4b82735ef54f336a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/__pycache__/_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/_agent_engines.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/_agent_engines.py
new file mode 100644
index 0000000000000000000000000000000000000000..48d44fa51e413a19f6947bec2baa1f8056441e94
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/_agent_engines.py
@@ -0,0 +1,2016 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import abc
+import inspect
+import io
+import json
+import logging
+import os
+import sys
+import tarfile
+import types
+import typing
+from typing import (
+ Any,
+ AsyncIterable,
+ Callable,
+ Coroutine,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Protocol,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+from google.api_core import exceptions
+from google.cloud import storage
+from google.cloud.aiplatform import base
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform import utils as aip_utils
+from google.cloud.aiplatform_v1 import types as aip_types
+from google.cloud.aiplatform_v1.types import reasoning_engine_service
+from agentplatform.agent_engines import _utils
+import httpx
+import proto
+
+from google.protobuf import field_mask_pb2
+
+
+_LOGGER = _utils.LOGGER
+_SUPPORTED_PYTHON_VERSIONS = ("3.10", "3.11", "3.12", "3.13", "3.14")
+_DEFAULT_GCS_DIR_NAME = "agent_engine"
+_BLOB_FILENAME = "agent_engine.pkl"
+_REQUIREMENTS_FILE = "requirements.txt"
+_EXTRA_PACKAGES_FILE = "dependencies.tar.gz"
+_STANDARD_API_MODE = ""
+_ASYNC_API_MODE = "async"
+_STREAM_API_MODE = "stream"
+_ASYNC_STREAM_API_MODE = "async_stream"
+_BIDI_STREAM_API_MODE = "bidi_stream"
+_A2A_EXTENSION_MODE = "a2a_extension"
+_A2A_AGENT_CARD = "a2a_agent_card"
+_MODE_KEY_IN_SCHEMA = "api_mode"
+_METHOD_NAME_KEY_IN_SCHEMA = "name"
+_DEFAULT_METHOD_NAME = "query"
+_DEFAULT_ASYNC_METHOD_NAME = "async_query"
+_DEFAULT_STREAM_METHOD_NAME = "stream_query"
+_DEFAULT_ASYNC_STREAM_METHOD_NAME = "async_stream_query"
+_DEFAULT_METHOD_RETURN_TYPE = "dict[str, Any]"
+_DEFAULT_ASYNC_METHOD_RETURN_TYPE = "Coroutine[Any, Any, Any]"
+_DEFAULT_STREAM_METHOD_RETURN_TYPE = "Iterable[Any]"
+_DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE = "AsyncIterable[Any]"
+_DEFAULT_METHOD_DOCSTRING_TEMPLATE = """
+ Runs the Agent Engine to serve the user request.
+ This will be based on the `.{method_name}(...)` of the python object that
+ was passed in when creating the Agent Engine. The method will invoke the
+ `{default_method_name}` API client of the python object.
+ Args:
+ **kwargs:
+ Optional. The arguments of the `.{method_name}(...)` method.
+ Returns:
+ {return_type}: The response from serving the user request.
+"""
+_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE = (
+ "Failed to register API methods. Please follow the guide to "
+ "register the API methods: "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#custom-methods. "
+ "Error: {%s}"
+)
+_AGENT_FRAMEWORK_ATTR = "agent_framework"
+_DEFAULT_AGENT_FRAMEWORK = "custom"
+_BUILD_OPTIONS_INSTALLATION = "installation_scripts"
+_DEFAULT_METHOD_NAME_MAP = {
+ _STANDARD_API_MODE: _DEFAULT_METHOD_NAME,
+ _ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_NAME,
+ _STREAM_API_MODE: _DEFAULT_STREAM_METHOD_NAME,
+ _ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_NAME,
+}
+_DEFAULT_METHOD_RETURN_TYPE_MAP = {
+ _STANDARD_API_MODE: _DEFAULT_METHOD_RETURN_TYPE,
+ _ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_RETURN_TYPE,
+ _STREAM_API_MODE: _DEFAULT_STREAM_METHOD_RETURN_TYPE,
+ _ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE,
+}
+
+
+try:
+ from google.adk.agents import BaseAgent
+
+ ADKAgent = BaseAgent
+except (ImportError, AttributeError):
+ ADKAgent = None
+
+try:
+ from a2a.types import (
+ AgentCard,
+ AgentInterface,
+ Message,
+ TaskIdParams,
+ TaskQueryParams,
+ )
+ from a2a.utils.constants import TransportProtocol, PROTOCOL_VERSION_CURRENT
+ from a2a.client import ClientConfig, ClientFactory
+
+ AgentCard = AgentCard
+ AgentInterface = AgentInterface
+ TransportProtocol = TransportProtocol
+ PROTOCOL_VERSION_CURRENT = PROTOCOL_VERSION_CURRENT
+ Message = Message
+ ClientConfig = ClientConfig
+ ClientFactory = ClientFactory
+ TaskIdParams = TaskIdParams
+ TaskQueryParams = TaskQueryParams
+except (ImportError, AttributeError):
+ AgentCard = None
+ AgentInterface = None
+ TransportProtocol = None
+ PROTOCOL_VERSION_CURRENT = None
+ Message = None
+ ClientConfig = None
+ ClientFactory = None
+ TaskIdParams = None
+ TaskQueryParams = None
+
+
+@typing.runtime_checkable
+class Queryable(Protocol):
+ """Protocol for Agent Engines that can be queried."""
+
+ @abc.abstractmethod
+ def query(self, **kwargs) -> Any:
+ """Runs the Agent Engine to serve the user query."""
+
+
+@typing.runtime_checkable
+class AsyncQueryable(Protocol):
+ """Protocol for Agent Engines that can be queried asynchronously."""
+
+ @abc.abstractmethod
+ def async_query(self, **kwargs) -> Coroutine[Any, Any, Any]:
+ """Runs the Agent Engine to serve the user query asynchronously."""
+
+
+@typing.runtime_checkable
+class AsyncStreamQueryable(Protocol):
+ """Protocol for Agent Engines that can stream responses asynchronously."""
+
+ @abc.abstractmethod
+ async def async_stream_query(self, **kwargs) -> AsyncIterable[Any]:
+ """Asynchronously stream responses to serve the user query."""
+
+
+@typing.runtime_checkable
+class StreamQueryable(Protocol):
+ """Protocol for Agent Engines that can stream responses."""
+
+ @abc.abstractmethod
+ def stream_query(self, **kwargs) -> Iterable[Any]:
+ """Stream responses to serve the user query."""
+
+
+@typing.runtime_checkable
+class BidiStreamQueryable(Protocol):
+ """Protocol for Agent Engines that can stream requests and responses."""
+
+ @abc.abstractmethod
+ async def bidi_stream_query(self, **kwargs) -> AsyncIterable[Any]:
+ """Asynchronously stream requests and responses to serve the user query."""
+
+
+@typing.runtime_checkable
+class Cloneable(Protocol):
+ """Protocol for Agent Engines that can be cloned."""
+
+ @abc.abstractmethod
+ def clone(self) -> Any:
+ """Return a clone of the object."""
+
+
+@typing.runtime_checkable
+class OperationRegistrable(Protocol):
+ """Protocol for agents that have registered operations."""
+
+ @abc.abstractmethod
+ def register_operations(self, **kwargs) -> Dict[str, Sequence[str]]:
+ """Register the user provided operations (modes and methods)."""
+
+
+_AgentEngineInterface = Union[
+ ADKAgent,
+ AsyncQueryable,
+ AsyncStreamQueryable,
+ BidiStreamQueryable,
+ OperationRegistrable,
+ Queryable,
+ StreamQueryable,
+]
+
+
+def _wrap_agent_operation(agent: Any, operation: str):
+ """Wraps an agent operation into a method (works for all API modes)."""
+
+ def _method(self, **kwargs):
+ if not self._tmpl_attrs.get("agent"):
+ self.set_up()
+ return getattr(self._tmpl_attrs["agent"], operation)(**kwargs)
+
+ _method.__name__ = operation
+ _method.__doc__ = getattr(agent, operation).__doc__
+ return _method
+
+
+class ModuleAgent(Cloneable, OperationRegistrable):
+ """Agent that is defined by a module and an agent name.
+
+ This agent is instantiated by importing a module and instantiating an agent
+ from that module. It also allows to register operations that are defined in
+ the agent.
+ """
+
+ def __init__(
+ self,
+ *,
+ module_name: str,
+ agent_name: str,
+ register_operations: Dict[str, Sequence[str]],
+ sys_paths: Optional[Sequence[str]] = None,
+ agent_framework: Optional[str] = None,
+ ):
+ """Initializes a module-based agent.
+
+ Args:
+ module_name (str):
+ Required. The name of the module to import.
+ agent_name (str):
+ Required. The name of the agent in the module to instantiate.
+ register_operations (Dict[str, Sequence[str]]):
+ Required. A dictionary of API modes to a list of method names.
+ sys_paths (Sequence[str]):
+ Optional. The system paths to search for the module. It should
+ be relative to the directory where the code will be running.
+ I.e. it should correspond to the directory being passed to
+ `extra_packages=...` in the create method. It will be appended
+ to the system path in the sequence being specified here, and
+ only be appended if it is not already in the system path.
+ """
+ self.agent_framework = agent_framework
+ self._tmpl_attrs = {
+ "module_name": module_name,
+ "agent_name": agent_name,
+ "register_operations": register_operations,
+ "sys_paths": sys_paths,
+ }
+
+ def clone(self):
+ """Return a clone of the agent."""
+ return ModuleAgent(
+ module_name=self._tmpl_attrs.get("module_name"),
+ agent_name=self._tmpl_attrs.get("agent_name"),
+ register_operations=self._tmpl_attrs.get("register_operations"),
+ sys_paths=self._tmpl_attrs.get("sys_paths"),
+ agent_framework=self.agent_framework,
+ )
+
+ def register_operations(self, **kwargs) -> Dict[str, Sequence[str]]:
+ return self._tmpl_attrs.get("register_operations")
+
+ def set_up(self) -> None:
+ """Sets up the agent for execution of queries at runtime.
+
+ It runs the code to import the agent from the module, and registers the
+ operations of the agent.
+ """
+ if self._tmpl_attrs.get("sys_paths"):
+ import sys
+
+ for sys_path in self._tmpl_attrs.get("sys_paths"):
+ abs_path = os.path.abspath(sys_path)
+ if abs_path not in sys.path:
+ sys.path.append(abs_path)
+
+ import importlib
+
+ module = importlib.import_module(self._tmpl_attrs.get("module_name"))
+ try:
+ importlib.reload(module)
+ except Exception as e:
+ _LOGGER.warning(
+ f"Failed to reload module {self._tmpl_attrs.get('module_name')}: {e}"
+ )
+ agent_name = self._tmpl_attrs.get("agent_name")
+ try:
+ agent = getattr(module, agent_name)
+ except AttributeError as e:
+ raise AttributeError(
+ f"Agent {agent_name} not found in module "
+ f"{self._tmpl_attrs.get('module_name')}"
+ ) from e
+ if not self.agent_framework:
+ self.agent_framework = _get_agent_framework(agent)
+ self._tmpl_attrs["agent"] = agent
+ if hasattr(agent, "set_up"):
+ agent.set_up()
+ for operations in self.register_operations().values():
+ for operation in operations:
+ op = _wrap_agent_operation(agent, operation)
+ setattr(self, operation, types.MethodType(op, self))
+
+
+class AgentEngine(base.VertexAiResourceNounWithFutureManager):
+ """Represents a Vertex AI Agent Engine resource."""
+
+ client_class = aip_utils.AgentEngineClientWithOverride
+ _resource_noun = "reasoning_engine"
+ _getter_method = "get_reasoning_engine"
+ _list_method = "list_reasoning_engines"
+ _delete_method = "delete_reasoning_engine"
+ _parse_resource_name_method = "parse_reasoning_engine_path"
+ _format_resource_name_method = "reasoning_engine_path"
+
+ def __init__(self, resource_name: str):
+ """Retrieves an Agent Engine resource.
+
+ Args:
+ resource_name (str):
+ Required. A fully-qualified resource name or ID such as
+ "projects/123/locations/us-central1/reasoningEngines/456" or
+ "456" when project and location are initialized or passed.
+ """
+ super().__init__(resource_name=resource_name)
+ self.execution_api_client = initializer.global_config.create_client(
+ client_class=aip_utils.AgentEngineExecutionClientWithOverride,
+ )
+ self.execution_async_client = initializer.global_config.create_client(
+ client_class=aip_utils.AgentEngineExecutionAsyncClientWithOverride,
+ )
+ self._gca_resource = self._get_gca_resource(resource_name=resource_name)
+ try:
+ _register_api_methods_or_raise(self)
+ except Exception as e:
+ _LOGGER.warning(_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e)
+ self._operation_schemas = None
+
+ @property
+ def resource_name(self) -> str:
+ """Fully-qualified resource name."""
+ return self._gca_resource.name
+
+ @classmethod
+ def create(
+ cls,
+ agent_engine: Optional[_AgentEngineInterface] = None,
+ *,
+ requirements: Optional[Union[str, Sequence[str]]] = None,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ gcs_dir_name: Optional[str] = None,
+ extra_packages: Optional[Sequence[str]] = None,
+ env_vars: Optional[
+ Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
+ ] = None,
+ build_options: Optional[Dict[str, Sequence[str]]] = None,
+ service_account: Optional[str] = None,
+ psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[Dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+ encryption_spec: Optional[aip_types.EncryptionSpec] = None,
+ ) -> "AgentEngine":
+ """Creates a new Agent Engine.
+
+ The Agent Engine will be an instance of the `agent_engine` that
+ was passed in, running remotely on Vertex AI.
+
+ Sample `src_dir` contents (e.g. `./user_src_dir`):
+
+ .. code-block:: python
+
+ user_src_dir/
+ |-- main.py
+ |-- requirements.txt
+ |-- user_code/
+ | |-- utils.py
+ | |-- ...
+ |-- installation_scripts/
+ | |-- install_package.sh
+ | |-- ...
+ |-- ...
+
+ To build an Agent Engine with the above files, run:
+
+ .. code-block:: python
+
+ remote_agent = agent_engines.create(
+ agent_engine=local_agent,
+ requirements=[
+ # I.e. the PyPI dependencies listed in requirements.txt
+ "google-cloud-aiplatform==1.25.0",
+ "langchain==0.0.242",
+ ...
+ ],
+ extra_packages=[
+ "./user_src_dir/main.py", # a single file
+ "./user_src_dir/user_code", # a directory
+ ...
+ ],
+ build_options={
+ "installation_scripts": [
+ "./user_src_dir/installation_scripts/install_package.sh",
+ ...
+ ],
+ },
+ )
+
+ Args:
+ agent_engine (AgentEngineInterface):
+ Optional. The Agent Engine to be created.
+ requirements (Union[str, Sequence[str]]):
+ Optional. The set of PyPI dependencies needed. It can either be
+ the path to a single file (requirements.txt), or an ordered list
+ of strings corresponding to each line of the requirements file.
+ display_name (str):
+ Optional. The user-defined name of the Agent Engine.
+ The name can be up to 128 characters long and can comprise any
+ UTF-8 character.
+ description (str):
+ Optional. The description of the Agent Engine.
+ gcs_dir_name (str):
+ Optional. The GCS bucket directory under `staging_bucket` to
+ use for staging the artifacts needed.
+ extra_packages (Sequence[str]):
+ Optional. The set of extra user-provided packages (if any).
+ env_vars (Union[Sequence[str], Dict[str, Union[str, SecretRef]]]):
+ Optional. The environment variables to be set when running the
+ Agent Engine. If it is a list of strings, each string should be
+ a valid key to `os.environ`. If it is a dictionary, the keys are
+ the environment variable names, and the values are the
+ corresponding values.
+ build_options (Dict[str, Sequence[str]]):
+ Optional. The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ service_account (str):
+ Optional. The service account to be used for the Agent Engine.
+ If not specified, the default reasoning engine service agent
+ service account will be used.
+ psc_interface_config (aip_types.PscInterfaceConfig):
+ Optional. The Private Service Connect interface config for the
+ Agent Engine.
+ min_instances (int):
+ Optional. The minimum number of instances to be running for the
+ Agent Engine.
+ max_instances (int):
+ Optional. The maximum number of instances to be running for the
+ Agent Engine.
+ resource_limits (Dict[str, str]):
+ Optional. The resource limits for the Agent Engine.
+ container_concurrency (int):
+ Optional. The container concurrency for the Agent Engine.
+ encryption_spec (aip_types.EncryptionSpec):
+ Optional. The Cloud KMS resource identifier of the customer
+ managed encryption key used to protect the model. Has the
+ form:
+ `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`.
+ The key needs to be in the same region as the model.
+
+ Returns:
+ AgentEngine: The Agent Engine that was created.
+
+ Raises:
+ ValueError: If the `project` was not set using `agentplatform.init`.
+ ValueError: If the `location` was not set using `agentplatform.init`.
+ ValueError: If the `staging_bucket` was not set using agentplatform.init.
+ ValueError: If the `staging_bucket` does not start with "gs://".
+ ValueError: If `extra_packages` is specified but `agent_engine` is None.
+ ValueError: If `requirements` is specified but `agent_engine` is None.
+ ValueError: If `env_vars` has a dictionary entry that does not
+ correspond to a SecretRef.
+ ValueError: If `env_vars` is a list which contains a string that
+ does not exist in `os.environ`.
+ TypeError: If `env_vars` is not a list of strings or a dictionary.
+ TypeError: If `env_vars` has a value that is not a string or SecretRef.
+ FileNotFoundError: If `extra_packages` includes a file or directory
+ that does not exist.
+ IOError: If requirements is a string that corresponds to a
+ nonexistent file.
+ """
+ sys_version = f"{sys.version_info.major}.{sys.version_info.minor}"
+ _validate_sys_version_or_raise(sys_version)
+ gcs_dir_name = gcs_dir_name or _DEFAULT_GCS_DIR_NAME
+ staging_bucket = initializer.global_config.staging_bucket
+
+ if agent_engine is not None:
+ agent_engine = _validate_agent_engine_or_raise(agent_engine)
+ staging_bucket = _validate_staging_bucket_or_raise(staging_bucket)
+ if _is_adk_agent(None, agent_engine):
+ env_vars = _add_telemetry_enablement_env(env_vars=env_vars)
+
+ if agent_engine is None:
+ if requirements is not None:
+ raise ValueError("requirements must be None if agent_engine is None.")
+ if extra_packages is not None:
+ raise ValueError("extra_packages must be None if agent_engine is None.")
+ requirements = _validate_requirements_or_raise(
+ agent_engine=agent_engine,
+ requirements=requirements,
+ )
+ extra_packages = _validate_extra_packages_or_raise(
+ extra_packages=extra_packages,
+ build_options=build_options,
+ )
+
+ sdk_resource = cls.__new__(cls)
+ base.VertexAiResourceNounWithFutureManager.__init__(sdk_resource)
+
+ # Prepares the Agent Engine for creation in Vertex AI.
+ # This involves packaging and uploading the artifacts for
+ # agent_engine, requirements and extra_packages to
+ # `staging_bucket/gcs_dir_name`.
+ _prepare(
+ agent_engine=agent_engine,
+ requirements=requirements,
+ project=sdk_resource.project,
+ location=sdk_resource.location,
+ staging_bucket=staging_bucket,
+ gcs_dir_name=gcs_dir_name,
+ extra_packages=extra_packages,
+ )
+ reasoning_engine = aip_types.ReasoningEngine(
+ display_name=display_name,
+ description=description,
+ encryption_spec=encryption_spec,
+ )
+ if agent_engine is not None:
+ # Update the package spec.
+ package_spec = aip_types.ReasoningEngineSpec.PackageSpec(
+ python_version=sys_version,
+ pickle_object_gcs_uri="{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _BLOB_FILENAME,
+ ),
+ )
+ if extra_packages:
+ package_spec.dependency_files_gcs_uri = "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _EXTRA_PACKAGES_FILE,
+ )
+ if requirements:
+ package_spec.requirements_gcs_uri = "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _REQUIREMENTS_FILE,
+ )
+ agent_engine_spec = aip_types.ReasoningEngineSpec(
+ package_spec=package_spec,
+ )
+ if (
+ env_vars
+ or psc_interface_config
+ or min_instances is not None
+ or max_instances is not None
+ or resource_limits
+ or container_concurrency is not None
+ ):
+ deployment_spec, _ = _generate_deployment_spec_or_raise(
+ env_vars=env_vars,
+ psc_interface_config=psc_interface_config,
+ min_instances=min_instances,
+ max_instances=max_instances,
+ resource_limits=resource_limits,
+ container_concurrency=container_concurrency,
+ )
+ agent_engine_spec.deployment_spec = deployment_spec
+ class_methods_spec = _generate_class_methods_spec_or_raise(
+ agent_engine=agent_engine,
+ operations=_get_registered_operations(agent_engine),
+ )
+ agent_engine_spec.class_methods.extend(class_methods_spec)
+ if service_account:
+ agent_engine_spec.service_account = service_account
+ reasoning_engine.spec = agent_engine_spec
+ reasoning_engine.spec.agent_framework = _get_agent_framework(agent_engine)
+ operation_future = sdk_resource.api_client.create_reasoning_engine(
+ parent=initializer.global_config.common_location_path(
+ project=sdk_resource.project, location=sdk_resource.location
+ ),
+ reasoning_engine=reasoning_engine,
+ )
+ _LOGGER.log_create_with_lro(cls, operation_future)
+ _LOGGER.info(
+ f"View progress and logs at https://console.cloud.google.com/logs/query?project={sdk_resource.project}"
+ )
+ created_resource = operation_future.result()
+ _LOGGER.info(f"{cls.__name__} created. Resource name: {created_resource.name}")
+ _LOGGER.info(f"To use this {cls.__name__} in another session:")
+ _LOGGER.info(
+ f"agent_engine = agentplatform.agent_engines.get('{created_resource.name}')"
+ )
+ # We use `._get_gca_resource(...)` instead of `created_resource` to
+ # fully instantiate the attributes of the agent engine.
+ sdk_resource._gca_resource = sdk_resource._get_gca_resource(
+ resource_name=created_resource.name
+ )
+ sdk_resource.execution_api_client = initializer.global_config.create_client(
+ client_class=aip_utils.AgentEngineExecutionClientWithOverride,
+ credentials=sdk_resource.credentials,
+ location_override=sdk_resource.location,
+ )
+ sdk_resource.execution_async_client = initializer.global_config.create_client(
+ client_class=aip_utils.AgentEngineExecutionAsyncClientWithOverride,
+ credentials=sdk_resource.credentials,
+ location_override=sdk_resource.location,
+ )
+ if agent_engine is not None:
+ try:
+ _register_api_methods_or_raise(sdk_resource)
+ except Exception as e:
+ _LOGGER.warning(_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e)
+ sdk_resource._operation_schemas = None
+ return sdk_resource
+
+ def update(
+ self,
+ *,
+ agent_engine: Optional[_AgentEngineInterface] = None,
+ requirements: Optional[Union[str, Sequence[str]]] = None,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ gcs_dir_name: Optional[str] = None,
+ extra_packages: Optional[Sequence[str]] = None,
+ env_vars: Optional[
+ Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
+ ] = None,
+ build_options: Optional[Dict[str, Sequence[str]]] = None,
+ service_account: Optional[str] = None,
+ psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[Dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+ encryption_spec: Optional[aip_types.EncryptionSpec] = None,
+ ) -> "AgentEngine":
+ """Updates an existing Agent Engine.
+
+ This method updates the configuration of an existing Agent Engine
+ running remotely, which is identified by its resource name.
+ Unlike the `create` function which requires a `agent_engine` object,
+ all arguments in this method are optional.
+ This method allows you to modify individual aspects of the configuration
+ by providing any of the optional arguments.
+
+ Args:
+ agent_engine (AgentEngineInterface):
+ Optional. The instance to be used as the updated Agent Engine.
+ If it is not specified, the existing instance will be used.
+ requirements (Union[str, Sequence[str]]):
+ Optional. The set of PyPI dependencies needed. It can either be
+ the path to a single file (requirements.txt), or an ordered list
+ of strings corresponding to each line of the requirements file.
+ If it is not specified, the existing requirements will be used.
+ If it is set to an empty string or list, the existing
+ requirements will be removed.
+ display_name (str):
+ Optional. The user-defined name of the Agent Engine.
+ The name can be up to 128 characters long and can comprise any
+ UTF-8 character.
+ description (str):
+ Optional. The description of the Agent Engine.
+ gcs_dir_name (str):
+ Optional. The GCS bucket directory under `staging_bucket` to
+ use for staging the artifacts needed.
+ extra_packages (Sequence[str]):
+ Optional. The set of extra user-provided packages (if any). If
+ it is not specified, the existing extra packages will be used.
+ If it is set to an empty list, the existing extra packages will
+ be removed.
+ env_vars (Union[Sequence[str], Dict[str, Union[str, SecretRef]]]):
+ Optional. The environment variables to be set when running the
+ Agent Engine. If it is a list of strings, each string should be
+ a valid key to `os.environ`. If it is a dictionary, the keys are
+ the environment variable names, and the values are the
+ corresponding values.
+ build_options (Dict[str, Sequence[str]]):
+ Optional. The build options for the Agent Engine.
+ The following keys are supported:
+ - installation_scripts:
+ Optional. The paths to the installation scripts to be
+ executed in the Docker image.
+ The scripts must be located in the `installation_scripts`
+ subdirectory and the path must be added to `extra_packages`.
+ service_account (str):
+ Optional. The service account to be used for the Agent Engine.
+ If not specified, the default reasoning engine service agent
+ service account will be used.
+ psc_interface_config (aip_types.PscInterfaceConfig):
+ Optional. The Private Service Connect interface config for the
+ Agent Engine.
+ min_instances (int):
+ Optional. The minimum number of instances to be running for the
+ Agent Engine.
+ max_instances (int):
+ Optional. The maximum number of instances to be running for the
+ Agent Engine.
+ resource_limits (Dict[str, str]):
+ Optional. The resource limits for the Agent Engine.
+ container_concurrency (int):
+ Optional. The container concurrency for the Agent Engine.
+ encryption_spec (aip_types.EncryptionSpec):
+ Optional. The Cloud KMS resource identifier of the customer
+ managed encryption key used to protect the model. Has the
+ form:
+ `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`.
+ The key needs to be in the same region as the model.
+
+ Returns:
+ AgentEngine: The Agent Engine that was updated.
+
+ Raises:
+ ValueError: If the `staging_bucket` was not set using agentplatform.init.
+ ValueError: If the `staging_bucket` does not start with "gs://".
+ ValueError: If `env_vars` has a dictionary entry that does not
+ correspond to a SecretRef.
+ ValueError: If `env_vars` is a list which contains a string that
+ does not exist in `os.environ`.
+ TypeError: If `env_vars` is not a list of strings or a dictionary.
+ TypeError: If `env_vars` has a value that is not a string or SecretRef.
+ FileNotFoundError: If `extra_packages` includes a file or directory
+ that does not exist.
+ ValueError: if none of `display_name`, `description`, `requirements`,
+ `extra_packages`, `env_vars`, or `agent_engine` were specified.
+ IOError: If requirements is a string that corresponds to a
+ nonexistent file.
+ """
+ staging_bucket = initializer.global_config.staging_bucket
+ staging_bucket = _validate_staging_bucket_or_raise(staging_bucket)
+ historical_operation_schemas = self.operation_schemas()
+ gcs_dir_name = gcs_dir_name or _DEFAULT_GCS_DIR_NAME
+
+ # Validate the arguments.
+ if not any(
+ [
+ agent_engine,
+ requirements,
+ extra_packages,
+ display_name,
+ description,
+ env_vars,
+ build_options,
+ service_account,
+ psc_interface_config,
+ min_instances is not None,
+ max_instances is not None,
+ resource_limits,
+ container_concurrency is not None,
+ encryption_spec,
+ ]
+ ):
+ raise ValueError(
+ "At least one of `agent_engine`, `requirements`, "
+ "`extra_packages`, `display_name`, `description`, "
+ "`env_vars`, `build_options`, `service_account`, "
+ "`psc_interface_config`, `min_instances`, `max_instances`, "
+ "`resource_limits`, `container_concurrency`, or "
+ "`encryption_spec` must be specified."
+ )
+ if requirements is not None:
+ requirements = _validate_requirements_or_raise(
+ agent_engine=agent_engine,
+ requirements=requirements,
+ )
+ if extra_packages is not None:
+ extra_packages = _validate_extra_packages_or_raise(
+ extra_packages=extra_packages,
+ build_options=build_options,
+ )
+ if agent_engine is not None:
+ agent_engine = _validate_agent_engine_or_raise(agent_engine)
+
+ if _is_adk_agent(self, agent_engine):
+ env_vars = _add_telemetry_enablement_env(env_vars=env_vars)
+
+ # Prepares the Agent Engine for update in Vertex AI. This involves
+ # packaging and uploading the artifacts for agent_engine, requirements
+ # and extra_packages to `staging_bucket/gcs_dir_name`.
+ _prepare(
+ agent_engine=agent_engine,
+ requirements=requirements,
+ project=self.project,
+ location=self.location,
+ staging_bucket=staging_bucket,
+ gcs_dir_name=gcs_dir_name,
+ extra_packages=extra_packages,
+ )
+ update_request = _generate_update_request_or_raise(
+ resource_name=self.resource_name,
+ staging_bucket=staging_bucket,
+ gcs_dir_name=gcs_dir_name,
+ agent_engine=agent_engine,
+ requirements=requirements,
+ extra_packages=extra_packages,
+ display_name=display_name,
+ description=description,
+ env_vars=env_vars,
+ service_account=service_account,
+ psc_interface_config=psc_interface_config,
+ min_instances=min_instances,
+ max_instances=max_instances,
+ resource_limits=resource_limits,
+ container_concurrency=container_concurrency,
+ encryption_spec=encryption_spec,
+ )
+ operation_future = self.api_client.update_reasoning_engine(
+ request=update_request
+ )
+ _LOGGER.info(
+ f"Update Agent Engine backing LRO: {operation_future.operation.name}"
+ )
+ created_resource = operation_future.result()
+ _LOGGER.info(f"Agent Engine updated. Resource name: {created_resource.name}")
+ self._operation_schemas = None
+ self.execution_api_client = initializer.global_config.create_client(
+ client_class=aip_utils.AgentEngineExecutionClientWithOverride,
+ )
+ # We use `._get_gca_resource(...)` instead of `created_resource` to
+ # fully instantiate the attributes of the agent engine.
+ self._gca_resource = self._get_gca_resource(resource_name=self.resource_name)
+
+ if (
+ agent_engine is None
+ or historical_operation_schemas == self.operation_schemas()
+ ):
+ # The operations of the agent engine are unchanged, so we return it.
+ return self
+
+ # If the agent engine has changed and the historical operation
+ # schemas are different from the current operation schemas, we need to
+ # unregister the historical operation schemas and register the current
+ # operation schemas.
+ _unregister_api_methods(self, historical_operation_schemas)
+ try:
+ _register_api_methods_or_raise(self)
+ except Exception as e:
+ _LOGGER.warning(_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e)
+ return self
+
+ def delete(
+ self,
+ *,
+ force: bool = False,
+ **kwargs,
+ ) -> None:
+ """Deletes the ReasoningEngine.
+
+ Args:
+ force (bool):
+ Optional. If set to True, child resources will also be deleted.
+ Otherwise, the request will fail with FAILED_PRECONDITION error
+ when the Agent Engine has undeleted child resources. Defaults to
+ False.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ delete_reasoning_engine method.
+ """
+ kwargs = kwargs or {}
+ operation_future = self.api_client.delete_reasoning_engine(
+ request=aip_types.DeleteReasoningEngineRequest(
+ name=self.resource_name,
+ force=force,
+ **kwargs,
+ ),
+ )
+ _LOGGER.info(
+ f"Delete Agent Engine backing LRO: {operation_future.operation.name}"
+ )
+ operation_future.result()
+ _LOGGER.info(f"Agent Engine deleted. Resource name: {self.resource_name}")
+
+ def operation_schemas(self) -> Sequence[_utils.JsonDict]:
+ """Returns the (Open)API schemas for the Agent Engine."""
+ spec = _utils.to_dict(self._gca_resource.spec)
+ if not hasattr(self, "_operation_schemas") or self._operation_schemas is None:
+ self._operation_schemas = spec.get("class_methods", [])
+ return self._operation_schemas
+
+
+def _validate_sys_version_or_raise(sys_version: str) -> None:
+ """Tries to validate the python system version."""
+ if sys_version not in _SUPPORTED_PYTHON_VERSIONS:
+ raise ValueError(
+ f"Unsupported python version: {sys_version}. AgentEngine "
+ f"only supports {_SUPPORTED_PYTHON_VERSIONS} at the moment."
+ )
+ if sys_version != f"{sys.version_info.major}.{sys.version_info.minor}":
+ _LOGGER.warning(
+ f"{sys_version=} is inconsistent with {sys.version_info=}. "
+ "This might result in issues with deployment, and should only "
+ "be used as a workaround for advanced cases."
+ )
+
+
+def _validate_staging_bucket_or_raise(staging_bucket: Optional[str]) -> str:
+ """Tries to validate the staging bucket."""
+ if not staging_bucket:
+ raise ValueError(
+ "Please provide a `staging_bucket` in `agentplatform.init(...)`"
+ )
+ if not staging_bucket.startswith("gs://"):
+ raise ValueError(f"{staging_bucket=} must start with `gs://`")
+ return staging_bucket
+
+
+def _validate_agent_engine_or_raise(
+ agent_engine: _AgentEngineInterface,
+ logger: base.Logger = _LOGGER,
+) -> _AgentEngineInterface:
+ """Tries to validate the agent engine.
+
+ The agent engine must have one of the following:
+ * a callable method named `query`
+ * a callable method named `stream_query`
+ * a callable method named `async_stream_query`
+ * a callable method named `bidi_stream_query`
+ * a callable method named `register_operations`
+
+ Args:
+ agent_engine: The agent engine to be validated.
+ logger: The logger to use for logging.
+
+ Returns:
+ The validated agent engine.
+
+ Raises:
+ TypeError: If `agent_engine` has no callable method named `query`,
+ `stream_query` or `register_operations`.
+ ValueError: If `agent_engine` has an invalid `query`, `stream_query` or
+ `register_operations` signature.
+ """
+ try:
+ from google.adk.agents import BaseAgent
+
+ if isinstance(agent_engine, BaseAgent):
+ logger.info("Deploying google.adk.agents.Agent as an application.")
+ from agentplatform import agent_engines
+
+ agent_engine = agent_engines.AdkApp(agent=agent_engine)
+ except Exception:
+ pass
+ is_queryable = isinstance(agent_engine, Queryable) and callable(agent_engine.query)
+ is_async_queryable = isinstance(agent_engine, AsyncQueryable) and callable(
+ agent_engine.async_query
+ )
+ is_stream_queryable = isinstance(agent_engine, StreamQueryable) and callable(
+ agent_engine.stream_query
+ )
+ is_async_stream_queryable = isinstance(
+ agent_engine, AsyncStreamQueryable
+ ) and callable(agent_engine.async_stream_query)
+ is_bidi_stream_queryable = isinstance(
+ agent_engine, BidiStreamQueryable
+ ) and callable(agent_engine.bidi_stream_query)
+ is_operation_registrable = isinstance(
+ agent_engine, OperationRegistrable
+ ) and callable(agent_engine.register_operations)
+
+ if not (
+ is_queryable
+ or is_async_queryable
+ or is_stream_queryable
+ or is_operation_registrable
+ or is_async_stream_queryable
+ or is_bidi_stream_queryable
+ ):
+ raise TypeError(
+ "agent_engine has none of the following callable methods: "
+ "`query`, `async_query`, `stream_query`, `async_stream_query`, "
+ "`bidi_stream_query` or `register_operations`."
+ )
+
+ if is_queryable:
+ try:
+ inspect.signature(getattr(agent_engine, "query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid query signature. This might be due to a missing "
+ "`self` argument in the agent_engine.query method."
+ ) from err
+
+ if is_async_queryable:
+ try:
+ inspect.signature(getattr(agent_engine, "async_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid async_query signature. This might be due to a missing "
+ "`self` argument in the agent_engine.async_query method."
+ ) from err
+
+ if is_stream_queryable:
+ try:
+ inspect.signature(getattr(agent_engine, "stream_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid stream_query signature. This might be due to a missing"
+ " `self` argument in the agent_engine.stream_query method."
+ ) from err
+
+ if is_async_stream_queryable:
+ try:
+ inspect.signature(getattr(agent_engine, "async_stream_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid async_stream_query signature. This might be due to a "
+ " missing `self` argument in the "
+ "agent_engine.async_stream_query method."
+ ) from err
+
+ if is_bidi_stream_queryable:
+ try:
+ inspect.signature(getattr(agent_engine, "bidi_stream_query"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid bidi_stream_query signature. This might be due to a "
+ " missing `self` argument in the "
+ "agent_engine.bidi_stream_query method."
+ ) from err
+
+ if is_operation_registrable:
+ try:
+ inspect.signature(getattr(agent_engine, "register_operations"))
+ except ValueError as err:
+ raise ValueError(
+ "Invalid register_operations signature. This might be due to a "
+ "missing `self` argument in the "
+ "agent_engine.register_operations method."
+ ) from err
+
+ if isinstance(agent_engine, Cloneable):
+ # Avoid undeployable states.
+ agent_engine = agent_engine.clone()
+ return agent_engine
+
+
+def _is_adk_agent(
+ agent_engine_to_update: Optional[AgentEngine],
+ new_agent_engine: Optional[_AgentEngineInterface],
+) -> bool:
+ """Checks if the agent engine is an ADK agent.
+
+ Args:
+ agent_engine_to_update: Existing agent engine, None if creating new one.
+ new_agent_engine: The new agent engine to deploy. Can be None during an update, if the Python agent implementation is not provided, and should remain unchanged.
+
+ Returns:
+ True if the agent after the create/update operation, will be an ADK agent.
+ """
+
+ from agentplatform.agent_engines.templates import adk
+
+ if new_agent_engine is not None:
+ return (
+ getattr(new_agent_engine, "agent_framework", None)
+ == adk.AdkApp.agent_framework
+ )
+ if agent_engine_to_update is not None:
+ return (
+ agent_engine_to_update.gca_resource.spec.agent_framework
+ == adk.AdkApp.agent_framework
+ )
+ return False
+
+
+EnvVars = Optional[Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]]
+
+
+def _add_telemetry_enablement_env(*, env_vars: EnvVars) -> EnvVars:
+ """Adds telemetry enablement env var to the env vars.
+
+ This is in order to achieve default-on telemetry.
+ If the telemetry enablement env var is already set, we do not override it.
+
+ Args:
+ env_vars: The env vars to add the telemetry enablement env var to.
+
+ Returns:
+ The env vars with the telemetry enablement env var added.
+ """
+
+ GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY = (
+ "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
+ )
+
+ if env_vars is None:
+ return {GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY: "unspecified"}
+ if isinstance(env_vars, dict):
+ return (
+ env_vars
+ if GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY in env_vars
+ else env_vars | {GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY: "unspecified"}
+ )
+ if isinstance(env_vars, list) or isinstance(env_vars, tuple):
+ if GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY not in os.environ:
+ os.environ[GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY] = "unspecified"
+
+ if isinstance(env_vars, list):
+ return env_vars + [GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY]
+ else:
+ return env_vars + (GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY,)
+
+ raise TypeError(
+ f"env_vars must be a list, tuple or a dict, but got {type(env_vars)}."
+ )
+
+
+def _validate_requirements_or_raise(
+ *,
+ agent_engine: _AgentEngineInterface,
+ requirements: Optional[Sequence[str]] = None,
+ logger: logging.getLoggerClass() = _LOGGER,
+) -> Sequence[str]:
+ """Tries to validate the requirements."""
+ if requirements is None:
+ requirements = []
+ elif isinstance(requirements, str):
+ try:
+ logger.info(f"Reading requirements from {requirements=}")
+ with open(requirements) as f:
+ requirements = f.read().splitlines()
+ logger.info(f"Read the following lines: {requirements}")
+ except IOError as err:
+ raise IOError(f"Failed to read requirements from {requirements=}") from err
+ requirements = _utils.validate_requirements_or_warn(
+ obj=agent_engine,
+ requirements=requirements,
+ logger=logger,
+ )
+ logger.info(f"The final list of requirements: {requirements}")
+ return requirements
+
+
+def _validate_extra_packages_or_raise(
+ extra_packages: Optional[Sequence[str]],
+ build_options: Optional[Dict[str, Sequence[str]]] = None,
+) -> Sequence[str]:
+ """Tries to validates the extra packages."""
+ extra_packages = extra_packages or []
+ if build_options and _BUILD_OPTIONS_INSTALLATION in build_options:
+ _utils.validate_installation_scripts_or_raise(
+ script_paths=build_options[_BUILD_OPTIONS_INSTALLATION],
+ extra_packages=extra_packages,
+ )
+ for extra_package in extra_packages:
+ if not os.path.exists(extra_package):
+ raise FileNotFoundError(
+ f"Extra package specified but not found: {extra_package=}"
+ )
+ return extra_packages
+
+
+def _get_gcs_bucket(
+ *,
+ project: str,
+ location: str,
+ staging_bucket: str,
+ logger: base.Logger = _LOGGER,
+) -> storage.Bucket:
+ """Gets or creates the GCS bucket."""
+ storage = _utils._import_cloud_storage_or_raise()
+ storage_client = storage.Client(project=project)
+ staging_bucket = staging_bucket.replace("gs://", "")
+ try:
+ gcs_bucket = storage_client.get_bucket(staging_bucket)
+ logger.info(f"Using bucket {staging_bucket}")
+ except exceptions.NotFound:
+ new_bucket = storage_client.bucket(staging_bucket)
+ gcs_bucket = storage_client.create_bucket(new_bucket, location=location)
+ logger.info(f"Creating bucket {staging_bucket} in {location=}")
+ return gcs_bucket
+
+
+def _upload_agent_engine(
+ *,
+ agent_engine: _AgentEngineInterface,
+ gcs_bucket: storage.Bucket,
+ gcs_dir_name: str,
+ logger: base.Logger = _LOGGER,
+) -> None:
+ """Uploads the agent engine to GCS."""
+ cloudpickle = _utils._import_cloudpickle_or_raise()
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_BLOB_FILENAME}")
+ with blob.open("wb") as f:
+ try:
+ cloudpickle.dump(agent_engine, f)
+ except Exception as e:
+ url = "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#deployment-considerations"
+ error_msg = f"Failed to serialize agent engine. Visit {url} for details."
+ if "google._upb._message" in str(e) or "Descriptor" in str(e):
+ error_msg += (
+ " This is often caused by protobuf objects (like Part, AgentCard) "
+ "being imported at the global module level. Please move these "
+ "imports inside the functions or methods where they are used. "
+ "Alternatively, you can import the entire module: "
+ "`from a2a import types as a2a_types`."
+ )
+ raise TypeError(error_msg) from e
+ with blob.open("rb") as f:
+ try:
+ _ = cloudpickle.load(f)
+ except Exception as e:
+ raise TypeError("Agent engine serialized to an invalid format") from e
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
+ logger.info(f"Wrote to {dir_name}/{_BLOB_FILENAME}")
+
+
+def _upload_requirements(
+ *,
+ requirements: Sequence[str],
+ gcs_bucket: storage.Bucket,
+ gcs_dir_name: str,
+ logger: base.Logger = _LOGGER,
+) -> None:
+ """Uploads the requirements file to GCS."""
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_REQUIREMENTS_FILE}")
+ blob.upload_from_string("\n".join(requirements))
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
+ logger.info(f"Writing to {dir_name}/{_REQUIREMENTS_FILE}")
+
+
+def _upload_extra_packages(
+ *,
+ extra_packages: Sequence[str],
+ gcs_bucket: storage.Bucket,
+ gcs_dir_name: str,
+ logger: base.Logger = _LOGGER,
+) -> None:
+ """Uploads extra packages to GCS."""
+ logger.info("Creating in-memory tarfile of extra_packages")
+ tar_fileobj = io.BytesIO()
+ with tarfile.open(fileobj=tar_fileobj, mode="w|gz") as tar:
+ for file in extra_packages:
+ tar.add(file)
+ tar_fileobj.seek(0)
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_EXTRA_PACKAGES_FILE}")
+ blob.upload_from_string(tar_fileobj.read())
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
+ logger.info(f"Writing to {dir_name}/{_EXTRA_PACKAGES_FILE}")
+
+
+def _prepare(
+ agent_engine: Optional[_AgentEngineInterface],
+ requirements: Optional[Sequence[str]],
+ extra_packages: Optional[Sequence[str]],
+ project: str,
+ location: str,
+ staging_bucket: str,
+ gcs_dir_name: str,
+ logger: base.Logger = _LOGGER,
+) -> None:
+ """Prepares the agent engine for creation or updates in Vertex AI.
+
+ This involves packaging and uploading artifacts to Cloud Storage. Note that
+ 1. This does not actually update the Agent Engine in Vertex AI.
+ 2. This will only generate and upload a pickled object if specified.
+ 3. This will only generate and upload the dependencies.tar.gz file if
+ extra_packages is non-empty.
+
+ Args:
+ agent_engine: The agent engine to be prepared.
+ requirements (Sequence[str]): The set of PyPI dependencies needed.
+ extra_packages (Sequence[str]): The set of extra user-provided packages.
+ project (str): The project for the staging bucket.
+ location (str): The location for the staging bucket.
+ staging_bucket (str): The staging bucket name in the form "gs://...".
+ gcs_dir_name (str): The GCS bucket directory under `staging_bucket` to
+ use for staging the artifacts needed.
+ """
+ if agent_engine is None:
+ return
+ gcs_bucket = _get_gcs_bucket(
+ project=project,
+ location=location,
+ staging_bucket=staging_bucket,
+ logger=logger,
+ )
+ _upload_agent_engine(
+ agent_engine=agent_engine,
+ gcs_bucket=gcs_bucket,
+ gcs_dir_name=gcs_dir_name,
+ logger=logger,
+ )
+ if requirements is not None:
+ _upload_requirements(
+ requirements=requirements,
+ gcs_bucket=gcs_bucket,
+ gcs_dir_name=gcs_dir_name,
+ logger=logger,
+ )
+ if extra_packages is not None:
+ _upload_extra_packages(
+ extra_packages=extra_packages,
+ gcs_bucket=gcs_bucket,
+ gcs_dir_name=gcs_dir_name,
+ logger=logger,
+ )
+
+
+def _update_deployment_spec_with_env_vars_dict_or_raise(
+ *,
+ deployment_spec: aip_types.ReasoningEngineSpec.DeploymentSpec,
+ env_vars: Dict[str, Union[str, aip_types.SecretRef]],
+) -> None:
+ for key, value in env_vars.items():
+ if isinstance(value, Dict):
+ try:
+ secret_ref = _utils.to_proto(value, aip_types.SecretRef())
+ except Exception as e:
+ raise ValueError(f"Failed to convert to secret ref: {value}") from e
+ deployment_spec.secret_env.append(
+ aip_types.SecretEnvVar(name=key, secret_ref=secret_ref)
+ )
+ elif isinstance(value, aip_types.SecretRef):
+ deployment_spec.secret_env.append(
+ aip_types.SecretEnvVar(name=key, secret_ref=value)
+ )
+ elif isinstance(value, str):
+ deployment_spec.env.append(aip_types.EnvVar(name=key, value=value))
+ else:
+ raise TypeError(
+ f"Unknown value type in env_vars for {key}. "
+ f"Must be a str or SecretRef: {value}"
+ )
+
+
+def _update_deployment_spec_with_env_vars_list_or_raise(
+ *,
+ deployment_spec: aip_types.ReasoningEngineSpec.DeploymentSpec,
+ env_vars: Sequence[str],
+) -> None:
+ for env_var in env_vars:
+ if env_var not in os.environ:
+ raise ValueError(f"Env var not found in os.environ: {env_var}.")
+ deployment_spec.env.append(
+ aip_types.EnvVar(name=env_var, value=os.environ[env_var])
+ )
+
+
+def _generate_deployment_spec_or_raise(
+ *,
+ env_vars: Optional[
+ Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
+ ] = None,
+ psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[Dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+) -> Tuple[aip_types.ReasoningEngineSpec.DeploymentSpec, List[str]]:
+ deployment_spec = aip_types.ReasoningEngineSpec.DeploymentSpec()
+ update_masks = []
+ if env_vars:
+ deployment_spec.env = []
+ deployment_spec.secret_env = []
+ if isinstance(env_vars, Dict):
+ _update_deployment_spec_with_env_vars_dict_or_raise(
+ deployment_spec=deployment_spec,
+ env_vars=env_vars,
+ )
+ elif isinstance(env_vars, Sequence):
+ _update_deployment_spec_with_env_vars_list_or_raise(
+ deployment_spec=deployment_spec,
+ env_vars=env_vars,
+ )
+ else:
+ raise TypeError(
+ f"env_vars must be a list, tuple or a dict, but got {type(env_vars)}."
+ )
+ if deployment_spec.env:
+ update_masks.append("spec.deployment_spec.env")
+ if deployment_spec.secret_env:
+ update_masks.append("spec.deployment_spec.secret_env")
+ if psc_interface_config:
+ deployment_spec.psc_interface_config = psc_interface_config
+ update_masks.append("spec.deployment_spec.psc_interface_config")
+ if min_instances is not None:
+ deployment_spec.min_instances = min_instances
+ update_masks.append("spec.deployment_spec.min_instances")
+ if max_instances is not None:
+ deployment_spec.max_instances = max_instances
+ update_masks.append("spec.deployment_spec.max_instances")
+ if resource_limits:
+ deployment_spec.resource_limits = resource_limits
+ update_masks.append("spec.deployment_spec.resource_limits")
+ if container_concurrency is not None:
+ deployment_spec.container_concurrency = container_concurrency
+ update_masks.append("spec.deployment_spec.container_concurrency")
+ return deployment_spec, update_masks
+
+
+def _get_agent_framework(
+ agent_engine: _AgentEngineInterface,
+) -> str:
+ if (
+ hasattr(agent_engine, _AGENT_FRAMEWORK_ATTR)
+ and getattr(agent_engine, _AGENT_FRAMEWORK_ATTR) is not None
+ and isinstance(getattr(agent_engine, _AGENT_FRAMEWORK_ATTR), str)
+ ):
+ return getattr(agent_engine, _AGENT_FRAMEWORK_ATTR)
+ return _DEFAULT_AGENT_FRAMEWORK
+
+
+def _generate_update_request_or_raise(
+ *,
+ resource_name: str,
+ staging_bucket: str,
+ gcs_dir_name: str = _DEFAULT_GCS_DIR_NAME,
+ agent_engine: Optional[_AgentEngineInterface] = None,
+ requirements: Optional[Union[str, Sequence[str]]] = None,
+ extra_packages: Optional[Sequence[str]] = None,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ env_vars: Optional[
+ Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
+ ] = None,
+ service_account: Optional[str] = None,
+ psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
+ min_instances: Optional[int] = None,
+ max_instances: Optional[int] = None,
+ resource_limits: Optional[Dict[str, str]] = None,
+ container_concurrency: Optional[int] = None,
+ encryption_spec: Optional[str] = None,
+) -> reasoning_engine_service.UpdateReasoningEngineRequest:
+ """Tries to generate the update request for the agent engine."""
+ is_spec_update = False
+ update_masks: List[str] = []
+ agent_engine_spec = aip_types.ReasoningEngineSpec()
+ package_spec = aip_types.ReasoningEngineSpec.PackageSpec()
+ if requirements is not None:
+ is_spec_update = True
+ update_masks.append("spec.package_spec.requirements_gcs_uri")
+ package_spec.requirements_gcs_uri = "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _REQUIREMENTS_FILE,
+ )
+ if extra_packages is not None:
+ is_spec_update = True
+ update_masks.append("spec.package_spec.dependency_files_gcs_uri")
+ package_spec.dependency_files_gcs_uri = "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _EXTRA_PACKAGES_FILE,
+ )
+ if agent_engine is not None:
+ is_spec_update = True
+ update_masks.append("spec.package_spec.pickle_object_gcs_uri")
+ package_spec.pickle_object_gcs_uri = "{}/{}/{}".format(
+ staging_bucket,
+ gcs_dir_name,
+ _BLOB_FILENAME,
+ )
+ class_methods_spec = _generate_class_methods_spec_or_raise(
+ agent_engine=agent_engine,
+ operations=_get_registered_operations(agent_engine),
+ )
+ agent_engine_spec.class_methods.extend(class_methods_spec)
+ update_masks.append("spec.class_methods")
+ agent_engine_spec.agent_framework = _get_agent_framework(agent_engine)
+ update_masks.append("spec.agent_framework")
+ if (
+ env_vars is not None
+ or psc_interface_config
+ or min_instances is not None
+ or max_instances is not None
+ or resource_limits
+ or container_concurrency is not None
+ ):
+ is_spec_update = True
+ deployment_spec, deployment_update_masks = _generate_deployment_spec_or_raise(
+ env_vars=env_vars,
+ psc_interface_config=psc_interface_config,
+ min_instances=min_instances,
+ max_instances=max_instances,
+ resource_limits=resource_limits,
+ container_concurrency=container_concurrency,
+ )
+ update_masks.extend(deployment_update_masks)
+ agent_engine_spec.deployment_spec = deployment_spec
+ if service_account is not None:
+ is_spec_update = True
+ update_masks.append("spec.service_account")
+ agent_engine_spec.service_account = service_account
+
+ agent_engine_message = aip_types.ReasoningEngine(name=resource_name)
+ if is_spec_update:
+ if package_spec:
+ agent_engine_spec.package_spec = package_spec
+ agent_engine_message.spec = agent_engine_spec
+ if display_name:
+ agent_engine_message.display_name = display_name
+ update_masks.append("display_name")
+ if description:
+ agent_engine_message.description = description
+ update_masks.append("description")
+ if encryption_spec:
+ agent_engine_message.encryption_spec = encryption_spec
+ update_masks.append("encryption_spec")
+ if not update_masks:
+ raise ValueError(
+ "At least one of `agent_engine`, `requirements`, `extra_packages`, "
+ "`display_name`, `description`, `env_vars`, or "
+ "`encryption_spec` must be specified."
+ )
+ return reasoning_engine_service.UpdateReasoningEngineRequest(
+ reasoning_engine=agent_engine_message,
+ update_mask=field_mask_pb2.FieldMask(paths=update_masks),
+ )
+
+
+def _wrap_query_operation(method_name: str) -> Callable[..., _utils.JsonDict]:
+ """Wraps an Agent Engine method, creating a callable for `query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method using the `query` API. It handles the creation of
+ the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `query` API.
+ """
+
+ def _method(self, **kwargs) -> _utils.JsonDict:
+ response = self.execution_api_client.query_reasoning_engine(
+ request=aip_types.QueryReasoningEngineRequest(
+ name=self.resource_name,
+ input=kwargs,
+ class_method=method_name,
+ ),
+ )
+ output = _utils.to_dict(response)
+ return output.get("output", output)
+
+ return _method
+
+
+def _wrap_async_query_operation(method_name: str) -> Callable[..., Coroutine]:
+ """Wraps an Agent Engine method, creating an async callable for `query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method asynchronously using the `query` API. It handles the
+ creation of the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `query` API.
+ """
+
+ async def _method(self, **kwargs) -> _utils.JsonDict:
+ response = await self.execution_async_client.query_reasoning_engine(
+ request=aip_types.QueryReasoningEngineRequest(
+ name=self.resource_name,
+ input=kwargs,
+ class_method=method_name,
+ ),
+ )
+ output = _utils.to_dict(response)
+ return output.get("output", output)
+
+ return _method
+
+
+def _wrap_stream_query_operation(*, method_name: str) -> Callable[..., Iterable[Any]]:
+ """Wraps an Agent Engine method, creating a callable for `stream_query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method using the `stream_query` API. It handles the
+ creation of the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `stream_query` API.
+ """
+
+ def _method(self, **kwargs) -> Iterable[Any]:
+ response = self.execution_api_client.stream_query_reasoning_engine(
+ request=aip_types.StreamQueryReasoningEngineRequest(
+ name=self.resource_name,
+ input=kwargs,
+ class_method=method_name,
+ ),
+ )
+ for chunk in response:
+ for parsed_json in _utils.yield_parsed_json(chunk):
+ if parsed_json is not None:
+ yield parsed_json
+
+ return _method
+
+
+def _wrap_async_stream_query_operation(
+ *, method_name: str
+) -> Callable[..., AsyncIterable[Any]]:
+ """Wraps an Agent Engine method, creating an async callable for `stream_query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method using the `stream_query` API. It handles the
+ creation of the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ doc: Documentation string for the method.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `stream_query` API.
+ """
+
+ async def _method(self, **kwargs) -> AsyncIterable[Any]:
+ response = self.execution_api_client.stream_query_reasoning_engine(
+ request=aip_types.StreamQueryReasoningEngineRequest(
+ name=self.resource_name,
+ input=kwargs,
+ class_method=method_name,
+ ),
+ )
+ for chunk in response:
+ for parsed_json in _utils.yield_parsed_json(chunk):
+ if parsed_json is not None:
+ yield parsed_json
+
+ return _method
+
+
+def _wrap_bidi_stream_query_operation(
+ *, method_name: str
+) -> Callable[..., AsyncIterable[Any]]:
+ """Wraps an Agent Engine method, creating an async callable for `bidi_stream_query` API.
+
+ This function creates a callable object that executes the specified
+ Agent Engine method using the `bidi_stream_query` API. It handles the
+ creation of the API request and the processing of the API response.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the `bidi_stream_query` API.
+ """
+
+ async def _method(self, **kwargs) -> AsyncIterable[Any]:
+ # Agent Engine bidi streaming query execution should use GenAI SDK Agent
+ # Engine live API client directly.
+ raise NotImplementedError(
+ f"{method_name} is not implemented, please use GenAI SDK Agent "
+ "Enginve live API client instead."
+ )
+
+
+def _wrap_a2a_operation(method_name: str, agent_card: str) -> Callable[..., list]:
+ """Wraps an Agent Engine method, creating a callable for A2A API.
+
+ Args:
+ method_name: The name of the Agent Engine method to call.
+ agent_card: The agent card to use for the A2A API call.
+ Example:
+ {'additionalInterfaces': None,
+ 'capabilities': {'extensions': None,
+ 'pushNotifications': None,
+ 'stateTransitionHistory': None,
+ 'streaming': False},
+ 'defaultInputModes': ['text'],
+ 'defaultOutputModes': ['text'],
+ 'description': (
+ 'A helpful assistant agent that can answer questions.'
+ ),
+ 'documentationUrl': None,
+ 'iconUrl': None,
+ 'name': 'Q&A Agent',
+ 'preferredTransport': 'JSONRPC',
+ 'protocolVersion': '0.3.0',
+ 'provider': None,
+ 'security': None,
+ 'securitySchemes': None,
+ 'signatures': None,
+ 'skills': [{
+ 'description': (
+ 'A helpful assistant agent that can answer questions.'
+ ),
+ 'examples': ['Who is leading 2025 F1 Standings?',
+ 'Where can i find an active volcano?'],
+ 'id': 'question_answer',
+ 'inputModes': None,
+ 'name': 'Q&A Agent',
+ 'outputModes': None,
+ 'security': None,
+ 'tags': ['Question-Answer']}],
+ 'supportsAuthenticatedExtendedCard': True,
+ 'url': 'http://localhost:8080/',
+ 'version': '1.0.0'}
+ Returns:
+ A callable object that executes the method on the Agent Engine via
+ the A2A API.
+ """
+
+ async def _method(self, **kwargs) -> Any:
+ """Wraps an Agent Engine method, creating a callable for A2A API."""
+ a2a_agent_card = AgentCard(**json.loads(agent_card))
+
+ # A2A + AE integration currently only supports Rest API.
+ if (
+ a2a_agent_card.supported_interfaces
+ and a2a_agent_card.supported_interfaces[0].protocol_binding
+ != TransportProtocol.HTTP_JSON
+ ):
+ raise ValueError(
+ "Only HTTP+JSON is supported for primary interface on agent card "
+ )
+
+ # Set primary interface to HTTP+JSON if not set.
+ if not a2a_agent_card.supported_interfaces:
+ a2a_agent_card.supported_interfaces = []
+ a2a_agent_card.supported_interfaces.append(
+ AgentInterface(
+ protocol_binding=TransportProtocol.HTTP_JSON,
+ protocol_version=PROTOCOL_VERSION_CURRENT,
+ )
+ )
+
+ # AE cannot support streaming yet. Turn off streaming for now.
+ if a2a_agent_card.capabilities and a2a_agent_card.capabilities.streaming:
+ raise ValueError(
+ "Streaming is not supported in Agent Engine, please change "
+ "a2a_agent_card.capabilities.streaming to False."
+ )
+
+ if not hasattr(a2a_agent_card.capabilities, "streaming"):
+ a2a_agent_card.capabilities.streaming = False
+
+ # agent_card is set on the class_methods before set_up is invoked.
+ # Ensure that the agent_card url is set correctly before the client is created.
+ url = f"https://{initializer.global_config.api_endpoint}/v1beta1/{self.resource_name}/a2a"
+ a2a_agent_card.supported_interfaces[0].url = url
+
+ # Using a2a client, inject the auth token from the global config.
+ config = ClientConfig(
+ supported_transports=[
+ TransportProtocol.HTTP_JSON,
+ ],
+ use_client_preference=True,
+ httpx_client=httpx.AsyncClient(
+ headers={
+ "Authorization": (
+ f"Bearer {initializer.global_config.credentials.token}"
+ )
+ }
+ ),
+ )
+ factory = ClientFactory(config)
+ client = factory.create(a2a_agent_card)
+
+ # kokoro job uses python 3.9, replaced match with if else.
+ if method_name == "on_message_send":
+ response = client.send_message(Message(**kwargs))
+ chunks = []
+ async for chunk in response:
+ chunks.append(chunk)
+ return chunks
+ elif method_name == "on_get_task":
+ response = await client.get_task(TaskQueryParams(**kwargs))
+ elif method_name == "on_cancel_task":
+ response = await client.cancel_task(TaskIdParams(**kwargs))
+ elif method_name == "handle_authenticated_agent_card":
+ response = await client.get_card()
+ else:
+ raise ValueError(f"Unknown method name: {method_name}")
+
+ return response
+
+ return _method
+
+
+def _unregister_api_methods(
+ obj: "AgentEngine", operation_schemas: Sequence[_utils.JsonDict]
+):
+ """Unregisters Agent Engine API methods based on operation schemas.
+
+ This function iterates through operation schemas provided by the
+ AgentEngine object. Each schema defines an API mode and method name.
+ It dynamically unregisters methods on the AgentEngine object. This
+ should only be used when updating the object.
+
+ Args:
+ obj: The AgentEngine object to augment with API methods.
+ operation_schemas: The operation schemas to use for method unregistration.
+ """
+ for operation_schema in operation_schemas:
+ if "name" in operation_schema:
+ method_name = operation_schema.get("name")
+ if hasattr(obj, method_name):
+ delattr(obj, method_name)
+
+
+def _register_api_methods_or_raise(
+ obj: "AgentEngine",
+ wrap_operation_fn: Optional[
+ dict[str, Callable[[str, str], Callable[..., Any]]]
+ ] = None,
+):
+ """Registers Agent Engine API methods based on operation schemas.
+
+ This function iterates through operation schemas provided by the
+ AgentEngine object. Each schema defines an API mode and method name.
+ It dynamically creates and registers methods on the AgentEngine object
+ to handle API calls based on the specified API mode.
+ Currently, only standard API mode `` is supported.
+
+ Args:
+ obj: The AgentEngine object to augment with API methods.
+ wrap_operation_fn: A dictionary of API modes and method wrapping
+ functions.
+
+ Raises:
+ ValueError: If the API mode is not supported or if the operation schema
+ is missing any required fields (e.g. `api_mode` or `name`).
+ """
+ for operation_schema in obj.operation_schemas():
+ if _MODE_KEY_IN_SCHEMA not in operation_schema:
+ raise ValueError(
+ f"Operation schema {operation_schema} does not"
+ f" contain an `{_MODE_KEY_IN_SCHEMA}` field."
+ )
+ api_mode = operation_schema.get(_MODE_KEY_IN_SCHEMA)
+ if _METHOD_NAME_KEY_IN_SCHEMA not in operation_schema:
+ raise ValueError(
+ f"Operation schema {operation_schema} does not"
+ f" contain a `{_METHOD_NAME_KEY_IN_SCHEMA}` field."
+ )
+ method_name = operation_schema.get(_METHOD_NAME_KEY_IN_SCHEMA)
+ method_description = operation_schema.get(
+ "description",
+ _DEFAULT_METHOD_DOCSTRING_TEMPLATE.format(
+ method_name=method_name,
+ default_method_name=_DEFAULT_METHOD_NAME_MAP.get(
+ api_mode, _DEFAULT_METHOD_NAME
+ ),
+ return_type=_DEFAULT_METHOD_RETURN_TYPE_MAP.get(
+ api_mode,
+ _DEFAULT_METHOD_RETURN_TYPE,
+ ),
+ ),
+ )
+ _wrap_operation_map = {
+ _STANDARD_API_MODE: _wrap_query_operation,
+ _ASYNC_API_MODE: _wrap_async_query_operation,
+ _STREAM_API_MODE: _wrap_stream_query_operation,
+ _ASYNC_STREAM_API_MODE: _wrap_async_stream_query_operation,
+ _BIDI_STREAM_API_MODE: _wrap_bidi_stream_query_operation,
+ _A2A_EXTENSION_MODE: _wrap_a2a_operation,
+ }
+ if isinstance(wrap_operation_fn, dict) and api_mode in wrap_operation_fn:
+ # Override the default function with user-specified function if it exists.
+ _wrap_operation = wrap_operation_fn[api_mode]
+ elif api_mode in _wrap_operation_map:
+ _wrap_operation = _wrap_operation_map[api_mode]
+ else:
+ supported_api_modes = ", ".join(
+ f"`{mode}`" for mode in sorted(_wrap_operation_map.keys())
+ )
+ raise ValueError(
+ f"Unsupported api mode: `{api_mode}`,"
+ f" Supported modes are: {supported_api_modes}."
+ )
+
+ # Bind the method to the object.
+ if api_mode == _A2A_EXTENSION_MODE:
+ agent_card = operation_schema.get(_A2A_AGENT_CARD)
+ method = _wrap_operation(method_name=method_name, agent_card=agent_card)
+ else:
+ method = _wrap_operation(method_name=method_name)
+ method.__name__ = method_name
+ method.__doc__ = method_description
+ setattr(obj, method_name, types.MethodType(method, obj))
+
+
+def _get_registered_operations(
+ agent_engine: _AgentEngineInterface,
+) -> Dict[str, List[str]]:
+ """Retrieves registered operations for a AgentEngine."""
+ if isinstance(agent_engine, OperationRegistrable):
+ return agent_engine.register_operations()
+
+ operations = {}
+ if isinstance(agent_engine, Queryable):
+ operations[_STANDARD_API_MODE] = [_DEFAULT_METHOD_NAME]
+ if isinstance(agent_engine, AsyncQueryable):
+ operations[_ASYNC_API_MODE] = [_DEFAULT_ASYNC_METHOD_NAME]
+ if isinstance(agent_engine, StreamQueryable):
+ operations[_STREAM_API_MODE] = [_DEFAULT_STREAM_METHOD_NAME]
+ if isinstance(agent_engine, AsyncStreamQueryable):
+ operations[_ASYNC_STREAM_API_MODE] = [_DEFAULT_ASYNC_STREAM_METHOD_NAME]
+ return operations
+
+
+def _generate_class_methods_spec_or_raise(
+ *,
+ agent_engine: _AgentEngineInterface,
+ operations: Dict[str, List[str]],
+ logger: base.Logger = _LOGGER,
+) -> List[proto.Message]:
+ """Generates a ReasoningEngineSpec based on the registered operations.
+
+ Args:
+ agent_engine: The AgentEngine instance.
+ operations: A dictionary of API modes and method names.
+
+ Returns:
+ A list of ReasoningEngineSpec.ClassMethod messages.
+
+ Raises:
+ ValueError: If a method defined in `register_operations` is not found on
+ the AgentEngine.
+ """
+ if isinstance(agent_engine, ModuleAgent):
+ # We do a dry-run of setting up the agent engine to have the operations
+ # needed for registration.
+ agent_engine = agent_engine.clone()
+ try:
+ agent_engine.set_up()
+ except Exception as e:
+ raise ValueError(
+ f"Failed to set up agent engine {agent_engine}: {e}"
+ ) from e
+ class_methods_spec = []
+ for mode, method_names in operations.items():
+ for method_name in method_names:
+ if mode == _BIDI_STREAM_API_MODE:
+ _LOGGER.warning(
+ "Bidi stream API mode is not supported yet in Vertex SDK, "
+ "please use the GenAI SDK instead. Skipping "
+ f"method {method_name}."
+ )
+ continue
+ if not hasattr(agent_engine, method_name):
+ raise ValueError(
+ f"Method `{method_name}` defined in `register_operations`"
+ " not found on AgentEngine."
+ )
+
+ method = getattr(agent_engine, method_name)
+ try:
+ schema_dict = _utils.generate_schema(method, schema_name=method_name)
+ except Exception as e:
+ logger.warning(f"failed to generate schema for {method_name}: {e}")
+ continue
+
+ class_method = _utils.to_proto(schema_dict)
+ class_method[_MODE_KEY_IN_SCHEMA] = mode
+ # A2A agent card is a special case, when running in A2A mode,
+ if hasattr(agent_engine, "agent_card"):
+ from google.protobuf import json_format
+
+ class_method[_A2A_AGENT_CARD] = json_format.MessageToJson(
+ getattr(agent_engine, "agent_card")
+ )
+ class_methods_spec.append(class_method)
+
+ return class_methods_spec
+
+
+def _class_methods_to_class_methods_spec(
+ class_methods: List[dict[str, Any]],
+) -> List[proto.Message]:
+ """Converts a list of class methods to a list of ReasoningEngineSpec.ClassMethod messages."""
+ return [_utils.to_proto(class_method) for class_method in class_methods]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b5aeb6daf5e2fae455d0080aa8b1ae2151dcf0e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/_utils.py
@@ -0,0 +1,936 @@
+# -*- coding: utf-8 -*-
+# Copyright 2023 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import dataclasses
+import inspect
+import json
+import os
+import sys
+import types
+import typing
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Set,
+ TypedDict,
+ Union,
+)
+from importlib import metadata as importlib_metadata
+
+import proto
+
+from google.cloud.aiplatform import base
+from google.api import httpbody_pb2
+from google.protobuf import struct_pb2
+from google.protobuf import json_format
+
+try:
+ # For LangChain templates, they might not import langchain_core and get
+ # PydanticUserError: `query` is not fully defined; you should define
+ # `RunnableConfig`, then call `query.model_rebuild()`.
+ import langchain_core.runnables.config
+
+ RunnableConfig = langchain_core.runnables.config.RunnableConfig
+except ImportError:
+ RunnableConfig = Any
+
+try:
+ import packaging
+
+ SpecifierSet = packaging.specifiers.SpecifierSet
+except AttributeError:
+ SpecifierSet = Any
+
+try:
+ _BUILTIN_MODULE_NAMES: Sequence[str] = sys.builtin_module_names
+except AttributeError:
+ _BUILTIN_MODULE_NAMES: Sequence[str] = []
+
+try:
+ # sys.stdlib_module_names is available from Python 3.10 onwards.
+ _STDLIB_MODULE_NAMES: frozenset = sys.stdlib_module_names
+except AttributeError:
+ _STDLIB_MODULE_NAMES: frozenset = frozenset()
+
+try:
+ _PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = (
+ importlib_metadata.packages_distributions()
+ )
+
+except AttributeError:
+ _PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = {}
+
+try:
+ from autogen.agentchat import chat
+
+ AutogenChatResult = chat.ChatResult
+except ImportError:
+ AutogenChatResult = Any
+
+try:
+ from autogen.io import run_response
+
+ AutogenRunResponse = run_response.RunResponse
+except ImportError:
+ AutogenRunResponse = Any
+
+try:
+ import pydantic
+
+ BaseModel = pydantic.BaseModel
+except ImportError:
+ BaseModel = Any
+
+JsonDict = Dict[str, Any]
+
+
+class _RequirementsValidationActions(TypedDict):
+ append: Set[str]
+
+
+class _RequirementsValidationWarnings(TypedDict):
+ missing: Set[str]
+ incompatible: Set[str]
+
+
+class _RequirementsValidationResult(TypedDict):
+ warnings: _RequirementsValidationWarnings
+ actions: _RequirementsValidationActions
+
+
+LOGGER = base.Logger("agentplatform.agent_engines")
+
+_BASE_MODULES = set(_BUILTIN_MODULE_NAMES + tuple(_STDLIB_MODULE_NAMES))
+_DEFAULT_REQUIRED_PACKAGES = frozenset(["cloudpickle", "pydantic"])
+_ACTIONS_KEY = "actions"
+_ACTION_APPEND = "append"
+_WARNINGS_KEY = "warnings"
+_WARNING_MISSING = "missing"
+_WARNING_INCOMPATIBLE = "incompatible"
+_INSTALLATION_SUBDIR = "installation_scripts"
+
+
+def to_proto(
+ obj: Union[JsonDict, proto.Message],
+ message: Optional[proto.Message] = None,
+) -> proto.Message:
+ """Parses a JSON-like object into a message.
+
+ If the object is already a message, this will return the object as-is. If
+ the object is a JSON Dict, this will parse and merge the object into the
+ message.
+
+ Args:
+ obj (Union[dict[str, Any], proto.Message]):
+ Required. The object to convert to a proto message.
+ message (proto.Message):
+ Optional. A protocol buffer message to merge the obj into. It
+ defaults to Struct() if unspecified.
+
+ Returns:
+ proto.Message: The same message passed as argument.
+ """
+ if message is None:
+ message = struct_pb2.Struct()
+ if isinstance(obj, (proto.Message, struct_pb2.Struct)):
+ return obj
+ try:
+ json_format.ParseDict(obj, message._pb)
+ except AttributeError:
+ json_format.ParseDict(obj, message)
+ return message
+
+
+def to_dict(message: proto.Message) -> JsonDict:
+ """Converts the contents of the protobuf message to JSON format.
+
+ Args:
+ message (proto.Message):
+ Required. The proto message to be converted to a JSON dictionary.
+
+ Returns:
+ dict[str, Any]: A dictionary containing the contents of the proto.
+ """
+ try:
+ # Best effort attempt to convert the message into a JSON dictionary.
+ result: JsonDict = json.loads(
+ json_format.MessageToJson(
+ message._pb,
+ preserving_proto_field_name=True,
+ )
+ )
+ except AttributeError:
+ result: JsonDict = json.loads(
+ json_format.MessageToJson(
+ message,
+ preserving_proto_field_name=True,
+ )
+ )
+ return result
+
+
+def _dataclass_to_dict_or_raise(obj: Any) -> JsonDict:
+ """Converts a dataclass to a JSON dictionary.
+
+ Args:
+ obj (Any):
+ Required. The dataclass to be converted to a JSON dictionary.
+
+ Returns:
+ dict[str, Any]: A dictionary containing the contents of the dataclass.
+
+ Raises:
+ TypeError: If the object is not a dataclass.
+ """
+ if not dataclasses.is_dataclass(obj):
+ raise TypeError(f"Object is not a dataclass: {obj}")
+ return json.loads(json.dumps(dataclasses.asdict(obj)))
+
+
+def _autogen_run_response_protocol_to_dict(
+ obj: AutogenRunResponse,
+) -> JsonDict:
+ """Converts an AutogenRunResponse object into a JSON-serializable dictionary.
+
+ This function takes a `RunResponseProtocol` object and transforms its
+ relevant attributes into a dictionary format suitable for JSON conversion.
+
+ The `RunResponseProtocol` defines the structure of the response object,
+ which typically includes:
+
+ * **summary** (`Optional[str]`):
+ A textual summary of the run.
+ * **messages** (`Iterable[Message]`):
+ A sequence of messages exchanged during the run.
+ Each message is expected to be a JSON-serializable dictionary (`Dict[str,
+ Any]`).
+ * **events** (`Iterable[BaseEvent]`):
+ A sequence of events that occurred during the run.
+ Note: The `process()` method, if present, is called before conversion,
+ which typically clears this event queue.
+ * **context_variables** (`Optional[dict[str, Any]]`):
+ A dictionary containing contextual variables from the run.
+ * **last_speaker** (`Optional[Agent]`):
+ The agent that produced the last message.
+ The `Agent` object has attributes like `name` (Optional[str]) and
+ `description` (Optional[str]).
+ * **cost** (`Optional[Cost]`):
+ Information about the computational cost of the run.
+ The `Cost` object inherits from `pydantic.BaseModel` and is converted
+ to JSON using its `model_dump_json()` method.
+ * **process** (`Optional[Callable[[], None]]`):
+ An optional function (like a console event processor) that is called
+ before the conversion takes place.
+ Executing this method often clears the `events` queue.
+
+ For a detailed definition of `RunResponseProtocol` and its components, refer
+ to: https://github.com/ag2ai/ag2/blob/main/autogen/io/run_response.py
+
+ Args:
+ obj (AutogenRunResponse): The AutogenRunResponse object to convert. This
+ object must conform to the `RunResponseProtocol`.
+
+ Returns:
+ JsonDict: A dictionary representation of the AutogenRunResponse, ready
+ to be serialized into JSON. The dictionary includes keys like
+ 'summary', 'messages', 'context_variables', 'last_speaker_name',
+ and 'cost'.
+ """
+ if hasattr(obj, "process"):
+ obj.process()
+
+ last_speaker = None
+ if getattr(obj, "last_speaker", None) is not None:
+ last_speaker = {
+ "name": getattr(obj.last_speaker, "name", None),
+ "description": getattr(obj.last_speaker, "description", None),
+ }
+
+ cost = None
+ if getattr(obj, "cost", None) is not None:
+ if hasattr(obj.cost, "model_dump_json"):
+ cost = json.loads(obj.cost.model_dump_json())
+ else:
+ cost = str(obj.cost)
+
+ result = {
+ "summary": getattr(obj, "summary", None),
+ "messages": list(getattr(obj, "messages", [])),
+ "context_variables": getattr(obj, "context_variables", None),
+ "last_speaker": last_speaker,
+ "cost": cost,
+ }
+ return json.loads(json.dumps(result))
+
+
+def to_json_serializable_autogen_object(
+ obj: Union[
+ AutogenChatResult,
+ AutogenRunResponse,
+ ],
+) -> JsonDict:
+ """Converts an Autogen object to a JSON serializable object.
+
+ In `ag2<=0.8.4`, `.run()` will return a `ChatResult` object.
+ In `ag2>=0.8.5`, `.run()` will return a `RunResponse` object.
+
+ Args:
+ obj (Union[AutogenChatResult, AutogenRunResponse]):
+ Required. The Autogen object to be converted to a JSON serializable
+ object.
+
+ Returns:
+ JsonDict: A JSON serializable object.
+ """
+ if isinstance(obj, AutogenChatResult):
+ return _dataclass_to_dict_or_raise(obj)
+ return _autogen_run_response_protocol_to_dict(obj)
+
+
+def yield_parsed_json(body: httpbody_pb2.HttpBody) -> Iterable[Any]:
+ """Converts the contents of the httpbody message to JSON format.
+
+ Args:
+ body (httpbody_pb2.HttpBody):
+ Required. The httpbody body to be converted to a JSON.
+
+ Yields:
+ Any: A JSON object or the original body if it is not JSON or None.
+ """
+ content_type = getattr(body, "content_type", None)
+ data = getattr(body, "data", None)
+
+ if content_type is None or data is None or "application/json" not in content_type:
+ yield body
+ return
+
+ try:
+ utf8_data = data.decode("utf-8")
+ except Exception as e:
+ LOGGER.warning(f"Failed to decode data: {data}. Exception: {e}")
+ yield body
+ return
+
+ if not utf8_data:
+ yield None
+ return
+
+ # Handle the case of multiple dictionaries delimited by newlines.
+ for line in utf8_data.split("\n"):
+ if line:
+ try:
+ line = json.loads(line)
+ except Exception as e:
+ LOGGER.warning(f"failed to parse json: {line}. Exception: {e}")
+ yield line
+
+
+def parse_constraints(
+ constraints: Sequence[str],
+) -> Mapping[str, "SpecifierSet"]:
+ """Parses a list of constraints into a dict of requirements.
+
+ Args:
+ constraints (list[str]):
+ Required. The list of package requirements to parse. This is assumed
+ to come from the `requirements.txt` file.
+
+ Returns:
+ dict[str, SpecifierSet]: The specifiers for each package.
+ """
+ requirements = _import_packaging_requirements_or_raise()
+ result = {}
+ for constraint in constraints:
+ try:
+ if constraint.endswith(".whl"):
+ constraint = os.path.basename(constraint)
+ requirement = requirements.Requirement(constraint)
+ except Exception as e:
+ LOGGER.warning(f"Failed to parse constraint: {constraint}. Exception: {e}")
+ continue
+ result[requirement.name] = requirement.specifier or None
+ return result
+
+
+def validate_requirements_or_warn(
+ obj: Any,
+ requirements: List[str],
+ logger: base.Logger = LOGGER,
+) -> Mapping[str, str]:
+ """Compiles the requirements into a list of requirements."""
+ requirements = requirements.copy()
+ try:
+ current_requirements = scan_requirements(obj)
+ logger.info(f"Identified the following requirements: {current_requirements}")
+ constraints = parse_constraints(requirements)
+ missing_requirements = compare_requirements(current_requirements, constraints)
+ for warning_type, warnings in missing_requirements.get(
+ _WARNINGS_KEY, {}
+ ).items():
+ if warnings:
+ logger.warning(
+ f"The following requirements are {warning_type}: {warnings}"
+ )
+ for action_type, actions in missing_requirements.get(_ACTIONS_KEY, {}).items():
+ if actions and action_type == _ACTION_APPEND:
+ for action in actions:
+ requirements.append(action)
+ logger.info(f"The following requirements are appended: {actions}")
+ except Exception as e:
+ logger.warning(f"Failed to compile requirements: {e}")
+ return requirements
+
+
+def compare_requirements(
+ requirements: Mapping[str, str],
+ constraints: Union[Sequence[str], Mapping[str, "SpecifierSet"]],
+ *,
+ required_packages: Optional[Sequence[str]] = None,
+) -> Mapping[str, Mapping[str, Any]]:
+ """Compares the requirements with the constraints.
+
+ Args:
+ requirements (Mapping[str, str]):
+ Required. The packages (and their versions) to compare with the constraints.
+ This is assumed to be the result of `scan_requirements`.
+ constraints (Union[Sequence[str], Mapping[str, SpecifierSet]]):
+ Required. The package constraints to compare against. This is assumed
+ to be the result of `parse_constraints`.
+ required_packages (Sequence[str]):
+ Optional. The set of packages that are required to be in the
+ constraints. It defaults to the set of packages that are required
+ for deployment on Agent Engine.
+
+ Returns:
+ dict[str, dict[str, Any]]: The comparison result as a dictionary containing:
+ * warnings:
+ * missing: The set of packages that are not in the constraints.
+ * incompatible: The set of packages that are in the constraints
+ but have versions that are not in the constraint specifier.
+ * actions:
+ * append: The set of packages that are not in the constraints
+ but should be appended to the constraints.
+ """
+ packaging_version = _import_packaging_version_or_raise()
+ if required_packages is None:
+ required_packages = _DEFAULT_REQUIRED_PACKAGES
+ result = _RequirementsValidationResult(
+ warnings=_RequirementsValidationWarnings(missing=set(), incompatible=set()),
+ actions=_RequirementsValidationActions(append=set()),
+ )
+ if isinstance(constraints, list):
+ constraints = parse_constraints(constraints)
+ for package, package_version in requirements.items():
+ if package not in constraints:
+ result[_WARNINGS_KEY][_WARNING_MISSING].add(package)
+ if package in required_packages:
+ result[_ACTIONS_KEY][_ACTION_APPEND].add(
+ f"{package}=={package_version}"
+ )
+ continue
+ if package_version:
+ package_specifier = constraints[package]
+ if not package_specifier:
+ continue
+ if packaging_version.Version(package_version) not in package_specifier:
+ result[_WARNINGS_KEY][_WARNING_INCOMPATIBLE].add(
+ f"{package}=={package_version} (required: {str(package_specifier)})"
+ )
+ return result
+
+
+def scan_requirements(
+ obj: Any,
+ ignore_modules: Optional[Sequence[str]] = None,
+ package_distributions: Optional[Mapping[str, Sequence[str]]] = None,
+ inspect_getmembers_kwargs: Optional[Mapping[str, Any]] = None,
+) -> Mapping[str, str]:
+ """Scans the object for modules and returns the requirements discovered.
+
+ This is not a comprehensive scan of the object, and only detects for common
+ cases based on the members of the object returned by `dir(obj)`.
+
+ Args:
+ obj (Any):
+ Required. The object to scan for package requirements.
+ ignore_modules (Sequence[str]):
+ Optional. The set of modules to ignore. It defaults to the set of
+ built-in and stdlib modules.
+ package_distributions (Mapping[str, Sequence[str]]):
+ Optional. The mapping of module names to the set of packages that
+ contain them. It defaults to the set of packages from
+ `importlib_metadata.packages_distributions()`.
+ inspect_getmembers_kwargs (Mapping[str, Any]):
+ Optional. The keyword arguments to pass to `inspect.getmembers`. It
+ defaults to an empty dictionary.
+
+ Returns:
+ Sequence[str]: The list of requirements that were discovered.
+ """
+ if ignore_modules is None:
+ ignore_modules = _BASE_MODULES
+ if package_distributions is None:
+ package_distributions = _PACKAGE_DISTRIBUTIONS
+ modules_found = set(_DEFAULT_REQUIRED_PACKAGES)
+ inspect_getmembers_kwargs = inspect_getmembers_kwargs or {}
+ for _, attr in inspect.getmembers(obj, **inspect_getmembers_kwargs):
+ if not attr or inspect.isbuiltin(attr) or not hasattr(attr, "__module__"):
+ continue
+ module_name = (attr.__module__ or "").split(".")[0]
+ if module_name and module_name not in ignore_modules:
+ for module in package_distributions.get(module_name, []):
+ modules_found.add(module)
+ return {module: importlib_metadata.version(module) for module in modules_found}
+
+
+def _is_pydantic_serializable(param: inspect.Parameter) -> bool:
+ """Checks if the parameter is pydantic serializable."""
+
+ if param.annotation == inspect.Parameter.empty:
+ return True
+
+ if isinstance(param.annotation, str):
+ return False
+ pydantic = _import_pydantic_or_raise()
+ try:
+ pydantic.TypeAdapter(param.annotation)
+ return True
+ except Exception:
+ return False
+
+
+def generate_schema(
+ f: Callable[..., Any],
+ *,
+ schema_name: Optional[str] = None,
+ descriptions: Mapping[str, str] = {},
+ required: Sequence[str] = [],
+) -> JsonDict:
+ """Generates the OpenAPI Schema for a callable object.
+
+ Only positional and keyword arguments of the function `f` will be supported
+ in the OpenAPI Schema that is generated. I.e. `*args` and `**kwargs` will
+ not be present in the OpenAPI schema returned from this function. For those
+ cases, you can either include it in the docstring for `f`, or modify the
+ OpenAPI schema returned from this function to include additional arguments.
+
+ Args:
+ f (Callable):
+ Required. The function to generate an OpenAPI Schema for.
+ schema_name (str):
+ Optional. The name for the OpenAPI schema. If unspecified, the name
+ of the Callable will be used.
+ descriptions (Mapping[str, str]):
+ Optional. A `{name: description}` mapping for annotating input
+ arguments of the function with user-provided descriptions. It
+ defaults to an empty dictionary (i.e. there will not be any
+ description for any of the inputs).
+ required (Sequence[str]):
+ Optional. For the user to specify the set of required arguments in
+ function calls to `f`. If specified, it will be automatically
+ inferred from `f`.
+
+ Returns:
+ dict[str, Any]: The OpenAPI Schema for the function `f` in JSON format.
+ """
+ pydantic = _import_pydantic_or_raise()
+ defaults = dict(inspect.signature(f).parameters)
+ fields_dict = {
+ name: (
+ # 1. We infer the argument type here: use Any rather than None so
+ # it will not try to auto-infer the type based on the default value.
+ (param.annotation if param.annotation != inspect.Parameter.empty else Any),
+ pydantic.Field(
+ # 2. We do not support default values for now.
+ # default=(
+ # param.default if param.default != inspect.Parameter.empty
+ # else None
+ # ),
+ # 3. We support user-provided descriptions.
+ description=descriptions.get(name, None),
+ ),
+ )
+ for name, param in defaults.items()
+ # We do not support *args or **kwargs
+ if param.kind
+ in (
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ inspect.Parameter.KEYWORD_ONLY,
+ inspect.Parameter.POSITIONAL_ONLY,
+ )
+ and _is_pydantic_serializable(param)
+ }
+ parameters = pydantic.create_model(f.__name__, **fields_dict).schema()
+ # Postprocessing
+ # 4. Suppress unnecessary title generation:
+ # * https://github.com/pydantic/pydantic/issues/1051
+ # * http://cl/586221780
+ parameters.pop("title", "")
+ for name, function_arg in parameters.get("properties", {}).items():
+ function_arg.pop("title", "")
+ annotation = defaults[name].annotation
+ # 5. Nullable fields:
+ # * https://github.com/pydantic/pydantic/issues/1270
+ # * https://stackoverflow.com/a/58841311
+ # * https://github.com/pydantic/pydantic/discussions/4872
+ if typing.get_origin(annotation) is Union and type(None) in typing.get_args(
+ annotation
+ ):
+ # for "typing.Optional" arguments, function_arg might be a
+ # dictionary like
+ #
+ # {'anyOf': [{'type': 'integer'}, {'type': 'null'}]
+ for schema in function_arg.pop("anyOf", []):
+ schema_type = schema.get("type")
+ if schema_type and schema_type != "null":
+ function_arg["type"] = schema_type
+ break
+ function_arg["nullable"] = True
+ # 6. Annotate required fields.
+ if required:
+ # We use the user-provided "required" fields if specified.
+ parameters["required"] = required
+ else:
+ # Otherwise we infer it from the function signature.
+ parameters["required"] = [
+ k
+ for k in defaults
+ if (
+ defaults[k].default == inspect.Parameter.empty
+ and defaults[k].kind
+ in (
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ inspect.Parameter.KEYWORD_ONLY,
+ inspect.Parameter.POSITIONAL_ONLY,
+ )
+ )
+ ]
+ schema = dict(name=f.__name__, description=f.__doc__, parameters=parameters)
+ if schema_name:
+ schema["name"] = schema_name
+ return schema
+
+
+def is_noop_or_proxy_tracer_provider(tracer_provider) -> bool:
+ """Returns True if the tracer_provider is Proxy or NoOp."""
+ opentelemetry = _import_opentelemetry_or_warn()
+ ProxyTracerProvider = opentelemetry.trace.ProxyTracerProvider
+ NoOpTracerProvider = opentelemetry.trace.NoOpTracerProvider
+ return isinstance(tracer_provider, (NoOpTracerProvider, ProxyTracerProvider))
+
+
+def dump_event_for_json(event: BaseModel) -> Dict[str, Any]:
+ """Dumps an ADK event to a JSON-serializable dictionary."""
+ return json.loads(event.model_dump_json(exclude_none=True))
+
+
+def _import_cloud_storage_or_raise() -> types.ModuleType:
+ """Tries to import the Cloud Storage module."""
+ try:
+ from google.cloud import storage
+ except ImportError as e:
+ raise ImportError(
+ "Cloud Storage is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return storage
+
+
+def _import_cloudpickle_or_raise() -> types.ModuleType:
+ """Tries to import the cloudpickle module."""
+ try:
+ import cloudpickle # noqa:F401
+ except ImportError as e:
+ raise ImportError(
+ "cloudpickle is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return cloudpickle
+
+
+def _import_pydantic_or_raise() -> types.ModuleType:
+ """Tries to import the pydantic module."""
+ try:
+ import pydantic
+
+ _ = pydantic.Field
+ except AttributeError:
+ from pydantic import v1 as pydantic
+ except ImportError as e:
+ raise ImportError(
+ "pydantic is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return pydantic
+
+
+def _import_packaging_requirements_or_raise() -> types.ModuleType:
+ """Tries to import the packaging.requirements module."""
+ try:
+ from packaging import requirements
+ except ImportError as e:
+ raise ImportError(
+ "packaging.requirements is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return requirements
+
+
+def _import_packaging_version_or_raise() -> types.ModuleType:
+ """Tries to import the packaging.requirements module."""
+ try:
+ from packaging import version
+ except ImportError as e:
+ raise ImportError(
+ "packaging.version is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ ) from e
+ return version
+
+
+def _import_opentelemetry_or_warn() -> Optional[types.ModuleType]:
+ """Tries to import the opentelemetry module."""
+ try:
+ import opentelemetry # noqa:F401
+
+ return opentelemetry
+ except ImportError:
+ LOGGER.warning(
+ "opentelemetry-sdk is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ )
+ return None
+
+
+def _import_opentelemetry_sdk_trace_or_warn() -> Optional[types.ModuleType]:
+ """Tries to import the opentelemetry.sdk.trace module."""
+ try:
+ import opentelemetry.sdk.trace # noqa:F401
+
+ return opentelemetry.sdk.trace
+ except ImportError:
+ LOGGER.warning(
+ "opentelemetry-sdk is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ )
+ return None
+
+
+def _import_cloud_trace_v2_or_warn() -> Optional[types.ModuleType]:
+ """Tries to import the google.cloud.trace_v2 module."""
+ try:
+ import google.cloud.trace_v2
+
+ return google.cloud.trace_v2
+ except ImportError:
+ LOGGER.warning(
+ "google-cloud-trace is not installed. Please call "
+ "'pip install google-cloud-aiplatform[agent_engines]'."
+ )
+ return None
+
+
+def _import_cloud_trace_exporter_or_warn() -> Optional[types.ModuleType]:
+ """Tries to import the opentelemetry.exporter.cloud_trace module."""
+ try:
+ import opentelemetry.exporter.cloud_trace # noqa:F401
+
+ return opentelemetry.exporter.cloud_trace
+ except ImportError:
+ LOGGER.warning(
+ "opentelemetry-exporter-gcp-trace is not installed. Please "
+ "call 'pip install google-cloud-aiplatform[agent_engines]'."
+ )
+ return None
+
+
+def _import_openinference_langchain_or_warn() -> Optional[types.ModuleType]:
+ """Tries to import the openinference.instrumentation.langchain module."""
+ try:
+ import openinference.instrumentation.langchain # noqa:F401
+
+ return openinference.instrumentation.langchain
+ except ImportError:
+ LOGGER.warning(
+ "openinference-instrumentation-langchain is not installed. Please "
+ "call 'pip install google-cloud-aiplatform[langchain]'."
+ )
+ return None
+
+
+def _import_openinference_autogen_or_warn() -> Optional[types.ModuleType]:
+ """Tries to import the openinference.instrumentation.autogen module."""
+ try:
+ import openinference.instrumentation.autogen # noqa:F401
+
+ return openinference.instrumentation.autogen
+ except ImportError:
+ LOGGER.warning(
+ "openinference-instrumentation-autogen is not installed. Please "
+ "call 'pip install google-cloud-aiplatform[ag2]'."
+ )
+ return None
+
+
+def _import_autogen_tools_or_warn() -> Optional[types.ModuleType]:
+ """Tries to import the autogen.tools module."""
+ try:
+ from autogen import tools
+
+ return tools
+ except ImportError:
+ LOGGER.warning(
+ "autogen.tools is not installed. Please "
+ "call `pip install google-cloud-aiplatform[ag2]`."
+ )
+ return None
+
+
+def validate_installation_scripts_or_raise(
+ script_paths: Sequence[str],
+ extra_packages: Sequence[str],
+):
+ """Validates the installation scripts' path explicitly provided by the user.
+
+ Args:
+ script_paths (Sequence[str]):
+ Required. The paths to the installation scripts.
+ extra_packages (Sequence[str]):
+ Required. The extra packages to be updated.
+
+ Raises:
+ ValueError: If a user-defined script is not under the expected
+ subdirectory, or not in `extra_packages`, or if an extra package is
+ in the installation scripts subdirectory, but is not specified as an
+ installation script.
+ """
+ for script_path in script_paths:
+ if not script_path.startswith(_INSTALLATION_SUBDIR):
+ LOGGER.warning(
+ f"User-defined installation script '{script_path}' is not in "
+ f"the expected '{_INSTALLATION_SUBDIR}' subdirectory. "
+ f"Ensure it is placed in '{_INSTALLATION_SUBDIR}' within your "
+ f"`extra_packages`."
+ )
+ raise ValueError(
+ f"Required installation script '{script_path}' "
+ f"is not under '{_INSTALLATION_SUBDIR}'"
+ )
+
+ if script_path not in extra_packages:
+ LOGGER.warning(
+ f"User-defined installation script '{script_path}' is not in "
+ f"extra_packages. Ensure it is added to `extra_packages`."
+ )
+ raise ValueError(
+ f"User-defined installation script '{script_path}' "
+ f"does not exist in `extra_packages`"
+ )
+
+ for extra_package in extra_packages:
+ if (
+ extra_package.startswith(_INSTALLATION_SUBDIR)
+ and extra_package not in script_paths
+ ):
+ LOGGER.warning(
+ f"Extra package '{extra_package}' is in the installation "
+ "scripts subdirectory, but is not specified as an installation "
+ "script in `build_options`. "
+ "Ensure it is added to installation_scripts for "
+ "automatic execution."
+ )
+ raise ValueError(
+ f"Extra package '{extra_package}' is in the installation "
+ "scripts subdirectory, but is not specified as an installation "
+ "script in `build_options`."
+ )
+ return
+
+
+def _validate_resource_limits_or_raise(resource_limits: dict[str, str]) -> None:
+ """Validates the resource limits.
+
+ Checks that the resource limits are a dict with 'cpu' and 'memory' keys.
+ Checks that the 'cpu' value is one of 1, 2, 4, 6, 8.
+ Checks that the 'memory' value is a string ending with 'Gi'.
+ Checks that the memory size is smaller than 32Gi.
+ Checks that the memory size requires at least the specified number of CPUs.
+
+ Args:
+ resource_limits: The resource limits to be validated.
+
+ Raises:
+ TypeError: If the resource limits are not a dict.
+ KeyError: If the resource limits do not contain 'cpu' and 'memory' keys.
+ ValueError: If the 'cpu' value is not one of 1, 2, 4, 6, 8.
+ ValueError: If the 'memory' value is not a string ending with 'Gi'.
+ ValueError: If the memory size is too large.
+ ValueError: If the memory size requires more CPUs than the specified
+ 'cpu' value.
+ """
+ if not isinstance(resource_limits, dict):
+ raise TypeError(f"resource_limits must be a dict. Got {type(resource_limits)}")
+ if "cpu" not in resource_limits or "memory" not in resource_limits:
+ raise KeyError("resource_limits must contain 'cpu' and 'memory' keys.")
+
+ cpu = int(resource_limits["cpu"])
+ memory_str = resource_limits["memory"]
+
+ if cpu not in [1, 2, 4, 6, 8]:
+ raise ValueError(
+ "resource_limits['cpu'] must be one of 1, 2, 4, 6, 8. Got" f" {cpu}"
+ )
+
+ if not isinstance(memory_str, str) or not memory_str.endswith("Gi"):
+ raise ValueError(
+ "resource_limits['memory'] must be a string ending with 'Gi'."
+ f" Got {memory_str}"
+ )
+
+ try:
+ memory_gb = int(memory_str[:-2])
+ except ValueError:
+ raise ValueError(
+ f"Invalid memory value: {memory_str}. Must be an integer"
+ " followed by 'Gi'."
+ )
+
+ # https://cloud.google.com/run/docs/configuring/memory-limits
+ if memory_gb > 32:
+ raise ValueError(
+ f"Memory size of {memory_str} is too large. Must be smaller than 32Gi."
+ )
+ if memory_gb > 24:
+ min_cpu = 8
+ elif memory_gb > 16:
+ min_cpu = 6
+ elif memory_gb > 8:
+ min_cpu = 4
+ elif memory_gb > 4:
+ min_cpu = 2
+ else:
+ min_cpu = 1
+
+ if cpu < min_cpu:
+ raise ValueError(
+ f"Memory size of {memory_str} requires at least {min_cpu} CPUs."
+ f" Got {cpu}"
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/a2a.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/a2a.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cb2b19287c117d6f22ec8afbdfc056f8eded882
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/a2a.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/adk.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/adk.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5aa4637b2f50b7b7a506f0b497284c51a28a0cfa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/adk.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/ag2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/ag2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aefe7299ea38d978ab9aa2c8e2a23cc78feed279
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/ag2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/langchain.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/langchain.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05d78490942b883171a5feabd540f6cff06716ef
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/langchain.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/langgraph.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/langgraph.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7275a1f9a2715526c5596d63ad12c11ed3917af1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/__pycache__/langgraph.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/a2a.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/a2a.py
new file mode 100644
index 0000000000000000000000000000000000000000..705d57c42827da2472f8343cd627334ef7f1acab
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/a2a.py
@@ -0,0 +1,579 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections.abc import AsyncIterator
+import os
+from typing import Any, Callable, Dict, List, Mapping, Optional, TYPE_CHECKING
+
+
+if TYPE_CHECKING:
+ try:
+ from a2a.server.request_handlers import RequestHandler
+ from a2a.server.tasks import TaskStore
+ from a2a.types import AgentCard, AgentSkill
+ from a2a.server.agent_execution import AgentExecutor
+ from a2a.server.context import ServerCallContext
+ from a2a.types import (
+ SendMessageRequest,
+ CancelTaskRequest,
+ GetTaskRequest,
+ GetExtendedAgentCardRequest,
+ SubscribeToTaskRequest,
+ ListTasksRequest,
+ ListTasksResponse,
+ TaskPushNotificationConfig,
+ GetTaskPushNotificationConfigRequest,
+ ListTaskPushNotificationConfigsRequest,
+ ListTaskPushNotificationConfigsResponse,
+ DeleteTaskPushNotificationConfigRequest,
+ Message,
+ Task,
+ )
+ from a2a.server.events.event_queue import Event
+
+ RequestHandler = RequestHandler
+ TaskStore = TaskStore
+ AgentCard = AgentCard
+ AgentSkill = AgentSkill
+ AgentExecutor = AgentExecutor
+ ServerCallContext = ServerCallContext
+ SendMessageRequest = SendMessageRequest
+ CancelTaskRequest = CancelTaskRequest
+ GetTaskRequest = GetTaskRequest
+ GetExtendedAgentCardRequest = GetExtendedAgentCardRequest
+ SubscribeToTaskRequest = SubscribeToTaskRequest
+ ListTasksRequest = ListTasksRequest
+ ListTasksResponse = ListTasksResponse
+ TaskPushNotificationConfig = TaskPushNotificationConfig
+ GetTaskPushNotificationConfigRequest = GetTaskPushNotificationConfigRequest
+ ListTaskPushNotificationConfigsRequest = ListTaskPushNotificationConfigsRequest
+ ListTaskPushNotificationConfigsResponse = (
+ ListTaskPushNotificationConfigsResponse
+ )
+ DeleteTaskPushNotificationConfigRequest = (
+ DeleteTaskPushNotificationConfigRequest
+ )
+ Message = Message
+ Task = Task
+ Event = Event
+ except (ImportError, AttributeError):
+ RequestHandler = Any
+ TaskStore = Any
+ AgentCard = Any
+ AgentSkill = Any
+ AgentExecutor = Any
+ ServerCallContext = Any
+ SendMessageRequest = Any
+ CancelTaskRequest = Any
+ GetTaskRequest = Any
+ GetExtendedAgentCardRequest = Any
+ SubscribeToTaskRequest = Any
+ ListTasksRequest = Any
+ ListTasksResponse = Any
+ TaskPushNotificationConfig = Any
+ GetTaskPushNotificationConfigRequest = Any
+ ListTaskPushNotificationConfigsRequest = Any
+ ListTaskPushNotificationConfigsResponse = Any
+ DeleteTaskPushNotificationConfigRequest = Any
+ Message = Any
+ Task = Any
+ Event = Any
+ AgentExecutor = Any
+ ServerCallContext = Any
+ SendMessageRequest = Any
+ CancelTaskRequest = Any
+ GetTaskRequest = Any
+ GetExtendedAgentCardRequest = Any
+ SubscribeToTaskRequest = Any
+ Message = Any
+ Task = Any
+ Event = Any
+
+
+def create_agent_card(
+ agent_name: Optional[str] = None,
+ description: Optional[str] = None,
+ skills: Optional[List["AgentSkill"]] = None,
+ agent_card: Optional[Dict[str, Any]] = None,
+ default_input_modes: Optional[List[str]] = None,
+ default_output_modes: Optional[List[str]] = None,
+ streaming: bool = False,
+) -> "AgentCard":
+ """Creates an AgentCard object.
+
+ The function can be called in two ways:
+ 1. By providing the individual parameters: agent_name, description, and
+ skills.
+ 2. By providing a single dictionary containing all the data.
+
+ If a dictionary is provided, the other parameters are ignored.
+
+ Args:
+ agent_name (Optional[str]): The name of the agent.
+ description (Optional[str]): A description of the agent.
+ skills (Optional[List[AgentSkill]]): A list of AgentSkills.
+ agent_card (Optional[Dict[str, Any]]): Agent Card as a dictionary.
+ default_input_modes (Optional[List[str]]): A list of input modes, default
+ to ["text/plain"].
+ default_output_modes (Optional[List[str]]): A list of output modes,
+ default to ["application/json"].
+ streaming (bool): Whether to enable streaming for the agent. Defaults to
+ False.
+
+ Returns:
+ AgentCard: A fully constructed AgentCard object.
+
+ Raises:
+ ValueError: If neither a dictionary nor the required parameters are
+ provided.
+ """
+ # pylint: disable=g-import-not-at-top
+ from a2a.types import AgentCard, AgentCapabilities, AgentInterface
+ from a2a.utils.constants import TransportProtocol, PROTOCOL_VERSION_CURRENT
+
+ # Check if a dictionary was provided.
+ if agent_card:
+ return AgentCard(**agent_card)
+
+ # If no dictionary, use the individual parameters.
+ elif agent_name and description and skills:
+ return AgentCard(
+ name=agent_name,
+ description=description,
+ version="1.0.0",
+ default_input_modes=default_input_modes or ["text/plain"],
+ default_output_modes=default_output_modes or ["application/json"],
+ capabilities=AgentCapabilities(
+ streaming=streaming, extended_agent_card=True
+ ),
+ skills=skills,
+ supported_interfaces=[
+ AgentInterface(
+ url="http://localhost:9999/",
+ protocol_binding=TransportProtocol.HTTP_JSON,
+ protocol_version=PROTOCOL_VERSION_CURRENT,
+ )
+ ],
+ )
+
+ # Raise an error if insufficient data is provided.
+ else:
+ raise ValueError(
+ "Please provide either an agent_card or all of the required "
+ "parameters (agent_name, description, and skills)."
+ )
+
+
+def default_a2a_agent() -> "A2aAgent":
+ """Creates a default A2aAgent instance."""
+ # pylint: disable=g-import-not-at-top
+ from a2a.server.agent_execution import AgentExecutor, RequestContext
+ from a2a.types import AgentSkill
+ from a2a.server.events import EventQueue
+ from a2a.helpers.proto_helpers import new_text_message
+
+ skill = AgentSkill(
+ id="hello_world",
+ name="Returns hello world",
+ description="just returns hello world",
+ tags=["hello world"],
+ examples=["hi", "hello world"],
+ )
+ agent_card = create_agent_card(
+ agent_name="Hello World Agent",
+ description="Just a hello world agent",
+ skills=[skill],
+ )
+
+ class HelloWorldAgentExecutor(AgentExecutor):
+ """Hello World Agent Executor."""
+
+ def get_agent_response(self) -> str:
+ return "Hello World"
+
+ async def execute(
+ self,
+ context: RequestContext,
+ event_queue: EventQueue,
+ ) -> None:
+ result = self.get_agent_response()
+ await event_queue.enqueue_event(new_text_message(result))
+
+ async def cancel(
+ self, context: RequestContext, event_queue: EventQueue
+ ) -> None:
+ raise Exception("cancel not supported")
+
+ return A2aAgent(
+ agent_card=agent_card,
+ agent_executor_builder=HelloWorldAgentExecutor,
+ )
+
+
+def _is_version_enabled(agent_card: "AgentCard", version: str) -> bool:
+ """Checks if a specific version compatibility should be enabled for the A2aAgent."""
+ # pylint: disable=g-import-not-at-top
+ from a2a.utils.constants import TransportProtocol
+
+ if not getattr(agent_card, "supported_interfaces", None):
+ return False
+ for interface in agent_card.supported_interfaces:
+ if (
+ interface.protocol_version == version
+ and interface.protocol_binding == TransportProtocol.HTTP_JSON
+ ):
+ return True
+ return False
+
+
+class A2aAgent:
+ """A class to initialize and set up an Agent-to-Agent application."""
+
+ agent_framework = "a2a"
+
+ # TODO: Add instrumentation for the A2A agent.
+ def __init__(
+ self,
+ *,
+ agent_card: "AgentCard",
+ task_store_builder: Callable[..., "TaskStore"] = None,
+ task_store_kwargs: Optional[Mapping[str, Any]] = None,
+ agent_executor_kwargs: Optional[Mapping[str, Any]] = None,
+ agent_executor_builder: Optional[Callable[..., "AgentExecutor"]] = None,
+ request_handler_kwargs: Optional[Mapping[str, Any]] = None,
+ request_handler_builder: Optional[Callable[..., "RequestHandler"]] = None,
+ extended_agent_card: "AgentCard" = None,
+ ):
+ """Initializes the A2A agent."""
+ # pylint: disable=g-import-not-at-top
+ from google.cloud.aiplatform import initializer
+ from a2a.utils.constants import TransportProtocol, PROTOCOL_VERSION_CURRENT
+
+ if (
+ agent_card.supported_interfaces
+ and agent_card.supported_interfaces[0].protocol_binding
+ != TransportProtocol.HTTP_JSON
+ ):
+ raise ValueError(
+ "Only HTTP+JSON is supported for the primary interface on agent card "
+ )
+ if not _is_version_enabled(agent_card, PROTOCOL_VERSION_CURRENT):
+ raise ValueError(
+ "A2A protocol version 1.0 is required but not enabled on the agent card."
+ )
+
+ self._tmpl_attrs: dict[str, Any] = {
+ "project": initializer.global_config.project,
+ "location": initializer.global_config.location,
+ "agent_card": agent_card,
+ "agent_executor": None,
+ "agent_executor_kwargs": agent_executor_kwargs or {},
+ "agent_executor_builder": agent_executor_builder,
+ "task_store": None,
+ "task_store_kwargs": task_store_kwargs or {},
+ "task_store_builder": task_store_builder,
+ "request_handler": None,
+ "request_handler_kwargs": request_handler_kwargs or {},
+ "request_handler_builder": request_handler_builder,
+ "extended_agent_card": extended_agent_card,
+ }
+ self.agent_card = agent_card
+ self.request_handler = None
+ self.task_store = None
+ self.agent_executor = None
+
+ def clone(self) -> "A2aAgent":
+ """Clones the A2A agent."""
+ import copy
+
+ return A2aAgent(
+ agent_card=copy.deepcopy(self.agent_card),
+ task_store_builder=self._tmpl_attrs.get("task_store_builder"),
+ task_store_kwargs=self._tmpl_attrs.get("task_store_kwargs"),
+ agent_executor_kwargs=self._tmpl_attrs.get("agent_executor_kwargs"),
+ agent_executor_builder=self._tmpl_attrs.get("agent_executor_builder"),
+ request_handler_kwargs=self._tmpl_attrs.get("request_handler_kwargs"),
+ request_handler_builder=self._tmpl_attrs.get("request_handler_builder"),
+ extended_agent_card=self._tmpl_attrs.get("extended_agent_card"),
+ )
+
+ def set_up(self):
+ """Sets up the A2A application."""
+ # pylint: disable=g-import-not-at-top
+ from a2a.server.request_handlers import DefaultRequestHandler
+ from a2a.server.routes.rest_routes import create_rest_routes
+ from a2a.server.tasks import InMemoryTaskStore
+
+ os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "1"
+ project = self._tmpl_attrs.get("project")
+ os.environ["GOOGLE_CLOUD_PROJECT"] = project
+ location = self._tmpl_attrs.get("location")
+ os.environ["GOOGLE_CLOUD_LOCATION"] = location
+ agent_engine_id = os.getenv("GOOGLE_CLOUD_AGENT_ENGINE_ID", "test-agent-engine")
+ version = "v1beta1"
+
+ new_url = f"https://{location}-aiplatform.googleapis.com/{version}/projects/{project}/locations/{location}/reasoningEngines/{agent_engine_id}/a2a"
+ if not self.agent_card.supported_interfaces:
+ from a2a.types import AgentInterface
+ from a2a.utils.constants import TransportProtocol, PROTOCOL_VERSION_CURRENT
+
+ self.agent_card.supported_interfaces.append(
+ AgentInterface(
+ url=new_url,
+ protocol_binding=TransportProtocol.HTTP_JSON,
+ protocol_version=PROTOCOL_VERSION_CURRENT,
+ )
+ )
+ else:
+ # primary interface must be HTTP+JSON
+ self.agent_card.supported_interfaces[0].url = new_url
+ self._tmpl_attrs["agent_card"] = self.agent_card
+
+ # Create the agent executor if a builder is provided.
+ agent_executor_builder = self._tmpl_attrs.get("agent_executor_builder")
+ if agent_executor_builder:
+ self._tmpl_attrs["agent_executor"] = agent_executor_builder(
+ **self._tmpl_attrs.get("agent_executor_kwargs")
+ )
+ self.agent_executor = self._tmpl_attrs.get("agent_executor")
+
+ # Create the task store if a builder is provided.
+ task_store_builder = self._tmpl_attrs.get("task_store_builder")
+ if task_store_builder:
+ self.task_store = task_store_builder(
+ **self._tmpl_attrs.get("task_store_kwargs")
+ )
+ else:
+ # Use the default task store if not provided. This could potentially
+ # lead to unexpected behavior if the agent is running on
+ # multiple instances.
+ self.task_store = InMemoryTaskStore()
+
+ self._tmpl_attrs["task_store"] = self.task_store
+
+ # Create the request handler if a builder is provided.
+ request_handler_builder = self._tmpl_attrs.get("request_handler_builder")
+ if request_handler_builder:
+ self.request_handler = request_handler_builder(
+ **self._tmpl_attrs.get("request_handler_kwargs")
+ )
+ else:
+ # Use the default request handler if not provided.
+ self.request_handler = DefaultRequestHandler(
+ agent_executor=self._tmpl_attrs.get("agent_executor"),
+ task_store=self.task_store,
+ agent_card=self.agent_card,
+ extended_agent_card=self._tmpl_attrs.get("extended_agent_card"),
+ )
+
+ self._tmpl_attrs["request_handler"] = self.request_handler
+
+ # Support native Starlette routes.
+ enable_v0_3 = _is_version_enabled(self.agent_card, "0.3")
+ self.rest_routes = create_rest_routes(
+ request_handler=self,
+ enable_v0_3_compat=enable_v0_3,
+ path_prefix="/a2a",
+ )
+
+ def __getattr__(self, name: str) -> Any:
+ """Delegates all missing RequestHandler methods to the underlying request_handler."""
+ if not self.request_handler:
+ raise AttributeError(
+ f"'A2aAgent' has no attribute '{name}' and request_handler is not initialized."
+ )
+ return getattr(self.request_handler, name)
+
+ async def on_message_send(
+ self,
+ request: "SendMessageRequest",
+ context: "ServerCallContext",
+ ) -> "Task | Message":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_message_send(request, context)
+
+ async def on_cancel_task(
+ self,
+ request: "CancelTaskRequest",
+ context: "ServerCallContext",
+ ) -> "Task | None":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_cancel_task(request, context)
+
+ async def on_get_task(
+ self,
+ request: "GetTaskRequest",
+ context: "ServerCallContext",
+ ) -> "Task | None":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_get_task(request, context)
+
+ async def on_list_tasks(
+ self,
+ request: "ListTasksRequest",
+ context: "ServerCallContext",
+ ) -> "ListTasksResponse":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_list_tasks(request, context)
+
+ async def on_create_task_push_notification_config(
+ self,
+ request: "TaskPushNotificationConfig",
+ context: "ServerCallContext",
+ ) -> "TaskPushNotificationConfig":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_create_task_push_notification_config(
+ request, context
+ )
+
+ async def on_get_task_push_notification_config(
+ self,
+ request: "GetTaskPushNotificationConfigRequest",
+ context: "ServerCallContext",
+ ) -> "TaskPushNotificationConfig":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_get_task_push_notification_config(
+ request, context
+ )
+
+ async def on_list_task_push_notification_configs(
+ self,
+ request: "ListTaskPushNotificationConfigsRequest",
+ context: "ServerCallContext",
+ ) -> "ListTaskPushNotificationConfigsResponse":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_list_task_push_notification_configs(
+ request, context
+ )
+
+ async def on_delete_task_push_notification_config(
+ self,
+ request: "DeleteTaskPushNotificationConfigRequest",
+ context: "ServerCallContext",
+ ) -> None:
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_delete_task_push_notification_config(
+ request, context
+ )
+
+ async def on_get_extended_agent_card(
+ self,
+ request: "GetExtendedAgentCardRequest",
+ context: "ServerCallContext",
+ ) -> "AgentCard":
+ if not self.request_handler:
+ raise NotImplementedError("request_handler not available.")
+ return await self.request_handler.on_get_extended_agent_card(request, context)
+
+ def register_operations(self) -> Dict[str, List[str]]:
+ """Registers the operations of the A2A Agent."""
+ routes = {
+ "a2a_extension": [
+ "on_message_send",
+ "on_get_task",
+ "on_list_tasks",
+ "on_cancel_task",
+ "on_create_task_push_notification_config",
+ "on_get_task_push_notification_config",
+ "on_list_task_push_notification_configs",
+ "on_delete_task_push_notification_config",
+ ]
+ }
+ if self.agent_card.capabilities and self.agent_card.capabilities.streaming:
+ routes["a2a_extension"].append("on_message_send_stream")
+ routes["a2a_extension"].append("on_subscribe_to_task")
+ if (
+ self.agent_card.capabilities
+ and self.agent_card.capabilities.extended_agent_card
+ ):
+ routes["a2a_extension"].append("on_get_extended_agent_card")
+ return routes
+
+ async def on_message_send_stream(
+ self,
+ request: "SendMessageRequest",
+ context: "ServerCallContext",
+ ) -> AsyncIterator["Event"]:
+ """Handles A2A streaming requests via SSE."""
+ async for chunk in self.request_handler.on_message_send_stream(
+ request, context
+ ):
+ yield chunk
+
+ async def on_subscribe_to_task(
+ self,
+ request: "SubscribeToTaskRequest",
+ context: "ServerCallContext",
+ ) -> AsyncIterator["Event"]:
+ """Handles A2A task resubscription requests via SSE."""
+ async for chunk in self.request_handler.on_subscribe_to_task(request, context):
+ yield chunk
+
+ def __getstate__(self):
+ """Serializes AgentCard proto to a dictionary."""
+ from google.protobuf import json_format
+ import json
+
+ state = self.__dict__.copy()
+
+ def _to_dict_if_proto(obj):
+ if hasattr(obj, "DESCRIPTOR"):
+ return {
+ "__protobuf_AgentCard__": json.loads(json_format.MessageToJson(obj))
+ }
+ return obj
+
+ state["agent_card"] = _to_dict_if_proto(state.get("agent_card"))
+ if "_tmpl_attrs" in state:
+ tmpl_attrs = state["_tmpl_attrs"].copy()
+ tmpl_attrs["agent_card"] = _to_dict_if_proto(tmpl_attrs.get("agent_card"))
+ tmpl_attrs["extended_agent_card"] = _to_dict_if_proto(
+ tmpl_attrs.get("extended_agent_card")
+ )
+ state["_tmpl_attrs"] = tmpl_attrs
+
+ return state
+
+ def __setstate__(self, state):
+ """Deserializes AgentCard proto from a dictionary."""
+ from google.protobuf import json_format
+ from a2a.types import AgentCard
+
+ def _from_dict_if_proto(obj):
+ if isinstance(obj, dict) and "__protobuf_AgentCard__" in obj:
+ agent_card = AgentCard()
+ json_format.ParseDict(obj["__protobuf_AgentCard__"], agent_card)
+ return agent_card
+ return obj
+
+ state["agent_card"] = _from_dict_if_proto(state.get("agent_card"))
+ if "_tmpl_attrs" in state:
+ state["_tmpl_attrs"]["agent_card"] = _from_dict_if_proto(
+ state["_tmpl_attrs"].get("agent_card")
+ )
+ state["_tmpl_attrs"]["extended_agent_card"] = _from_dict_if_proto(
+ state["_tmpl_attrs"].get("extended_agent_card")
+ )
+
+ self.__dict__.update(state)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/adk.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/adk.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f66ea60a95714329ce56c93e516663815f151c5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/adk.py
@@ -0,0 +1,1846 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import asyncio
+from collections.abc import Awaitable
+import enum
+import os
+import queue
+import sys
+import threading
+from typing import (
+ Any,
+ AsyncIterable,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ TYPE_CHECKING,
+ Union,
+)
+import warnings
+
+import google.auth
+from google.auth.transport import mtls
+from google.auth.transport import requests as requests_auth
+
+if TYPE_CHECKING:
+ try:
+ from google.adk.events.event import Event
+
+ Event = Event
+ except (ImportError, AttributeError):
+ Event = Any
+
+ try:
+ from google.adk.apps import App
+
+ App = App
+ except (ImportError, AttributeError):
+ App = Any
+
+ try:
+ from google.adk.agents import BaseAgent
+
+ BaseAgent = BaseAgent
+ except (ImportError, AttributeError):
+ BaseAgent = Any
+
+ try:
+ from google.adk.plugins.base_plugin import BasePlugin
+
+ BasePlugin = BasePlugin
+ except (ImportError, AttributeError):
+ BasePlugin = Any
+
+ try:
+ from google.adk.sessions import BaseSessionService
+
+ BaseSessionService = BaseSessionService
+ except (ImportError, AttributeError):
+ BaseSessionService = Any
+
+ try:
+ from google.adk.artifacts import BaseArtifactService
+
+ BaseArtifactService = BaseArtifactService
+ except (ImportError, AttributeError):
+ BaseArtifactService = Any
+
+ try:
+ from google.adk.memory import BaseMemoryService
+
+ BaseMemoryService = BaseMemoryService
+ except (ImportError, AttributeError):
+ BaseMemoryService = Any
+
+ try:
+ from opentelemetry.sdk import trace
+
+ TracerProvider = trace.TracerProvider
+ SpanProcessor = trace.SpanProcessor
+ SynchronousMultiSpanProcessor = trace.SynchronousMultiSpanProcessor
+ except (ImportError, AttributeError):
+ TracerProvider = Any
+ SpanProcessor = Any
+ SynchronousMultiSpanProcessor = Any
+
+
+_DEFAULT_APP_NAME = "default_app_name"
+_DEFAULT_USER_ID = "default-user-id"
+_TELEMETRY_API_DISABLED_WARNING = """\
+Tracing integration for Agent Engine has migrated to a new API.
+The 'telemetry.googleapis.com' has not been enabled in project %s.
+**Impact:** Until this API is enabled, telemetry data will not be stored.
+
+**Action:** Please enable the API by visiting https://console.developers.google.com/apis/api/telemetry.googleapis.com/overview?project=%s.
+
+(If you enabled this API recently, you can safely ignore this warning.)
+"""
+
+_DEFAULT_TELEMETRY_ENDPOINT = "https://telemetry.googleapis.com/v1/traces"
+_DEFAULT_MTLS_TELEMETRY_ENDPOINT = "https://telemetry.mtls.googleapis.com/v1/traces"
+
+
+class _MtlsEndpoint(enum.Enum):
+ """Enum for the mTLS endpoint setting."""
+
+ AUTO = "auto"
+ ALWAYS = "always"
+ NEVER = "never"
+
+
+def get_adk_version() -> Optional[str]:
+ """Returns the version of the ADK package."""
+ try:
+ from google.adk import version
+
+ return version.__version__
+ except (ImportError, AttributeError):
+ return None
+
+
+def is_version_sufficient(version_to_check: str) -> bool:
+ """Compares the existing version of ADK with the required version.
+
+ Args:
+ version_to_check: The version string to check.
+
+ Returns:
+ True if the existing version is sufficient, False otherwise.
+ """
+ try:
+ from packaging.version import parse
+
+ return parse(get_adk_version()) >= parse(version_to_check)
+ except (AttributeError, ImportError):
+ return False
+
+
+class _ArtifactVersion:
+ def __init__(self, **kwargs):
+ from google.genai import types
+
+ self.version: Optional[str] = kwargs.get("version")
+ data = kwargs.get("data")
+ self.data: Optional[types.Part] = (
+ types.Part.model_validate(data) if isinstance(data, dict) else data
+ )
+
+ def dump(self) -> Dict[str, Any]:
+ result = {}
+ if self.version:
+ result["version"] = self.version
+ if self.data:
+ result["data"] = self.data
+ return result
+
+
+class _Artifact:
+ def __init__(self, **kwargs):
+ self.file_name: Optional[str] = kwargs.get("file_name")
+ self.versions: List[_ArtifactVersion] = kwargs.get("versions")
+
+ def dump(self) -> Dict[str, Any]:
+ result = {}
+ if self.file_name:
+ result["file_name"] = self.file_name
+ if self.versions:
+ result["versions"] = [version.dump() for version in self.versions]
+ return result
+
+
+class _Authorization:
+ def __init__(self, **kwargs):
+ self.access_token: Optional[str] = kwargs.get("access_token") or kwargs.get(
+ "accessToken"
+ )
+
+
+class _StreamRunRequest:
+ """Request object for `streaming_agent_run_with_events` method."""
+
+ def __init__(self, **kwargs):
+ from google.adk.events.event import Event
+ from google.genai import types
+
+ self.message: Optional[types.Content] = kwargs.get("message")
+ # The new message to be processed by the agent.
+
+ self.events: Optional[List[Event]] = kwargs.get("events")
+ # List of preceding events happened in the same session.
+
+ self.artifacts: Optional[List[_Artifact]] = kwargs.get("artifacts")
+ # List of artifacts belonging to the session.
+
+ self.authorizations: Dict[str, _Authorization] = kwargs.get(
+ "authorizations", {}
+ )
+ # The authorizations of the user, keyed by authorization ID.
+
+ self.user_id: Optional[str] = kwargs.get("user_id") or kwargs.get(
+ "userId", _DEFAULT_USER_ID
+ )
+ # The user ID.
+
+ self.session_id: Optional[str] = kwargs.get("session_id") or kwargs.get(
+ "sessionId"
+ )
+ # The session ID.
+
+
+class _StreamingRunResponse:
+ """Response object for `streaming_agent_run_with_events` method.
+
+ It contains the generated events together with the belonging artifacts.
+ """
+
+ def __init__(self, **kwargs):
+ self.events: Optional[List["Event"]] = kwargs.get("events")
+ # List of generated events.
+ self.artifacts: Optional[List[_Artifact]] = kwargs.get("artifacts")
+ # List of artifacts belonging to the session.
+ self.session_id: Optional[str] = kwargs.get("session_id")
+ # The session ID.
+
+ def dump(self) -> Dict[str, Any]:
+ from agentplatform.agent_engines import _utils
+
+ result = {}
+ if self.events:
+ result["events"] = []
+ for event in self.events:
+ event_dict = _utils.dump_event_for_json(event)
+ event_dict["invocation_id"] = event_dict.get("invocation_id", "")
+ result["events"].append(event_dict)
+ if self.artifacts:
+ result["artifacts"] = [artifact.dump() for artifact in self.artifacts]
+ if self.session_id:
+ result["session_id"] = self.session_id
+ return result
+
+
+def _warn(msg: str):
+ if not hasattr(_warn, "_LOGGER"):
+ from google.cloud.aiplatform import base
+
+ _warn._LOGGER = base.Logger(
+ __name__
+ ) # pyright: ignore[reportFunctionMemberAccess]
+
+ _warn._LOGGER.warning(msg) # pyright: ignore[reportFunctionMemberAccess]
+
+
+async def _force_flush_otel(tracing_enabled: bool, logging_enabled: bool):
+ try:
+ import opentelemetry.trace
+ import opentelemetry._logs
+ except (ImportError, AttributeError):
+ _warn(
+ "Could not force flush telemetry data. opentelemetry-api is not installed. Please call 'pip install google-cloud-aiplatform[agent_engines]'."
+ )
+ return None
+
+ try:
+ import opentelemetry.sdk.trace
+ import opentelemetry.sdk._logs
+ except (ImportError, AttributeError):
+ _warn(
+ "Could not force flush telemetry data. opentelemetry-sdk is not installed. Please call 'pip install google-cloud-aiplatform[agent_engines]'."
+ )
+ return None
+
+ coros: List[Awaitable[bool]] = []
+
+ if tracing_enabled:
+ tracer_provider = opentelemetry.trace.get_tracer_provider()
+ if isinstance(tracer_provider, opentelemetry.sdk.trace.TracerProvider):
+ coros.append(asyncio.to_thread(tracer_provider.force_flush))
+
+ if logging_enabled:
+ logger_provider = opentelemetry._logs.get_logger_provider()
+ if isinstance(logger_provider, opentelemetry.sdk._logs.LoggerProvider):
+ coros.append(asyncio.to_thread(logger_provider.force_flush))
+
+ await asyncio.gather(*coros, return_exceptions=True)
+
+
+def _default_instrumentor_builder(
+ project_id: Optional[str],
+ *,
+ enable_tracing: bool = False,
+ enable_logging: bool = False,
+):
+ if not enable_tracing and not enable_logging:
+ return None
+
+ if project_id is None:
+ _warn(
+ "telemetry is only supported when project is specified, proceeding with"
+ " no telemetry"
+ )
+ return None
+
+ import os
+
+ def _warn_missing_dependency(
+ package: str,
+ *,
+ needed_for_logging: bool = False,
+ needed_for_tracing: bool = False,
+ ) -> None:
+ _warn(
+ f"{package} is not installed. Please call 'pip install"
+ " google-cloud-aiplatform[agent_engines]'."
+ )
+ MISSING_TRACE_IMPORT_ERROR_MESSAGE = (
+ "proceeding with tracing disabled because not all packages (i.e."
+ " `google-cloud-trace`, `opentelemetry-sdk`,"
+ " `opentelemetry-exporter-gcp-trace`) for tracing have been installed"
+ )
+ MISSING_LOGGING_IMPORT_ERROR_MESSAGE = (
+ "proceeding with logging disabled because not all packages (i.e."
+ " `google-cloud-logging`, `opentelemetry-sdk`,"
+ " `opentelemetry-exporter-gcp-logging`) for tracing have been installed"
+ )
+
+ if needed_for_tracing and enable_tracing:
+ _warn(MISSING_TRACE_IMPORT_ERROR_MESSAGE)
+ if needed_for_logging and enable_logging:
+ _warn(MISSING_LOGGING_IMPORT_ERROR_MESSAGE)
+ return None
+
+ def _detect_cloud_resource_id(project_id: str) -> Optional[str]:
+ location = os.getenv("GOOGLE_CLOUD_AGENT_ENGINE_LOCATION", "") or os.getenv(
+ "GOOGLE_CLOUD_LOCATION", ""
+ )
+ agent_engine_id = os.getenv("GOOGLE_CLOUD_AGENT_ENGINE_ID")
+ if all(v is not None for v in (location, agent_engine_id)):
+ return f"//aiplatform.googleapis.com/projects/{project_id}/locations/{location}/reasoningEngines/{agent_engine_id}"
+ return None
+
+ try:
+ import opentelemetry
+ import opentelemetry.trace
+ import opentelemetry._logs
+ import opentelemetry._events
+ except (ImportError, AttributeError):
+ return _warn_missing_dependency(
+ "opentelemetry-api", needed_for_tracing=True, needed_for_logging=True
+ )
+
+ try:
+ import opentelemetry.sdk.resources
+ import opentelemetry.sdk.trace
+ import opentelemetry.sdk.trace.export
+ import opentelemetry.sdk._logs
+ import opentelemetry.sdk._logs.export
+ import opentelemetry.sdk._events
+ except (ImportError, AttributeError):
+ return _warn_missing_dependency(
+ "opentelemetry-sdk", needed_for_tracing=True, needed_for_logging=True
+ )
+
+ import uuid
+
+ # Provide a set of resource attributes but allow to override them with env
+ # variables like OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME.
+ cloud_resource_id = _detect_cloud_resource_id(project_id)
+ resource = opentelemetry.sdk.resources.Resource.create(
+ attributes={
+ "gcp.project_id": project_id,
+ "cloud.account.id": project_id,
+ "cloud.provider": "gcp",
+ "cloud.platform": "gcp.agent_engine",
+ "service.name": os.getenv("GOOGLE_CLOUD_AGENT_ENGINE_ID", ""),
+ "service.instance.id": f"{uuid.uuid4().hex}-{os.getpid()}",
+ "cloud.region": (
+ os.getenv("GOOGLE_CLOUD_AGENT_ENGINE_LOCATION", "")
+ or os.getenv("GOOGLE_CLOUD_LOCATION", "")
+ ),
+ }
+ | (
+ {"cloud.resource_id": cloud_resource_id}
+ if cloud_resource_id is not None
+ else {}
+ )
+ ).merge(opentelemetry.sdk.resources.OTELResourceDetector().detect())
+
+ if enable_tracing:
+ try:
+ import opentelemetry.exporter.otlp.proto.http.version
+ import opentelemetry.exporter.otlp.proto.http.trace_exporter
+ import google.auth.transport.requests
+ from google.cloud.aiplatform import version as aip_version
+ except (ImportError, AttributeError):
+ return _warn_missing_dependency(
+ "opentelemetry-exporter-otlp-proto-http", needed_for_tracing=True
+ )
+
+ import google.auth
+
+ credentials, _ = google.auth.default()
+ vertex_sdk_version = aip_version.__version__
+ otlp_http_version = opentelemetry.exporter.otlp.proto.http.version.__version__
+ user_agent = (
+ f"Vertex-Agent-Engine/{vertex_sdk_version}"
+ f" OTel-OTLP-Exporter-Python/{otlp_http_version}"
+ )
+
+ session = requests_auth.AuthorizedSession(credentials=credentials)
+
+ use_client_cert = _use_client_cert_effective()
+ if use_client_cert:
+ client_cert_source = (
+ mtls.default_client_cert_source()
+ if mtls.has_default_client_cert_source()
+ else None
+ )
+ session.configure_mtls_channel()
+ endpoint = _get_api_endpoint(client_cert_source)
+ else:
+ endpoint = _DEFAULT_TELEMETRY_ENDPOINT
+
+ span_exporter = (
+ opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter(
+ session=session,
+ endpoint=endpoint,
+ headers={"User-Agent": user_agent},
+ )
+ )
+ span_processor = opentelemetry.sdk.trace.export.BatchSpanProcessor(
+ span_exporter=span_exporter,
+ )
+ tracer_provider = opentelemetry.trace.get_tracer_provider()
+ # Get the appropriate tracer provider:
+ # 1. If _TRACER_PROVIDER is already set, use that.
+ # 2. Otherwise, if the OTEL_PYTHON_TRACER_PROVIDER environment
+ # variable is set, use that.
+ # 3. As a final fallback, use _PROXY_TRACER_PROVIDER.
+ # If none of the above is set, we log a warning, and
+ # create a tracer provider.
+ if not tracer_provider:
+ _warn(
+ "No tracer provider. By default, "
+ "we should get one of the following providers: "
+ "OTEL_PYTHON_TRACER_PROVIDER, _TRACER_PROVIDER, "
+ "or _PROXY_TRACER_PROVIDER."
+ )
+ tracer_provider = opentelemetry.sdk.trace.TracerProvider(resource=resource)
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids AttributeError:
+ # 'ProxyTracerProvider' and 'NoOpTracerProvider' objects has no
+ # attribute 'add_span_processor'.
+ from agentplatform.agent_engines import _utils
+
+ if _utils.is_noop_or_proxy_tracer_provider(tracer_provider):
+ tracer_provider = opentelemetry.sdk.trace.TracerProvider(resource=resource)
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids OpenTelemetry client already exists error.
+ _override_active_span_processor(
+ tracer_provider,
+ opentelemetry.sdk.trace.SynchronousMultiSpanProcessor(),
+ )
+ tracer_provider.add_span_processor(span_processor)
+
+ if enable_logging:
+ try:
+ import opentelemetry.exporter.cloud_logging
+ except (ImportError, AttributeError):
+ return _warn_missing_dependency(
+ "opentelemetry-exporter-gcp-logging", needed_for_logging=True
+ )
+
+ class _SimpleLogRecordProcessor(
+ opentelemetry.sdk._logs.export.SimpleLogRecordProcessor
+ ):
+
+ def force_flush(
+ self, timeout_millis: int = 30000
+ ) -> bool: # pylint: disable=no-self-use
+ sys.stdout.flush()
+ sys.stderr.flush()
+ return True
+
+ logger_provider = opentelemetry.sdk._logs.LoggerProvider(resource=resource)
+ # Use the legacy log processor when experimental semconv is enabled.
+ # Exporting JSON logs to stdout is bugged; Agent Engine fails to
+ # correctly parse the `gen_ai.client.inference.operation.details`
+ # messages.
+ # TODO: b/480102541 - Unify both branches once the regression is fixed.
+ if "gen_ai_latest_experimental" in os.getenv(
+ "OTEL_SEMCONV_STABILITY_OPT_IN", ""
+ ).split(","):
+ logger_provider.add_log_record_processor(
+ opentelemetry.sdk._logs.export.BatchLogRecordProcessor(
+ opentelemetry.exporter.cloud_logging.CloudLoggingExporter(
+ project_id=project_id,
+ default_log_name=os.getenv(
+ "GCP_DEFAULT_LOG_NAME", "adk-on-agent-engine"
+ ),
+ ),
+ )
+ )
+ else:
+ logger_provider.add_log_record_processor(
+ _SimpleLogRecordProcessor(
+ opentelemetry.exporter.cloud_logging.CloudLoggingExporter(
+ project_id=project_id,
+ default_log_name=os.getenv(
+ "GCP_DEFAULT_LOG_NAME", "adk-on-agent-engine"
+ ),
+ structured_json_file=sys.stdout,
+ ),
+ )
+ )
+ event_logger_provider = opentelemetry.sdk._events.EventLoggerProvider(
+ logger_provider=logger_provider
+ )
+
+ opentelemetry._logs.set_logger_provider(logger_provider=logger_provider)
+ opentelemetry._events.set_event_logger_provider(
+ event_logger_provider=event_logger_provider
+ )
+
+ try:
+ from opentelemetry.instrumentation import google_genai
+
+ google_genai.GoogleGenAiSdkInstrumentor().instrument()
+ except (ImportError, AttributeError):
+ _warn(
+ "telemetry enabled but proceeding without GenAI instrumentation,"
+ " because not all packages (i.e."
+ " opentelemetry-instrumentation-google-genai) have been installed"
+ )
+
+ return None
+
+
+def _override_active_span_processor(
+ tracer_provider: "TracerProvider",
+ active_span_processor: "SynchronousMultiSpanProcessor",
+):
+ """Overrides the active span processor.
+
+ When working with multiple LangchainAgents in the same environment,
+ it's crucial to manage trace exports carefully.
+ Each agent needs its own span processor tied to a unique project ID.
+ While we add a new span processor for each agent, this can lead to
+ unexpected behavior.
+ For instance, with two agents linked to different projects, traces from the
+ second agent might be sent to both projects.
+ To prevent this and guarantee traces go to the correct project, we overwrite
+ the active span processor whenever a new LangchainAgent is created.
+
+ Args:
+ tracer_provider (TracerProvider):
+ The tracer provider to use for the project.
+ active_span_processor (SynchronousMultiSpanProcessor):
+ The active span processor overrides the tracer provider's
+ active span processor.
+ """
+ if tracer_provider._active_span_processor:
+ tracer_provider._active_span_processor.shutdown()
+ tracer_provider._active_span_processor = active_span_processor
+
+
+def _validate_run_config(run_config: Optional[Dict[str, Any]]):
+ """Validates the run config."""
+ from google.adk.agents.run_config import RunConfig
+
+ if run_config is None:
+ return None
+ elif isinstance(run_config, Dict):
+ return RunConfig.model_validate(run_config)
+ raise TypeError("run_config must be a dictionary representing a RunConfig object.")
+
+
+def _warn_if_telemetry_api_disabled():
+ """Warn if telemetry API is disabled."""
+ credentials, project = google.auth.default()
+ session = requests_auth.AuthorizedSession(credentials=credentials)
+
+ use_client_cert = _use_client_cert_effective()
+ if use_client_cert:
+ client_cert_source = (
+ mtls.default_client_cert_source()
+ if mtls.has_default_client_cert_source()
+ else None
+ )
+ session.configure_mtls_channel()
+ endpoint = _get_api_endpoint(client_cert_source)
+ else:
+ endpoint = _DEFAULT_TELEMETRY_ENDPOINT
+ r = session.post(endpoint, data=None)
+ if "Telemetry API has not been used in project" in r.text:
+ _warn(_TELEMETRY_API_DISABLED_WARNING % (project, project))
+
+
+def _get_api_endpoint(client_cert_source: bytes | None = None) -> str:
+ """Returns API endpoint based on mTLS configuration and cert availability.
+
+ Args:
+ client_cert_source (bytes | None): The client certificate source.
+
+ Returns:
+ str: The API endpoint to be used.
+ """
+ use_mtls_endpoint_str = os.getenv(
+ "GOOGLE_API_USE_MTLS_ENDPOINT", _MtlsEndpoint.AUTO.value
+ ).lower()
+
+ try:
+ use_mtls_endpoint = _MtlsEndpoint(use_mtls_endpoint_str)
+ except ValueError:
+ _warn(
+ f"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be one of "
+ f"{[e.value for e in _MtlsEndpoint]}. Defaulting to"
+ f" {_MtlsEndpoint.AUTO.value}."
+ )
+ use_mtls_endpoint = _MtlsEndpoint.AUTO
+
+ if (use_mtls_endpoint == _MtlsEndpoint.ALWAYS) or (
+ use_mtls_endpoint == _MtlsEndpoint.AUTO and client_cert_source
+ ):
+ return _DEFAULT_MTLS_TELEMETRY_ENDPOINT
+
+ return _DEFAULT_TELEMETRY_ENDPOINT
+
+
+def _use_client_cert_effective() -> bool:
+ """Returns whether client certificate should be used for mTLS.
+
+ This checks if the google-auth version supports should_use_client_cert
+ automatic mTLS enablement. Alternatively, it reads from the
+ GOOGLE_API_USE_CLIENT_CERTIFICATE env var.
+
+ Returns:
+ bool: whether client certificate should be used for mTLS.
+ """
+ # check if google-auth version supports should_use_client_cert for automatic
+ # mTLS enablement
+ try:
+ return mtls.should_use_client_cert()
+ except (ImportError, AttributeError):
+ # if unsupported, fallback to reading from env var
+ use_client_cert_str = os.getenv(
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
+ ).lower()
+ if use_client_cert_str not in ("true", "false"):
+ _warn(
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be"
+ " either `true` or `false`"
+ )
+ return use_client_cert_str == "true"
+
+
+class AdkApp:
+ """An ADK Application."""
+
+ agent_framework = "google-adk"
+
+ def __init__(
+ self,
+ *,
+ app: "App" = None,
+ agent: "BaseAgent" = None,
+ app_name: Optional[str] = None,
+ plugins: Optional[List["BasePlugin"]] = None,
+ enable_tracing: Optional[bool] = None,
+ session_service_builder: Optional[Callable[..., "BaseSessionService"]] = None,
+ artifact_service_builder: Optional[Callable[..., "BaseArtifactService"]] = None,
+ memory_service_builder: Optional[Callable[..., "BaseMemoryService"]] = None,
+ instrumentor_builder: Optional[Callable[..., Any]] = None,
+ ):
+ """An ADK Application.
+
+ See https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/adk
+ for details on how to develop ADK applications on Agent Engine.
+
+ Args:
+ agent (google.adk.agents.BaseAgent):
+ Required. The ADK agent to run.
+ app_name (str):
+ Optional. The name of the ADK application. Defaults to
+ "default-app-name" when running locally, and to the
+ corresponding agent engine ID when deployed on Agent Engine.
+ plugins (List[BasePlugin]):
+ Optional. The plugins to use for the ADK application.
+ Defaults to an empty list.
+ enable_tracing (bool):
+ Optional. Whether to enable tracing in Cloud Trace. Defaults to
+ False.
+ session_service_builder (Callable[..., BaseSessionService]):
+ Optional. A callable that returns an ADK session service.
+ Defaults to a callable that returns InMemorySessionService
+ when running locally and VertexAiSessionService when running
+ on Agent Engine.
+ artifact_service_builder (Callable[..., BaseArtifactService]):
+ Optional. A callable that returns an ADK artifact service.
+ Defaults to a callable that returns InMemoryArtifactService.
+ memory_service_builder (Callable[..., BaseMemoryService]):
+ Optional. A callable that returns an ADK memory service.
+ Defaults to a callable that returns InMemoryMemoryService
+ when running locally and VertexAiMemoryBankService when running
+ on Agent Engine.
+ instrumentor_builder (Callable[..., Any]):
+ Optional. Callable that returns a new instrumentor. This can be
+ used for customizing the instrumentation logic of the Agent.
+ If not provided, a default instrumentor builder will be used.
+ This parameter is ignored if `enable_tracing` is False.
+ """
+ import os
+ from google.cloud.aiplatform import initializer
+
+ adk_version = get_adk_version()
+ if not is_version_sufficient("1.5.0"):
+ msg = (
+ f"Unsupported google-adk version: {adk_version}, please use "
+ "google-adk>=1.5.0 for AdkApp deployment on Agent Engine."
+ )
+ raise ValueError(msg)
+
+ if not agent and not app:
+ raise ValueError("One of `agent` or `app` must be provided.")
+ if app:
+ if app_name:
+ raise ValueError(
+ "When app is provided, app_name should not be provided, "
+ "since it will be derived from app.name."
+ )
+ if agent:
+ raise ValueError("When app is provided, agent should not be provided.")
+ if plugins:
+ raise ValueError(
+ "When app is provided, plugins should not be provided and"
+ " should be provided in the app instead."
+ )
+
+ self._tmpl_attrs: Dict[str, Any] = {
+ "project": initializer.global_config.project,
+ "location": initializer.global_config.location,
+ "agent": agent,
+ "app": app,
+ "app_name": app_name,
+ "plugins": plugins,
+ "enable_tracing": enable_tracing,
+ "session_service_builder": session_service_builder,
+ "artifact_service_builder": artifact_service_builder,
+ "memory_service_builder": memory_service_builder,
+ "instrumentor_builder": instrumentor_builder,
+ "express_mode_api_key": (
+ initializer.global_config.api_key or os.environ.get("GOOGLE_API_KEY")
+ ),
+ }
+
+ def _serialize(self, obj: Any) -> Any:
+ """Serializes an object to be JSON compatible."""
+ if hasattr(obj, "model_dump"):
+ return obj.model_dump(mode="json")
+ elif hasattr(obj, "dict"):
+ return self._serialize(obj.dict())
+ elif isinstance(obj, dict):
+ return {k: self._serialize(v) for k, v in obj.items()}
+ elif isinstance(obj, list):
+ return [self._serialize(v) for v in obj]
+ return obj
+
+ def _app_name(self) -> str:
+ """Returns the app name."""
+ app = self._tmpl_attrs.get("app")
+ return app.name if app else self._tmpl_attrs.get("app_name")
+
+ async def _init_session(
+ self,
+ session_service: "BaseSessionService",
+ artifact_service: "BaseArtifactService",
+ request: _StreamRunRequest,
+ ):
+ """Initializes the session, and returns the session id."""
+ from google.adk.events.event import Event
+
+ session_state = None
+ if request.authorizations:
+ session_state = {}
+ for auth_id, auth in request.authorizations.items():
+ auth = _Authorization(**auth)
+ session_state[auth_id] = auth.access_token
+
+ session = await session_service.create_session(
+ app_name=self._app_name(),
+ user_id=request.user_id,
+ state=session_state,
+ )
+ if not session:
+ raise RuntimeError("Create session failed.")
+ if request.events:
+ for event in request.events:
+ await session_service.append_event(session, Event(**event))
+ if request.artifacts:
+ await self._save_artifacts(session.id, artifact_service, request)
+ return session
+
+ async def _save_artifacts(
+ self,
+ session_id: str,
+ artifact_service: "BaseArtifactService",
+ request: _StreamRunRequest,
+ ):
+ """Saves the artifacts."""
+ if request.artifacts:
+ for artifact in request.artifacts:
+ artifact = _Artifact(**artifact)
+ for version_data in sorted(
+ artifact.versions, key=lambda x: x["version"]
+ ):
+ version_data = _ArtifactVersion(**version_data)
+ saved_version = await artifact_service.save_artifact(
+ app_name=self._app_name(),
+ user_id=request.user_id,
+ session_id=session_id,
+ filename=artifact.file_name,
+ artifact=version_data.data,
+ )
+ if saved_version != version_data.version:
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.debug(
+ "Artifact '%s' saved at version %s instead of %s",
+ artifact.file_name,
+ saved_version,
+ version_data.version,
+ )
+
+ async def _convert_response_events(
+ self,
+ user_id: str,
+ session_id: str,
+ events: List["Event"],
+ artifact_service: Optional["BaseArtifactService"],
+ ) -> _StreamingRunResponse:
+ """Converts the events to the streaming run response object."""
+ import collections
+
+ result = _StreamingRunResponse(
+ events=events, artifacts=[], session_id=session_id
+ )
+
+ # Save the generated artifacts into the result object.
+ artifact_versions = collections.defaultdict(list)
+ for event in events:
+ if event.actions and event.actions.artifact_delta:
+ for key, version in event.actions.artifact_delta.items():
+ artifact_versions[key].append(version)
+
+ for key, versions in artifact_versions.items():
+ result.artifacts.append(
+ _Artifact(
+ file_name=key,
+ versions=[
+ _ArtifactVersion(
+ version=version,
+ data=await artifact_service.load_artifact(
+ app_name=self._app_name(),
+ user_id=user_id,
+ session_id=session_id,
+ filename=key,
+ version=version,
+ ),
+ )
+ for version in versions
+ ],
+ )
+ )
+
+ return result.dump()
+
+ def clone(self):
+ """Returns a clone of the ADK application."""
+ import copy
+
+ return self.__class__(
+ app=copy.deepcopy(self._tmpl_attrs.get("app")),
+ enable_tracing=self._tmpl_attrs.get("enable_tracing"),
+ agent=(
+ None
+ if self._tmpl_attrs.get("app")
+ else copy.deepcopy(self._tmpl_attrs.get("agent"))
+ ),
+ app_name=(
+ None
+ if self._tmpl_attrs.get("app")
+ else self._tmpl_attrs.get("app_name")
+ ),
+ plugins=(
+ None
+ if self._tmpl_attrs.get("app")
+ else copy.deepcopy(self._tmpl_attrs.get("plugins"))
+ ),
+ session_service_builder=self._tmpl_attrs.get("session_service_builder"),
+ artifact_service_builder=self._tmpl_attrs.get("artifact_service_builder"),
+ memory_service_builder=self._tmpl_attrs.get("memory_service_builder"),
+ instrumentor_builder=self._tmpl_attrs.get("instrumentor_builder"),
+ )
+
+ def set_up(self):
+ """Sets up the ADK application."""
+ import os
+ from google.adk.runners import Runner
+ from google.adk.sessions.in_memory_session_service import InMemorySessionService
+ from google.adk.artifacts.in_memory_artifact_service import (
+ InMemoryArtifactService,
+ )
+ from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
+
+ os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "1"
+ project = self._tmpl_attrs.get("project")
+ if project:
+ os.environ["GOOGLE_CLOUD_PROJECT"] = project
+ location = self._tmpl_attrs.get("location")
+ if location:
+ if "GOOGLE_CLOUD_AGENT_ENGINE_LOCATION" not in os.environ:
+ os.environ["GOOGLE_CLOUD_AGENT_ENGINE_LOCATION"] = location
+ if "GOOGLE_CLOUD_LOCATION" not in os.environ:
+ os.environ["GOOGLE_CLOUD_LOCATION"] = location
+ agent_engine_location = os.environ.get(
+ "GOOGLE_CLOUD_AGENT_ENGINE_LOCATION", # the runtime env var (if set)
+ location, # the location set in the AdkApp template
+ )
+ express_mode_api_key = self._tmpl_attrs.get("express_mode_api_key")
+ if express_mode_api_key and not project:
+ os.environ["GOOGLE_API_KEY"] = express_mode_api_key
+ # Clear location and project env vars if express mode api key is provided.
+ os.environ.pop("GOOGLE_CLOUD_AGENT_ENGINE_LOCATION", None)
+ os.environ.pop("GOOGLE_CLOUD_LOCATION", None)
+ os.environ.pop("GOOGLE_CLOUD_PROJECT", None)
+ location = None
+
+ # Disable content capture in custom ADK spans unless user enabled
+ # tracing explicitly with the old flag
+ # (this is to preserve compatibility with old behavior).
+ if self._tmpl_attrs.get("enable_tracing"):
+ os.environ["ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS"] = "true"
+ else:
+ os.environ["ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS"] = "false"
+
+ enable_logging = bool(self._telemetry_enabled())
+
+ custom_instrumentor = self._tmpl_attrs.get("instrumentor_builder")
+
+ if self._tmpl_attrs.get("enable_tracing"):
+ _warn_if_telemetry_api_disabled()
+
+ if self._tmpl_attrs.get("enable_tracing") is False:
+ _warn(
+ (
+ "Your 'enable_tracing=False' setting is being deprecated "
+ "and will be removed in a future release.\n"
+ "This legacy setting overrides the new Cloud Console "
+ "toggle and environment variable controls.\n"
+ "Impact: The Cloud Console may incorrectly show telemetry "
+ "as 'On' when it is actually 'Off', and the UI toggle will "
+ "not work.\n"
+ "Action: To fix this and control telemetry, please remove "
+ "the 'enable_tracing' parameter from your deployment "
+ "code.\n"
+ "You can then use the "
+ "'GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY' "
+ "environment variable:\n"
+ "agent_engines.create(\n"
+ " env_vars={\n"
+ ' "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY": true|false\n'
+ " }\n"
+ ")\n"
+ "or the toggle in the Cloud Console: "
+ "https://console.cloud.google.com/vertex-ai/agents."
+ ),
+ )
+
+ if custom_instrumentor and self._tracing_enabled():
+ self._tmpl_attrs["instrumentor"] = custom_instrumentor(self.project_id())
+
+ if not custom_instrumentor:
+ self._tmpl_attrs["instrumentor"] = _default_instrumentor_builder(
+ self.project_id(),
+ enable_tracing=self._tracing_enabled(),
+ enable_logging=enable_logging,
+ )
+
+ if not self._tmpl_attrs.get("app_name"):
+ if "GOOGLE_CLOUD_AGENT_ENGINE_ID" in os.environ:
+ self._tmpl_attrs["app_name"] = os.environ.get(
+ "GOOGLE_CLOUD_AGENT_ENGINE_ID",
+ )
+ else:
+ self._tmpl_attrs["app_name"] = _DEFAULT_APP_NAME
+
+ artifact_service_builder = self._tmpl_attrs.get("artifact_service_builder")
+ if artifact_service_builder:
+ self._tmpl_attrs["artifact_service"] = artifact_service_builder()
+ else:
+ self._tmpl_attrs["artifact_service"] = InMemoryArtifactService()
+
+ session_service_builder = self._tmpl_attrs.get("session_service_builder")
+ if session_service_builder:
+ self._tmpl_attrs["session_service"] = session_service_builder()
+ elif "GOOGLE_CLOUD_AGENT_ENGINE_ID" in os.environ:
+ try:
+ from google.adk.sessions.vertex_ai_session_service import (
+ VertexAiSessionService,
+ )
+
+ # If the express mode api key is set, it will be read from the
+ # environment variable when initializing the session service.
+ self._tmpl_attrs["session_service"] = VertexAiSessionService(
+ project=project,
+ location=agent_engine_location,
+ agent_engine_id=os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID"),
+ )
+ except (ImportError, AttributeError):
+ from google.adk.sessions.vertex_ai_session_service_g3 import (
+ VertexAiSessionService,
+ )
+
+ # If the express mode api key is set, it will be read from the
+ # environment variable when initializing the session service.
+ self._tmpl_attrs["session_service"] = VertexAiSessionService(
+ project=project,
+ location=agent_engine_location,
+ agent_engine_id=os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID"),
+ )
+
+ else:
+ self._tmpl_attrs["session_service"] = InMemorySessionService()
+
+ memory_service_builder = self._tmpl_attrs.get("memory_service_builder")
+ if memory_service_builder:
+ self._tmpl_attrs["memory_service"] = memory_service_builder()
+ elif "GOOGLE_CLOUD_AGENT_ENGINE_ID" in os.environ and is_version_sufficient(
+ "1.5.0"
+ ):
+ try:
+ from google.adk.memory.vertex_ai_memory_bank_service import (
+ VertexAiMemoryBankService,
+ )
+
+ # If the express mode api key is set, it will be read from the
+ # environment variable when initializing the memory service.
+ self._tmpl_attrs["memory_service"] = VertexAiMemoryBankService(
+ project=project,
+ location=agent_engine_location,
+ agent_engine_id=os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID"),
+ )
+ except (ImportError, AttributeError):
+ from google.adk.memory.vertex_ai_memory_bank_service_g3 import (
+ VertexAiMemoryBankService,
+ )
+
+ # If the express mode api key is set, it will be read from the
+ # environment variable when initializing the memory service.
+ self._tmpl_attrs["memory_service"] = VertexAiMemoryBankService(
+ project=project,
+ location=agent_engine_location,
+ agent_engine_id=os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID"),
+ )
+ else:
+ self._tmpl_attrs["memory_service"] = InMemoryMemoryService()
+
+ self._tmpl_attrs["runner"] = Runner(
+ app=self._tmpl_attrs.get("app"),
+ agent=(
+ None if self._tmpl_attrs.get("app") else self._tmpl_attrs.get("agent")
+ ),
+ app_name=(
+ None
+ if self._tmpl_attrs.get("app")
+ else self._tmpl_attrs.get("app_name")
+ ),
+ plugins=(
+ None if self._tmpl_attrs.get("app") else self._tmpl_attrs.get("plugins")
+ ),
+ session_service=self._tmpl_attrs.get("session_service"),
+ artifact_service=self._tmpl_attrs.get("artifact_service"),
+ memory_service=self._tmpl_attrs.get("memory_service"),
+ )
+ self._tmpl_attrs["in_memory_session_service"] = InMemorySessionService()
+ self._tmpl_attrs["in_memory_artifact_service"] = InMemoryArtifactService()
+ self._tmpl_attrs["in_memory_memory_service"] = InMemoryMemoryService()
+ self._tmpl_attrs["in_memory_runner"] = Runner(
+ app=self._tmpl_attrs.get("app"),
+ app_name=(
+ None
+ if self._tmpl_attrs.get("app")
+ else self._tmpl_attrs.get("app_name")
+ ),
+ agent=(
+ None if self._tmpl_attrs.get("app") else self._tmpl_attrs.get("agent")
+ ),
+ plugins=(
+ None if self._tmpl_attrs.get("app") else self._tmpl_attrs.get("plugins")
+ ),
+ session_service=self._tmpl_attrs.get("in_memory_session_service"),
+ artifact_service=self._tmpl_attrs.get("in_memory_artifact_service"),
+ memory_service=self._tmpl_attrs.get("in_memory_memory_service"),
+ )
+
+ async def async_stream_query(
+ self,
+ *,
+ message: Union[str, Dict[str, Any]],
+ user_id: str,
+ session_id: Optional[str] = None,
+ session_events: Optional[List[Dict[str, Any]]] = None,
+ run_config: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ) -> AsyncIterable[Dict[str, Any]]:
+ """Streams responses asynchronously from the ADK application.
+
+ Args:
+ message (str):
+ Required. The message to stream responses for.
+ user_id (str):
+ Required. The ID of the user.
+ session_id (str):
+ Optional. The ID of the session. If not provided, a new
+ session will be created for the user. If this is specified, then
+ `session_events` will be ignored.
+ session_events (Optional[List[Dict[str, Any]]]):
+ Optional. The session events to use for the query. This will be
+ used to initialize the session if `session_id` is not provided.
+ run_config (Optional[Dict[str, Any]]):
+ Optional. The run config to use for the query. If you want to
+ pass in a `run_config` pydantic object, you can pass in a dict
+ representing it as `run_config.model_dump(mode="json")`.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ runner.
+
+ Yields:
+ Event dictionaries asynchronously.
+
+ Raises:
+ TypeError: If message is not a string or a dictionary representing
+ a Content object.
+ ValueError: If both session_id and session_events are specified.
+ """
+ from agentplatform.agent_engines import _utils
+ from google.genai import types
+
+ if isinstance(message, Dict):
+ content = types.Content.model_validate(message)
+ elif isinstance(message, str):
+ content = types.Content(role="user", parts=[types.Part(text=message)])
+ else:
+ raise TypeError(
+ "message must be a string or a dictionary representing"
+ " a Content object."
+ )
+
+ if not self._tmpl_attrs.get("runner"):
+ self.set_up()
+ if session_id and session_events:
+ raise ValueError(
+ "Only one of session_id and session_events should be specified."
+ )
+ if not session_id:
+ session = await self.async_create_session(user_id=user_id)
+ session_id = session["id"]
+ if session_events is not None:
+ # We allow for session_events to be an empty list.
+ from google.adk.events.event import Event
+
+ session_service = self._tmpl_attrs.get("session_service")
+ for event in session_events:
+ if not isinstance(event, Event):
+ event = Event.model_validate(event)
+ await session_service.append_event(
+ session=session,
+ event=event,
+ )
+
+ run_config = _validate_run_config(run_config)
+ if run_config:
+ events_async = self._tmpl_attrs.get("runner").run_async(
+ user_id=user_id,
+ session_id=session_id,
+ new_message=content,
+ run_config=run_config,
+ **kwargs,
+ )
+ else:
+ events_async = self._tmpl_attrs.get("runner").run_async(
+ user_id=user_id,
+ session_id=session_id,
+ new_message=content,
+ **kwargs,
+ )
+
+ try:
+ async for event in events_async:
+ # Yield the event data as a dictionary
+ yield _utils.dump_event_for_json(event)
+ finally:
+ # Avoid telemetry data loss having to do with CPU throttling on instance turndown
+ _ = await _force_flush_otel(
+ tracing_enabled=self._tracing_enabled(),
+ logging_enabled=bool(self._telemetry_enabled()),
+ )
+
+ def stream_query(
+ self,
+ *,
+ message: Union[str, Dict[str, Any]],
+ user_id: str,
+ session_id: Optional[str] = None,
+ run_config: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """Deprecated. Use async_stream_query instead.
+
+ Streams responses from the ADK application in response to a message.
+
+ Args:
+ message (Union[str, Dict[str, Any]]):
+ Required. The message to stream responses for.
+ user_id (str):
+ Required. The ID of the user.
+ session_id (str):
+ Optional. The ID of the session. If not provided, a new
+ session will be created for the user.
+ run_config (Optional[Dict[str, Any]]):
+ Optional. The run config to use for the query. If you want to
+ pass in a `run_config` pydantic object, you can pass in a dict
+ representing it as `run_config.model_dump(mode="json")`.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ runner.
+
+ Yields:
+ The output of querying the ADK application.
+ """
+ warnings.warn(
+ (
+ "AdkApp.stream_query(...) is deprecated. "
+ "Use AdkApp.async_stream_query(...) instead. See "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/use/adk#stream-responses "
+ "for more details."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ from agentplatform.agent_engines import _utils
+ from google.genai import types
+
+ if isinstance(message, Dict):
+ content = types.Content.model_validate(message)
+ elif isinstance(message, str):
+ content = types.Content(role="user", parts=[types.Part(text=message)])
+ else:
+ raise TypeError(
+ "message must be a string or a dictionary representing"
+ " a Content object."
+ )
+
+ if not self._tmpl_attrs.get("runner"):
+ self.set_up()
+ if not session_id:
+ session = self.create_session(user_id=user_id)
+ session_id = session["id"]
+ run_config = _validate_run_config(run_config)
+ if run_config:
+ for event in self._tmpl_attrs.get("runner").run(
+ user_id=user_id,
+ session_id=session_id,
+ new_message=content,
+ run_config=run_config,
+ **kwargs,
+ ):
+ yield _utils.dump_event_for_json(event)
+ else:
+ for event in self._tmpl_attrs.get("runner").run(
+ user_id=user_id,
+ session_id=session_id,
+ new_message=content,
+ **kwargs,
+ ):
+ yield _utils.dump_event_for_json(event)
+
+ async def streaming_agent_run_with_events(self, request_json: str):
+ """Streams responses asynchronously from the ADK application.
+
+ In general, you should use `async_stream_query` instead, as it has a
+ more structured API and works with the respective ADK services that
+ you have defined for the AdkApp. This method is primarily meant for
+ invocation from AgentSpace.
+
+ Args:
+ request_json (str):
+ Required. The request to stream responses for.
+ """
+
+ import json
+ from google.genai import types
+ from google.genai.errors import ClientError
+
+ request = _StreamRunRequest(**json.loads(request_json))
+ if not any(
+ self._tmpl_attrs.get(service)
+ for service in (
+ "in_memory_runner",
+ "runner",
+ "in_memory_artifact_service",
+ "artifact_service",
+ "in_memory_session_service",
+ "session_service",
+ "in_memory_memory_service",
+ "memory_service",
+ )
+ ):
+ self.set_up()
+
+ # Try to get the session, if it doesn't exist, create a new one.
+ if request.session_id:
+ session_service = self._tmpl_attrs.get("session_service")
+ artifact_service = self._tmpl_attrs.get("artifact_service")
+ runner = self._tmpl_attrs.get("runner")
+ session = None
+ try:
+ session = await session_service.get_session(
+ app_name=self._app_name(),
+ user_id=request.user_id,
+ session_id=request.session_id,
+ )
+ if session:
+ await self._save_artifacts(
+ session_id=request.session_id,
+ artifact_service=artifact_service,
+ request=request,
+ )
+ except ClientError:
+ pass
+ if not session:
+ # Fall back to create session if the session is not found.
+ # Specifying session_id on creation is not supported,
+ # so session id will be regenerated.
+ session = await self._init_session(
+ session_service=session_service,
+ artifact_service=artifact_service,
+ request=request,
+ )
+ else:
+ # Not providing a session ID will create a new in-memory session.
+ session_service = self._tmpl_attrs.get("in_memory_session_service")
+ artifact_service = self._tmpl_attrs.get("in_memory_artifact_service")
+ runner = self._tmpl_attrs.get("in_memory_runner")
+ session = await self._init_session(
+ session_service=session_service,
+ artifact_service=artifact_service,
+ request=request,
+ )
+ if not session:
+ raise RuntimeError("Session initialization failed.")
+
+ # Run the agent
+ message_for_agent = types.Content(**request.message)
+ try:
+ async for event in runner.run_async(
+ user_id=request.user_id,
+ session_id=session.id,
+ new_message=message_for_agent,
+ ):
+ converted_event = await self._convert_response_events(
+ user_id=request.user_id,
+ session_id=session.id,
+ events=[event],
+ artifact_service=artifact_service,
+ )
+ yield converted_event
+ finally:
+ if session and not request.session_id:
+ await session_service.delete_session(
+ app_name=self._app_name(),
+ user_id=request.user_id,
+ session_id=session.id,
+ )
+ # Avoid telemetry data loss having to do with CPU throttling on instance turndown
+ _ = await _force_flush_otel(
+ tracing_enabled=self._tracing_enabled(),
+ logging_enabled=bool(self._telemetry_enabled()),
+ )
+
+ async def async_get_session(
+ self,
+ *,
+ user_id: str,
+ session_id: str,
+ **kwargs,
+ ):
+ """Get a session for the given user.
+
+ Args:
+ user_id (str):
+ Required. The ID of the user.
+ session_id (str):
+ Required. The ID of the session.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ session service.
+
+ Returns:
+ Session: The session instance (if any). It returns None if the
+ session is not found.
+
+ Raises:
+ RuntimeError: If the session is not found.
+ """
+ if not self._tmpl_attrs.get("session_service"):
+ self.set_up()
+ session = await self._tmpl_attrs.get("session_service").get_session(
+ app_name=self._app_name(),
+ user_id=user_id,
+ session_id=session_id,
+ **kwargs,
+ )
+ if not session:
+ raise RuntimeError(
+ "Session not found. Please create it using .create_session()"
+ )
+ return session
+
+ def get_session(
+ self,
+ *,
+ user_id: str,
+ session_id: str,
+ **kwargs,
+ ):
+ """Deprecated. Use async_get_session instead.
+
+ Get a session for the given user.
+ """
+ warnings.warn(
+ (
+ "AdkApp.get_session(...) is deprecated. "
+ "Use AdkApp.async_get_session(...) instead. See "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/use/adk#get-session "
+ "for more details."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ event_queue = queue.Queue(maxsize=1)
+
+ async def _invoke_async_get_session():
+ return await self.async_get_session(
+ user_id=user_id, session_id=session_id, **kwargs
+ )
+
+ def _asyncio_thread_main():
+ try:
+ result = asyncio.run(_invoke_async_get_session())
+ event_queue.put(result)
+ except Exception as e:
+ event_queue.put(e)
+
+ thread = threading.Thread(target=_asyncio_thread_main)
+ thread.start()
+
+ # Wait for the thread to finish
+ thread.join()
+ try:
+ outcome = event_queue.get(timeout=10)
+ except queue.Empty:
+ raise RuntimeError(
+ "Session not found. Please create it using .create_session()"
+ ) from None
+ if isinstance(outcome, RuntimeError):
+ raise outcome from None
+ return outcome
+
+ async def async_list_sessions(self, *, user_id: str, **kwargs):
+ """List sessions for the given user.
+
+ Args:
+ user_id (str):
+ Required. The ID of the user.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ session service.
+
+ Returns:
+ ListSessionsResponse: The list of sessions.
+ """
+ if not self._tmpl_attrs.get("session_service"):
+ self.set_up()
+ return await self._tmpl_attrs.get("session_service").list_sessions(
+ app_name=self._app_name(),
+ user_id=user_id,
+ **kwargs,
+ )
+
+ def list_sessions(self, *, user_id: str, **kwargs):
+ """Deprecated. Use async_list_sessions instead.
+
+ List sessions for the given user.
+ """
+ warnings.warn(
+ (
+ "AdkApp.list_sessions(...) is deprecated. "
+ "Use AdkApp.async_list_sessions(...) instead. See "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/use/adk#list-sessions "
+ "for more details."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ event_queue = queue.Queue()
+
+ async def _invoke_async_list_sessions():
+ try:
+ response = await self.async_list_sessions(user_id=user_id, **kwargs)
+ event_queue.put(response)
+ except RuntimeError as e:
+ event_queue.put(e)
+
+ def _asyncio_thread_main():
+ try:
+ asyncio.run(_invoke_async_list_sessions())
+ finally:
+ event_queue.put(None)
+
+ thread = threading.Thread(target=_asyncio_thread_main)
+ thread.start()
+ # Wait for the thread to finish
+ thread.join()
+ try:
+ return event_queue.get(timeout=10)
+ except queue.Empty:
+ raise RuntimeError("Failed to list sessions.") from None
+
+ async def async_create_session(
+ self,
+ *,
+ user_id: str,
+ session_id: Optional[str] = None,
+ state: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """Creates a new session.
+
+ Args:
+ user_id (str):
+ Required. The ID of the user.
+ session_id (str):
+ Optional. The ID of the session. If not provided, an ID
+ will be be generated for the session.
+ state (dict[str, Any]):
+ Optional. The initial state of the session.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ session service.
+
+ Returns:
+ Session: The newly created session instance.
+ """
+ if not self._tmpl_attrs.get("session_service"):
+ self.set_up()
+ session = await self._tmpl_attrs.get("session_service").create_session(
+ app_name=self._app_name(),
+ user_id=user_id,
+ session_id=session_id,
+ state=state,
+ **kwargs,
+ )
+ return self._serialize(session)
+
+ def create_session(
+ self,
+ *,
+ user_id: str,
+ session_id: Optional[str] = None,
+ state: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """Deprecated. Use async_create_session instead.
+
+ Creates a new session.
+ """
+ warnings.warn(
+ (
+ "AdkApp.create_session(...) is deprecated. "
+ "Use AdkApp.async_create_session(...) instead. See "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/use/adk#create-session "
+ "for more details."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ event_queue = queue.Queue(maxsize=1)
+
+ async def _invoke_async_create_session():
+ return await self.async_create_session(
+ user_id=user_id,
+ session_id=session_id,
+ state=state,
+ **kwargs,
+ )
+
+ def _asyncio_thread_main():
+ try:
+ result = asyncio.run(_invoke_async_create_session())
+ event_queue.put(result)
+ except RuntimeError as e:
+ event_queue.put(e)
+
+ thread = threading.Thread(target=_asyncio_thread_main)
+ thread.start()
+ # Wait for the thread to finish
+ thread.join()
+
+ try:
+ outcome = event_queue.get(timeout=10)
+ except queue.Empty:
+ raise RuntimeError("Failed to create session.") from None
+ if isinstance(outcome, RuntimeError):
+ raise outcome from None
+ return outcome
+
+ async def async_delete_session(
+ self,
+ *,
+ user_id: str,
+ session_id: str,
+ **kwargs,
+ ):
+ """Deletes a session for the given user.
+
+ Args:
+ user_id (str):
+ Required. The ID of the user.
+ session_id (str):
+ Required. The ID of the session.
+ **kwargs (dict[str, Any]):
+ Optional. Additional keyword arguments to pass to the
+ session service.
+ """
+ if not self._tmpl_attrs.get("session_service"):
+ self.set_up()
+ await self._tmpl_attrs.get("session_service").delete_session(
+ app_name=self._app_name(),
+ user_id=user_id,
+ session_id=session_id,
+ **kwargs,
+ )
+
+ def delete_session(
+ self,
+ *,
+ user_id: str,
+ session_id: str,
+ **kwargs,
+ ):
+ """Deprecated. Use async_delete_session instead.
+
+ Deletes a session for the given user.
+ """
+ warnings.warn(
+ (
+ "AdkApp.delete_session(...) is deprecated. "
+ "Use AdkApp.async_delete_session(...) instead. See "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/use/adk#delete-session "
+ "for more details."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ event_queue = queue.Queue(maxsize=1)
+
+ async def _invoke_async_delete_session():
+ await self.async_delete_session(
+ user_id=user_id, session_id=session_id, **kwargs
+ )
+
+ def _asyncio_thread_main():
+ try:
+ asyncio.run(_invoke_async_delete_session())
+ event_queue.put(None)
+ except RuntimeError as e:
+ event_queue.put(e)
+
+ thread = threading.Thread(target=_asyncio_thread_main)
+ thread.start()
+ # Wait for the thread to finish
+ thread.join()
+
+ outcome = event_queue.get(timeout=10)
+ if isinstance(outcome, RuntimeError):
+ raise outcome from None
+
+ async def async_add_session_to_memory(self, *, session: Dict[str, Any]):
+ """Generates memories.
+
+ Args:
+ session (Dict[str, Any]):
+ Required. The session to use for generating memories. It should
+ be a dictionary representing an ADK Session object, e.g.
+ session.model_dump(mode="json").
+ """
+ from google.adk.sessions.session import Session
+
+ if isinstance(session, Dict):
+ session = Session.model_validate(session)
+ elif not isinstance(session, Session):
+ raise TypeError("session must be a Session object.")
+ if not session.events:
+ # Get the latest version of the session in case it was updated.
+ session = await self.async_get_session(
+ user_id=session.user_id,
+ session_id=session.id,
+ )
+ if not self._tmpl_attrs.get("memory_service"):
+ self.set_up()
+ return await self._tmpl_attrs.get("memory_service").add_session_to_memory(
+ session=session,
+ )
+
+ async def async_search_memory(self, *, user_id: str, query: str):
+ """Searches memories for the given user.
+
+ Args:
+ user_id: The id of the user.
+ query: The query to match the memories on.
+
+ Returns:
+ A SearchMemoryResponse containing the matching memories.
+ """
+ if not self._tmpl_attrs.get("memory_service"):
+ self.set_up()
+ return await self._tmpl_attrs.get("memory_service").search_memory(
+ app_name=self._app_name(),
+ user_id=user_id,
+ query=query,
+ )
+
+ def register_operations(self) -> Dict[str, List[str]]:
+ """Registers the operations of the ADK application."""
+ return {
+ "": [
+ "get_session",
+ "list_sessions",
+ "create_session",
+ "delete_session",
+ ],
+ "async": [
+ "async_get_session",
+ "async_list_sessions",
+ "async_create_session",
+ "async_delete_session",
+ "async_add_session_to_memory",
+ "async_search_memory",
+ ],
+ "stream": ["stream_query"],
+ "async_stream": [
+ "async_stream_query",
+ "streaming_agent_run_with_events",
+ ],
+ }
+
+ def _telemetry_enabled(self) -> Optional[bool]:
+ """Return status of telemetry enablement depending on enablement env variable.
+
+ In detail:
+ - Logging is always enabled when telemetry is enabled.
+ - Tracing is enabled depending on the truth table seen in `_tracing_enabled` method, in order to not break existing user enablement.
+
+ Returns:
+ True if telemetry is enabled, False if telemetry is disabled, or None
+ if telemetry enablement is not set (i.e. old deployments which don't support this env variable).
+ """
+ import os
+
+ GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY = (
+ "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
+ )
+
+ env_value = os.getenv(
+ GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY, "unspecified"
+ ).lower()
+
+ if env_value in ("true", "1"):
+ return True
+ if env_value in ("false", "0"):
+ return False
+ return None
+
+ # Tracing enablement follows truth table:
+ def _tracing_enabled(self) -> bool:
+ """Tracing enablement follows true table:
+
+ | enable_tracing | enable_telemetry(env) | tracing_actually_enabled |
+ |----------------|-----------------------|--------------------------|
+ | false | false | false |
+ | false | true | false |
+ | false | None | false |
+ | true | false | false |
+ | true | true | true |
+ | true | None | true |
+ | None(default) | false | false |
+ | None(default) | true | adk_version >= 1.17 |
+ | None(default) | None | false |
+ """
+ enable_tracing: Optional[bool] = self._tmpl_attrs.get("enable_tracing")
+ enable_telemetry: Optional[bool] = self._telemetry_enabled()
+
+ return (enable_tracing is True and enable_telemetry is not False) or (
+ enable_tracing is None
+ and enable_telemetry is True
+ and is_version_sufficient("1.17.0")
+ )
+
+ def project_id(self) -> Optional[str]:
+ if project := self._tmpl_attrs.get("project"):
+ try:
+ from google.cloud.aiplatform.utils import (
+ resource_manager_utils,
+ )
+ from google.api_core import exceptions
+
+ return resource_manager_utils.get_project_id(project)
+ # Fail open as temporary workaround for identity_type config parameter
+ except (exceptions.PermissionDenied, exceptions.Unauthenticated):
+ return project
+
+ return None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/ag2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/ag2.py
new file mode 100644
index 0000000000000000000000000000000000000000..84982ecd4c4874e96a051420d02a884f4d077c47
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/ag2.py
@@ -0,0 +1,489 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Mapping,
+ Optional,
+ Sequence,
+ Union,
+)
+
+if TYPE_CHECKING:
+ try:
+ from autogen import agentchat
+
+ ConversableAgent = agentchat.ConversableAgent
+ ChatResult = agentchat.ChatResult
+ except ImportError:
+ ConversableAgent = Any
+
+ try:
+ from opentelemetry.sdk import trace
+
+ TracerProvider = trace.TracerProvider
+ SpanProcessor = trace.SpanProcessor
+ SynchronousMultiSpanProcessor = trace.SynchronousMultiSpanProcessor
+ except ImportError:
+ TracerProvider = Any
+ SpanProcessor = Any
+ SynchronousMultiSpanProcessor = Any
+
+
+def _prepare_runnable_kwargs(
+ runnable_kwargs: Mapping[str, Any],
+ system_instruction: str,
+ runnable_name: str,
+ llm_config: Mapping[str, Any],
+) -> Mapping[str, Any]:
+ """Prepares the configuration for a runnable, applying defaults and enforcing constraints."""
+ if runnable_kwargs is None:
+ runnable_kwargs = {}
+
+ if (
+ "human_input_mode" in runnable_kwargs
+ and runnable_kwargs["human_input_mode"] != "NEVER"
+ ):
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.warning(
+ f"human_input_mode={runnable_kwargs['human_input_mode']}"
+ "is not supported. Will be enforced to 'NEVER'."
+ )
+ runnable_kwargs["human_input_mode"] = "NEVER"
+
+ if "system_message" not in runnable_kwargs and system_instruction:
+ runnable_kwargs["system_message"] = system_instruction
+
+ if "name" not in runnable_kwargs:
+ runnable_kwargs["name"] = runnable_name
+
+ if "llm_config" not in runnable_kwargs:
+ runnable_kwargs["llm_config"] = llm_config
+
+ return runnable_kwargs
+
+
+def _default_runnable_builder(
+ **runnable_kwargs: Any,
+) -> "ConversableAgent":
+ from autogen import agentchat
+
+ return agentchat.ConversableAgent(**runnable_kwargs)
+
+
+def _default_instrumentor_builder(project_id: str):
+ from agentplatform.agent_engines import _utils
+
+ cloud_trace_exporter = _utils._import_cloud_trace_exporter_or_warn()
+ cloud_trace_v2 = _utils._import_cloud_trace_v2_or_warn()
+ openinference_autogen = _utils._import_openinference_autogen_or_warn()
+ opentelemetry = _utils._import_opentelemetry_or_warn()
+ opentelemetry_sdk_trace = _utils._import_opentelemetry_sdk_trace_or_warn()
+ if all(
+ (
+ cloud_trace_exporter,
+ cloud_trace_v2,
+ openinference_autogen,
+ opentelemetry,
+ opentelemetry_sdk_trace,
+ )
+ ):
+ import google.auth
+
+ credentials, _ = google.auth.default()
+ span_exporter = cloud_trace_exporter.CloudTraceSpanExporter(
+ project_id=project_id,
+ client=cloud_trace_v2.TraceServiceClient(
+ credentials=credentials.with_quota_project(project_id),
+ ),
+ )
+ span_processor: SpanProcessor = (
+ opentelemetry_sdk_trace.export.SimpleSpanProcessor(
+ span_exporter=span_exporter,
+ )
+ )
+ tracer_provider: TracerProvider = opentelemetry.trace.get_tracer_provider()
+ # Get the appropriate tracer provider:
+ # 1. If _TRACER_PROVIDER is already set, use that.
+ # 2. Otherwise, if the OTEL_PYTHON_TRACER_PROVIDER environment
+ # variable is set, use that.
+ # 3. As a final fallback, use _PROXY_TRACER_PROVIDER.
+ # If none of the above is set, we log a warning, and
+ # create a tracer provider.
+ if not tracer_provider:
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.warning(
+ "No tracer provider. By default, "
+ "we should get one of the following providers: "
+ "OTEL_PYTHON_TRACER_PROVIDER, _TRACER_PROVIDER, "
+ "or _PROXY_TRACER_PROVIDER."
+ )
+ tracer_provider = opentelemetry_sdk_trace.TracerProvider()
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids AttributeError:
+ # 'ProxyTracerProvider' and 'NoOpTracerProvider' objects has no
+ # attribute 'add_span_processor'.
+ if _utils.is_noop_or_proxy_tracer_provider(tracer_provider):
+ tracer_provider = opentelemetry_sdk_trace.TracerProvider()
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids OpenTelemetry client already exists error.
+ _override_active_span_processor(
+ tracer_provider,
+ opentelemetry_sdk_trace.SynchronousMultiSpanProcessor(),
+ )
+ tracer_provider.add_span_processor(span_processor)
+ # Keep the instrumentation up-to-date.
+ # When creating multiple AG2Agents,
+ # we need to keep the instrumentation up-to-date.
+ # We deliberately override the instrument each time,
+ # so that if different agents end up using different
+ # instrumentations, we guarantee that the user is always
+ # working with the most recent agent's instrumentation.
+ instrumentor = openinference_autogen.AutogenInstrumentor()
+ instrumentor.uninstrument()
+ instrumentor.instrument()
+ return instrumentor
+ else:
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.warning(
+ "enable_tracing=True but proceeding with tracing disabled "
+ "because not all packages for tracing have been installed"
+ )
+ return None
+
+
+def _validate_callable_parameters_are_annotated(callable: Callable):
+ """Validates that the parameters of the callable have type annotations.
+
+ This ensures that they can be used for constructing AG2 tools that are
+ usable with Gemini function calling.
+ """
+ import inspect
+
+ parameters = dict(inspect.signature(callable).parameters)
+ for name, parameter in parameters.items():
+ if parameter.annotation == inspect.Parameter.empty:
+ raise TypeError(
+ f"Callable={callable.__name__} has untyped input_arg={name}. "
+ f"Please specify a type when defining it, e.g. `{name}: str`."
+ )
+
+
+def _validate_tools(tools: Sequence[Callable[..., Any]]):
+ """Validates that the tools are usable for tool calling."""
+ for tool in tools:
+ if isinstance(tool, Callable):
+ _validate_callable_parameters_are_annotated(tool)
+
+
+def _override_active_span_processor(
+ tracer_provider: "TracerProvider",
+ active_span_processor: "SynchronousMultiSpanProcessor",
+):
+ """Overrides the active span processor.
+
+ When working with multiple AG2Agents in the same environment,
+ it's crucial to manage trace exports carefully.
+ Each agent needs its own span processor tied to a unique project ID.
+ While we add a new span processor for each agent, this can lead to
+ unexpected behavior.
+ For instance, with two agents linked to different projects, traces from the
+ second agent might be sent to both projects.
+ To prevent this and guarantee traces go to the correct project, we overwrite
+ the active span processor whenever a new AG2Agent is created.
+
+ Args:
+ tracer_provider (TracerProvider):
+ The tracer provider to use for the project.
+ active_span_processor (SynchronousMultiSpanProcessor):
+ The active span processor overrides the tracer provider's
+ active span processor.
+ """
+ if tracer_provider._active_span_processor:
+ tracer_provider._active_span_processor.shutdown()
+ tracer_provider._active_span_processor = active_span_processor
+
+
+class AG2Agent:
+ """An AG2 Agent."""
+
+ agent_framework = "ag2"
+
+ def __init__(
+ self,
+ model: str,
+ runnable_name: str,
+ *,
+ api_type: Optional[str] = None,
+ llm_config: Optional[Mapping[str, Any]] = None,
+ system_instruction: Optional[str] = None,
+ runnable_kwargs: Optional[Mapping[str, Any]] = None,
+ runnable_builder: Optional[Callable[..., "ConversableAgent"]] = None,
+ tools: Optional[Sequence[Callable[..., Any]]] = None,
+ enable_tracing: bool = False,
+ instrumentor_builder: Optional[Callable[..., Any]] = None,
+ ):
+ """Initializes the AG2 Agent.
+
+ Under-the-hood, assuming .set_up() is called, this will correspond to
+ ```python
+ # runnable_builder
+ runnable = runnable_builder(
+ llm_config=llm_config,
+ system_message=system_instruction,
+ **runnable_kwargs,
+ )
+ ```
+
+ When everything is based on their default values, this corresponds to
+ ```python
+ # llm_config
+ llm_config = {
+ "config_list": [{
+ "project_id": initializer.global_config.project,
+ "location": initializer.global_config.location,
+ "model": "gemini-1.0-pro-001",
+ "api_type": "google",
+ }]
+ }
+
+ # runnable_builder
+ runnable = ConversableAgent(
+ llm_config=llm_config,
+ name="Default AG2 Agent"
+ system_message="You are a helpful AI Assistant.",
+ human_input_mode="NEVER",
+ )
+ ```
+
+ By default, if `llm_config` is not specified, a default configuration
+ will be created using the provided `model` and `api_type`.
+
+ If `runnable_builder` is not specified, a default runnable builder will
+ be used, configured with the `system_instruction`, `runnable_name` and
+ `runnable_kwargs`.
+
+ Args:
+ model (str):
+ Required. The name of the model (e.g. "gemini-1.0-pro").
+ Used to create a default `llm_config` if one is not provided.
+ This parameter is ignored if `llm_config` is provided.
+ runnable_name (str):
+ Required. The name of the runnable.
+ This name is used as the default `runnable_kwargs["name"]`
+ unless `runnable_kwargs` already contains a "name", in which
+ case the provided `runnable_kwargs["name"]` will be used.
+ api_type (str):
+ Optional. The API type to use for the language model.
+ Used to create a default `llm_config` if one is not provided.
+ This parameter is ignored if `llm_config` is provided.
+ llm_config (Mapping[str, Any]):
+ Optional. Configuration dictionary for the language model.
+ If provided, this configuration will be used directly.
+ Otherwise, a default `llm_config` will be created using `model`
+ and `api_type`. This `llm_config` is used as the default
+ `runnable_kwargs["llm_config"]` unless `runnable_kwargs` already
+ contains a "llm_config", in which case the provided
+ `runnable_kwargs["llm_config"]` will be used.
+ system_instruction (str):
+ Optional. The system instruction for the agent.
+ This instruction is used as the default
+ `runnable_kwargs["system_message"]` unless `runnable_kwargs`
+ already contains a "system_message", in which case the provided
+ `runnable_kwargs["system_message"]` will be used.
+ runnable_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ the runnable. Details of the kwargs can be found in
+ https://docs.ag2.ai/docs/api-reference/autogen/ConversableAgent.
+ `runnable_kwargs` only supports `human_input_mode="NEVER"`.
+ Other `human_input_mode` values will trigger a warning.
+ runnable_builder (Callable[..., "ConversableAgent"]):
+ Optional. Callable that returns a new runnable. This can be used
+ for customizing the orchestration logic of the Agent.
+ If not provided, a default runnable builder will be used.
+ tools (Sequence[Callable[..., Any]]):
+ Optional. The tools for the agent to be able to use. All input
+ callables (e.g. function or class method) will be converted
+ to a AG2 tool . Defaults to None.
+ enable_tracing (bool):
+ Optional. Whether to enable tracing in Cloud Trace. Defaults to
+ False.
+ instrumentor_builder (Callable[..., Any]):
+ Optional. Callable that returns a new instrumentor. This can be
+ used for customizing the instrumentation logic of the Agent.
+ If not provided, a default instrumentor builder will be used.
+ This parameter is ignored if `enable_tracing` is False.
+ """
+ from google.cloud.aiplatform import initializer
+
+ self._tmpl_attrs: dict[str, Any] = {
+ "project": initializer.global_config.project,
+ "location": initializer.global_config.location,
+ "model_name": model,
+ "api_type": api_type or "google",
+ "system_instruction": system_instruction,
+ "runnable_name": runnable_name,
+ "tools": [],
+ "ag2_tool_objects": [],
+ "runnable": None,
+ "runnable_builder": runnable_builder,
+ "instrumentor": None,
+ "instrumentor_builder": instrumentor_builder,
+ "enable_tracing": enable_tracing,
+ }
+ self._tmpl_attrs["llm_config"] = llm_config or {
+ "config_list": [
+ {
+ "project_id": self._tmpl_attrs.get("project"),
+ "location": self._tmpl_attrs.get("location"),
+ "model": self._tmpl_attrs.get("model_name"),
+ "api_type": self._tmpl_attrs.get("api_type"),
+ }
+ ]
+ }
+ self._tmpl_attrs["runnable_kwargs"] = _prepare_runnable_kwargs(
+ runnable_kwargs=runnable_kwargs,
+ llm_config=self._tmpl_attrs.get("llm_config"),
+ system_instruction=self._tmpl_attrs.get("system_instruction"),
+ runnable_name=self._tmpl_attrs.get("runnable_name"),
+ )
+ if tools:
+ # We validate tools at initialization for actionable feedback before
+ # they are deployed.
+ _validate_tools(tools)
+ self._tmpl_attrs["tools"] = tools
+
+ def set_up(self):
+ """Sets up the agent for execution of queries at runtime.
+
+ It initializes the runnable, binds the runnable with tools.
+
+ This method should not be called for an object that being passed to
+ the ReasoningEngine service for deployment, as it initializes clients
+ that can not be serialized.
+ """
+ if self._tmpl_attrs.get("enable_tracing"):
+ instrumentor_builder = (
+ self._tmpl_attrs.get("instrumentor_builder")
+ or _default_instrumentor_builder
+ )
+ self._tmpl_attrs["instrumentor"] = instrumentor_builder(
+ project_id=self._tmpl_attrs.get("project")
+ )
+
+ # Set up tools.
+ tools = self._tmpl_attrs.get("tools")
+ ag2_tool_objects = self._tmpl_attrs.get("ag2_tool_objects")
+ if tools and not ag2_tool_objects:
+ from agentplatform.agent_engines import _utils
+
+ autogen_tools = _utils._import_autogen_tools_or_warn()
+ if autogen_tools:
+ for tool in tools:
+ ag2_tool_objects.append(autogen_tools.Tool(func_or_tool=tool))
+
+ # Set up runnable.
+ runnable_builder = (
+ self._tmpl_attrs.get("runnable_builder") or _default_runnable_builder
+ )
+ self._tmpl_attrs["runnable"] = runnable_builder(
+ **self._tmpl_attrs.get("runnable_kwargs")
+ )
+
+ def clone(self) -> "AG2Agent":
+ """Returns a clone of the AG2Agent."""
+ import copy
+
+ return AG2Agent(
+ model=self._tmpl_attrs.get("model_name"),
+ api_type=self._tmpl_attrs.get("api_type"),
+ llm_config=copy.deepcopy(self._tmpl_attrs.get("llm_config")),
+ system_instruction=self._tmpl_attrs.get("system_instruction"),
+ runnable_name=self._tmpl_attrs.get("runnable_name"),
+ tools=copy.deepcopy(self._tmpl_attrs.get("tools")),
+ runnable_kwargs=copy.deepcopy(self._tmpl_attrs.get("runnable_kwargs")),
+ runnable_builder=self._tmpl_attrs.get("runnable_builder"),
+ enable_tracing=self._tmpl_attrs.get("enable_tracing"),
+ instrumentor_builder=self._tmpl_attrs.get("instrumentor_builder"),
+ )
+
+ def query(
+ self,
+ *,
+ input: Union[str, Mapping[str, Any]],
+ max_turns: Optional[int] = None,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ """Queries the Agent with the given input.
+
+ Args:
+ input (Union[str, Mapping[str, Any]]):
+ Required. The input to be passed to the Agent.
+ max_turns (int):
+ Optional. The maximum number of turns to run the agent for.
+ If not provided, the agent will run indefinitely.
+ If `max_turns` is a `float`, it will be converted to `int`
+ through rounding.
+ **kwargs:
+ Optional. Any additional keyword arguments to be passed to the
+ `.run()` method of the corresponding runnable.
+ Details of the kwargs can be found in
+ https://docs.ag2.ai/docs/api-reference/autogen/ConversableAgent#run.
+ The `user_input` parameter defaults to `False`, and should not
+ be passed through `kwargs`.
+
+ Returns:
+ The output of querying the Agent with the given input.
+ """
+ if isinstance(input, str):
+ input = {"content": input}
+
+ if max_turns and isinstance(max_turns, float):
+ # Supporting auto-conversion float to int.
+ max_turns = round(max_turns)
+
+ if "user_input" in kwargs:
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.warning(
+ "The `user_input` parameter should not be passed through"
+ "kwargs. The `user_input` defaults to `False`."
+ )
+ kwargs.pop("user_input")
+
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+
+ response = self._tmpl_attrs.get("runnable").run(
+ message=input,
+ user_input=False,
+ tools=self._tmpl_attrs.get("ag2_tool_objects"),
+ max_turns=max_turns,
+ **kwargs,
+ )
+
+ from agentplatform.agent_engines import _utils
+
+ return _utils.to_json_serializable_autogen_object(response)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/langchain.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/langchain.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ee9039a5f810526e397695cf7c5c5706f2e7ee8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/langchain.py
@@ -0,0 +1,713 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ Mapping,
+ Optional,
+ Union,
+)
+
+if TYPE_CHECKING:
+ try:
+ from langchain_core import runnables
+ from langchain_core import tools as lc_tools
+ from langchain_core.language_models import base as lc_language_models
+
+ BaseTool = lc_tools.BaseTool
+ BaseLanguageModel = lc_language_models.BaseLanguageModel
+ GetSessionHistoryCallable = runnables.history.GetSessionHistoryCallable
+ RunnableConfig = runnables.RunnableConfig
+ RunnableSerializable = runnables.RunnableSerializable
+ except ImportError:
+ BaseTool = Any
+ BaseLanguageModel = Any
+ GetSessionHistoryCallable = Any
+ RunnableConfig = Any
+ RunnableSerializable = Any
+
+ try:
+ from langchain_google_genai.functions_utils import _ToolsType
+ except ImportError:
+ try:
+ from langchain_google_vertexai.functions_utils import _ToolsType
+ except ImportError:
+ _ToolsType = Any
+
+ try:
+ from opentelemetry.sdk import trace
+
+ TracerProvider = trace.TracerProvider
+ SpanProcessor = trace.SpanProcessor
+ SynchronousMultiSpanProcessor = trace.SynchronousMultiSpanProcessor
+ except ImportError:
+ TracerProvider = Any
+ SpanProcessor = Any
+ SynchronousMultiSpanProcessor = Any
+
+
+def _default_runnable_kwargs(has_history: bool) -> Mapping[str, Any]:
+ # https://github.com/langchain-ai/langchain/blob/5784dfed001730530637793bea1795d9d5a7c244/libs/core/langchain_core/runnables/history.py#L237-L241
+ runnable_kwargs = {
+ # input_messages_key (str): Must be specified if the underlying
+ # agent accepts a dict as input.
+ "input_messages_key": "input",
+ # output_messages_key (str): Must be specified if the underlying
+ # agent returns a dict as output.
+ "output_messages_key": "output",
+ }
+ if has_history:
+ # history_messages_key (str): Must be specified if the underlying
+ # agent accepts a dict as input and a separate key for historical
+ # messages.
+ runnable_kwargs["history_messages_key"] = "history"
+ return runnable_kwargs
+
+
+def _default_output_parser():
+ try:
+ from langchain_classic.agents.output_parsers.tools import ToolsAgentOutputParser
+ except (ModuleNotFoundError, ImportError):
+ try:
+ from langchain.agents.output_parsers.tools import ToolsAgentOutputParser
+ except (ModuleNotFoundError, ImportError):
+ # Fallback to an older version if needed.
+ from langchain.agents.output_parsers.openai_tools import (
+ OpenAIToolsAgentOutputParser as ToolsAgentOutputParser,
+ )
+ return ToolsAgentOutputParser()
+
+
+def _default_model_builder(
+ model_name: str,
+ *,
+ project: str,
+ location: str,
+ model_kwargs: Optional[Mapping[str, Any]] = None,
+) -> "BaseLanguageModel":
+ model_kwargs = model_kwargs or {}
+ try:
+ from langchain_google_genai import ChatGoogleGenerativeAI
+
+ model = ChatGoogleGenerativeAI(
+ model=model_name,
+ project=project,
+ location=location,
+ vertexai=True,
+ **model_kwargs,
+ )
+ return model
+ except ImportError:
+ import agentplatform
+ from google.cloud.aiplatform import initializer
+ from langchain_google_vertexai import ChatVertexAI
+
+ current_project = initializer.global_config.project
+ current_location = initializer.global_config.location
+ agentplatform.init(project=project, location=location)
+ model = ChatVertexAI(model_name=model_name, **model_kwargs)
+ agentplatform.init(project=current_project, location=current_location)
+ return model
+
+
+def _default_runnable_builder(
+ model: "BaseLanguageModel",
+ *,
+ system_instruction: Optional[str] = None,
+ tools: Optional["_ToolsType"] = None,
+ prompt: Optional["RunnableSerializable"] = None,
+ output_parser: Optional["RunnableSerializable"] = None,
+ chat_history: Optional["GetSessionHistoryCallable"] = None,
+ model_tool_kwargs: Optional[Mapping[str, Any]] = None,
+ agent_executor_kwargs: Optional[Mapping[str, Any]] = None,
+ runnable_kwargs: Optional[Mapping[str, Any]] = None,
+) -> "RunnableSerializable":
+ from langchain_core import tools as lc_tools
+
+ try:
+ from langchain_classic.agents import AgentExecutor
+ except ImportError:
+ from langchain.agents import AgentExecutor
+
+ try:
+ from langchain_core.tools import StructuredTool
+ except ImportError:
+ from langchain.tools.base import StructuredTool
+
+ # The prompt template and runnable_kwargs needs to be customized depending
+ # on whether the user intends for the agent to have history. The way the
+ # user would reflect that is by setting chat_history (which defaults to
+ # None).
+ has_history: bool = chat_history is not None
+ prompt = prompt or _default_prompt(
+ has_history=has_history,
+ system_instruction=system_instruction,
+ )
+ output_parser = output_parser or _default_output_parser()
+ model_tool_kwargs = model_tool_kwargs or {}
+ agent_executor_kwargs = agent_executor_kwargs or {}
+ runnable_kwargs = runnable_kwargs or _default_runnable_kwargs(has_history)
+ if tools:
+ model = model.bind_tools(tools=tools, **model_tool_kwargs)
+ else:
+ tools = []
+ agent_executor = AgentExecutor(
+ agent=prompt | model | output_parser,
+ tools=[
+ (
+ tool
+ if isinstance(tool, lc_tools.BaseTool)
+ else StructuredTool.from_function(tool)
+ )
+ for tool in tools
+ if isinstance(tool, (Callable, lc_tools.BaseTool))
+ ],
+ **agent_executor_kwargs,
+ )
+ if has_history:
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+
+ return RunnableWithMessageHistory(
+ runnable=agent_executor,
+ get_session_history=chat_history,
+ **runnable_kwargs,
+ )
+ return agent_executor
+
+
+def _default_instrumentor_builder(project_id: str):
+ from agentplatform.agent_engines import _utils
+
+ cloud_trace_exporter = _utils._import_cloud_trace_exporter_or_warn()
+ cloud_trace_v2 = _utils._import_cloud_trace_v2_or_warn()
+ openinference_langchain = _utils._import_openinference_langchain_or_warn()
+ opentelemetry = _utils._import_opentelemetry_or_warn()
+ opentelemetry_sdk_trace = _utils._import_opentelemetry_sdk_trace_or_warn()
+ if all(
+ (
+ cloud_trace_exporter,
+ cloud_trace_v2,
+ openinference_langchain,
+ opentelemetry,
+ opentelemetry_sdk_trace,
+ )
+ ):
+ import google.auth
+
+ credentials, _ = google.auth.default()
+ span_exporter = cloud_trace_exporter.CloudTraceSpanExporter(
+ project_id=project_id,
+ client=cloud_trace_v2.TraceServiceClient(
+ credentials=credentials.with_quota_project(project_id),
+ ),
+ )
+ span_processor: SpanProcessor = (
+ opentelemetry_sdk_trace.export.SimpleSpanProcessor(
+ span_exporter=span_exporter,
+ )
+ )
+ tracer_provider: TracerProvider = opentelemetry.trace.get_tracer_provider()
+ # Get the appropriate tracer provider:
+ # 1. If _TRACER_PROVIDER is already set, use that.
+ # 2. Otherwise, if the OTEL_PYTHON_TRACER_PROVIDER environment
+ # variable is set, use that.
+ # 3. As a final fallback, use _PROXY_TRACER_PROVIDER.
+ # If none of the above is set, we log a warning, and
+ # create a tracer provider.
+ if not tracer_provider:
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.warning(
+ "No tracer provider. By default, "
+ "we should get one of the following providers: "
+ "OTEL_PYTHON_TRACER_PROVIDER, _TRACER_PROVIDER, "
+ "or _PROXY_TRACER_PROVIDER."
+ )
+ tracer_provider = opentelemetry_sdk_trace.TracerProvider()
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids AttributeError:
+ # 'ProxyTracerProvider' and 'NoOpTracerProvider' objects has no
+ # attribute 'add_span_processor'.
+ if _utils.is_noop_or_proxy_tracer_provider(tracer_provider):
+ tracer_provider = opentelemetry_sdk_trace.TracerProvider()
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids OpenTelemetry client already exists error.
+ _override_active_span_processor(
+ tracer_provider,
+ opentelemetry_sdk_trace.SynchronousMultiSpanProcessor(),
+ )
+ tracer_provider.add_span_processor(span_processor)
+ # Keep the instrumentation up-to-date.
+ # When creating multiple LangchainAgents,
+ # we need to keep the instrumentation up-to-date.
+ # We deliberately override the instrument each time,
+ # so that if different agents end up using different
+ # instrumentations, we guarantee that the user is always
+ # working with the most recent agent's instrumentation.
+ instrumentor = openinference_langchain.LangChainInstrumentor()
+ if instrumentor.is_instrumented_by_opentelemetry:
+ instrumentor.uninstrument()
+ instrumentor.instrument()
+ return instrumentor
+ else:
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.warning(
+ "enable_tracing=True but proceeding with tracing disabled "
+ "because not all packages for tracing have been installed"
+ )
+ return None
+
+
+def _default_prompt(
+ has_history: bool,
+ system_instruction: Optional[str] = None,
+) -> "RunnableSerializable":
+ from langchain_core import prompts
+
+ try:
+ from langchain_classic.agents.format_scratchpad.tools import (
+ format_to_tool_messages,
+ )
+ except (ModuleNotFoundError, ImportError):
+ try:
+ from langchain.agents.format_scratchpad.tools import format_to_tool_messages
+ except (ModuleNotFoundError, ImportError):
+ from langchain.agents.format_scratchpad.openai_tools import (
+ format_to_openai_tool_messages as format_to_tool_messages,
+ )
+
+ system_instructions = []
+ if system_instruction:
+ system_instructions = [("system", system_instruction)]
+
+ if has_history:
+ return {
+ "history": lambda x: x["history"],
+ "input": lambda x: x["input"],
+ "agent_scratchpad": (
+ lambda x: format_to_tool_messages(x["intermediate_steps"])
+ ),
+ } | prompts.ChatPromptTemplate.from_messages(
+ system_instructions
+ + [
+ prompts.MessagesPlaceholder(variable_name="history"),
+ ("user", "{input}"),
+ prompts.MessagesPlaceholder(variable_name="agent_scratchpad"),
+ ]
+ )
+ else:
+ return {
+ "input": lambda x: x["input"],
+ "agent_scratchpad": (
+ lambda x: format_to_tool_messages(x["intermediate_steps"])
+ ),
+ } | prompts.ChatPromptTemplate.from_messages(
+ system_instructions
+ + [
+ ("user", "{input}"),
+ prompts.MessagesPlaceholder(variable_name="agent_scratchpad"),
+ ]
+ )
+
+
+def _validate_callable_parameters_are_annotated(callable: Callable):
+ """Validates that the parameters of the callable have type annotations.
+
+ This ensures that they can be used for constructing LangChain tools that are
+ usable with Gemini function calling.
+ """
+ import inspect
+
+ parameters = dict(inspect.signature(callable).parameters)
+ for name, parameter in parameters.items():
+ if parameter.annotation == inspect.Parameter.empty:
+ raise TypeError(
+ f"Callable={callable.__name__} has untyped input_arg={name}. "
+ f"Please specify a type when defining it, e.g. `{name}: str`."
+ )
+
+
+def _validate_tools(tools: "_ToolsType"):
+ """Validates that the tools are usable for tool calling."""
+ for tool in tools:
+ if isinstance(tool, Callable):
+ _validate_callable_parameters_are_annotated(tool)
+
+
+def _override_active_span_processor(
+ tracer_provider: "TracerProvider",
+ active_span_processor: "SynchronousMultiSpanProcessor",
+):
+ """Overrides the active span processor.
+
+ When working with multiple LangchainAgents in the same environment,
+ it's crucial to manage trace exports carefully.
+ Each agent needs its own span processor tied to a unique project ID.
+ While we add a new span processor for each agent, this can lead to
+ unexpected behavior.
+ For instance, with two agents linked to different projects, traces from the
+ second agent might be sent to both projects.
+ To prevent this and guarantee traces go to the correct project, we overwrite
+ the active span processor whenever a new LangchainAgent is created.
+
+ Args:
+ tracer_provider (TracerProvider):
+ The tracer provider to use for the project.
+ active_span_processor (SynchronousMultiSpanProcessor):
+ The active span processor overrides the tracer provider's
+ active span processor.
+ """
+ if tracer_provider._active_span_processor:
+ tracer_provider._active_span_processor.shutdown()
+ tracer_provider._active_span_processor = active_span_processor
+
+
+class LangchainAgent:
+ """A Langchain Agent.
+
+ See https://cloud.google.com/vertex-ai/generative-ai/docs/reasoning-engine/develop
+ for details.
+ """
+
+ agent_framework = "langchain"
+
+ def __init__(
+ self,
+ model: str,
+ *,
+ system_instruction: Optional[str] = None,
+ prompt: Optional["RunnableSerializable"] = None,
+ tools: Optional["_ToolsType"] = None,
+ output_parser: Optional["RunnableSerializable"] = None,
+ chat_history: Optional["GetSessionHistoryCallable"] = None,
+ model_kwargs: Optional[Mapping[str, Any]] = None,
+ model_tool_kwargs: Optional[Mapping[str, Any]] = None,
+ agent_executor_kwargs: Optional[Mapping[str, Any]] = None,
+ runnable_kwargs: Optional[Mapping[str, Any]] = None,
+ model_builder: Optional[Callable] = None,
+ runnable_builder: Optional[Callable] = None,
+ enable_tracing: bool = False,
+ instrumentor_builder: Optional[Callable[..., Any]] = None,
+ ):
+ """Initializes the LangchainAgent.
+
+ Under-the-hood, assuming .set_up() is called, this will correspond to
+
+ ```
+ model = model_builder(model_name=model, model_kwargs=model_kwargs)
+ runnable = runnable_builder(
+ prompt=prompt,
+ model=model,
+ tools=tools,
+ output_parser=output_parser,
+ chat_history=chat_history,
+ agent_executor_kwargs=agent_executor_kwargs,
+ runnable_kwargs=runnable_kwargs,
+ )
+ ```
+
+ When everything is based on their default values, this corresponds to
+ ```
+ # model_builder
+ from langchain_google_vertexai import ChatVertexAI
+ llm = ChatVertexAI(model_name=model, **model_kwargs)
+
+ # runnable_builder
+ from langchain import agents
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+ llm_with_tools = llm.bind_tools(tools=tools, **model_tool_kwargs)
+ agent_executor = agents.AgentExecutor(
+ agent=prompt | llm_with_tools | output_parser,
+ tools=tools,
+ **agent_executor_kwargs,
+ )
+ runnable = RunnableWithMessageHistory(
+ runnable=agent_executor,
+ get_session_history=chat_history,
+ **runnable_kwargs,
+ )
+ ```
+
+ Args:
+ model (str):
+ Optional. The name of the model (e.g. "gemini-1.0-pro").
+ system_instruction (str):
+ Optional. The system instruction to use for the agent. This
+ argument should not be specified if `prompt` is specified.
+ prompt (langchain_core.runnables.RunnableSerializable):
+ Optional. The prompt template for the model. Defaults to a
+ ChatPromptTemplate.
+ tools (Sequence[langchain_core.tools.BaseTool, Callable]):
+ Optional. The tools for the agent to be able to use. All input
+ callables (e.g. function or class method) will be converted
+ to a langchain.tools.base.StructuredTool. Defaults to None.
+ output_parser (langchain_core.runnables.RunnableSerializable):
+ Optional. The output parser for the model. Defaults to an
+ output parser that works with Gemini function-calling.
+ chat_history (langchain_core.runnables.history.GetSessionHistoryCallable):
+ Optional. Callable that returns a new BaseChatMessageHistory.
+ Defaults to None, i.e. chat_history is not preserved.
+ model_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ chat_models.ChatVertexAI. An example would be
+ ```
+ {
+ # temperature (float): Sampling temperature, it controls the
+ # degree of randomness in token selection.
+ "temperature": 0.28,
+ # max_output_tokens (int): Token limit determines the
+ # maximum amount of text output from one prompt.
+ "max_output_tokens": 1000,
+ # top_p (float): Tokens are selected from most probable to
+ # least, until the sum of their probabilities equals the
+ # top_p value.
+ "top_p": 0.95,
+ # top_k (int): How the model selects tokens for output, the
+ # next token is selected from among the top_k most probable
+ # tokens.
+ "top_k": 40,
+ }
+ ```
+ model_tool_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments when binding tools to the
+ model using `model.bind_tools()`.
+ agent_executor_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ langchain.agents.AgentExecutor. An example would be
+ ```
+ {
+ # Whether to return the agent's trajectory of intermediate
+ # steps at the end in addition to the final output.
+ "return_intermediate_steps": False,
+ # The maximum number of steps to take before ending the
+ # execution loop.
+ "max_iterations": 15,
+ # The method to use for early stopping if the agent never
+ # returns `AgentFinish`. Either 'force' or 'generate'.
+ "early_stopping_method": "force",
+ # How to handle errors raised by the agent's output parser.
+ # Defaults to `False`, which raises the error.
+ "handle_parsing_errors": False,
+ }
+ ```
+ runnable_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ langchain.runnables.history.RunnableWithMessageHistory if
+ chat_history is specified. If chat_history is None, this will be
+ ignored.
+ model_builder (Callable):
+ Optional. Callable that returns a new language model. Defaults
+ to a a callable that returns ChatVertexAI based on `model`,
+ `model_kwargs` and the parameters in `agentplatform.init`.
+ runnable_builder (Callable):
+ Optional. Callable that returns a new runnable. This can be used
+ for customizing the orchestration logic of the Agent based on
+ the model returned by `model_builder` and the rest of the input
+ arguments.
+ enable_tracing (bool):
+ Optional. Whether to enable tracing in Cloud Trace. Defaults to
+ False.
+ instrumentor_builder (Callable[..., Any]):
+ Optional. Callable that returns a new instrumentor. This can be
+ used for customizing the instrumentation logic of the Agent.
+ If not provided, a default instrumentor builder will be used.
+ This parameter is ignored if `enable_tracing` is False.
+
+ Raises:
+ ValueError: If both `prompt` and `system_instruction` are specified.
+ TypeError: If there is an invalid tool (e.g. function with an input
+ that did not specify its type).
+ """
+ from google.cloud.aiplatform import initializer
+
+ self._tmpl_attrs: dict[str, Any] = {
+ "project": initializer.global_config.project,
+ "location": initializer.global_config.location,
+ "tools": [],
+ "model_name": model,
+ "system_instruction": system_instruction,
+ "prompt": prompt,
+ "output_parser": output_parser,
+ "chat_history": chat_history,
+ "model_kwargs": model_kwargs,
+ "model_tool_kwargs": model_tool_kwargs,
+ "agent_executor_kwargs": agent_executor_kwargs,
+ "runnable_kwargs": runnable_kwargs,
+ "model_builder": model_builder,
+ "runnable_builder": runnable_builder,
+ "enable_tracing": enable_tracing,
+ "model": None,
+ "runnable": None,
+ "instrumentor": None,
+ "instrumentor_builder": instrumentor_builder,
+ }
+ if tools:
+ # We validate tools at initialization for actionable feedback before
+ # they are deployed.
+ _validate_tools(tools)
+ self._tmpl_attrs["tools"] = tools
+ if prompt and system_instruction:
+ raise ValueError(
+ "Only one of `prompt` or `system_instruction` should be specified. "
+ "Consider incorporating the system instruction into the prompt "
+ "rather than passing it separately as an argument."
+ )
+
+ def set_up(self):
+ """Sets up the agent for execution of queries at runtime.
+
+ It initializes the model, binds the model with tools, and connects it
+ with the prompt template and output parser.
+
+ This method should not be called for an object being passed to the
+ service for deployment, as it might initialize clients that can not be
+ serialized.
+ """
+ if self._tmpl_attrs.get("enable_tracing"):
+ instrumentor_builder = (
+ self._tmpl_attrs.get("instrumentor_builder")
+ or _default_instrumentor_builder
+ )
+ self._tmpl_attrs["instrumentor"] = instrumentor_builder(
+ project_id=self._tmpl_attrs.get("project")
+ )
+ model_builder = self._tmpl_attrs.get("model_builder") or _default_model_builder
+ self._tmpl_attrs["model"] = model_builder(
+ model_name=self._tmpl_attrs.get("model_name"),
+ model_kwargs=self._tmpl_attrs.get("model_kwargs"),
+ project=self._tmpl_attrs.get("project"),
+ location=self._tmpl_attrs.get("location"),
+ )
+ runnable_builder = (
+ self._tmpl_attrs.get("runnable_builder") or _default_runnable_builder
+ )
+ self._tmpl_attrs["runnable"] = runnable_builder(
+ prompt=self._tmpl_attrs.get("prompt"),
+ model=self._tmpl_attrs.get("model"),
+ tools=self._tmpl_attrs.get("tools"),
+ system_instruction=self._tmpl_attrs.get("system_instruction"),
+ output_parser=self._tmpl_attrs.get("output_parser"),
+ chat_history=self._tmpl_attrs.get("chat_history"),
+ model_tool_kwargs=self._tmpl_attrs.get("model_tool_kwargs"),
+ agent_executor_kwargs=self._tmpl_attrs.get("agent_executor_kwargs"),
+ runnable_kwargs=self._tmpl_attrs.get("runnable_kwargs"),
+ )
+
+ def clone(self) -> "LangchainAgent":
+ """Returns a clone of the LangchainAgent."""
+ import copy
+
+ return LangchainAgent(
+ model=self._tmpl_attrs.get("model_name"),
+ system_instruction=self._tmpl_attrs.get("system_instruction"),
+ prompt=copy.deepcopy(self._tmpl_attrs.get("prompt")),
+ tools=copy.deepcopy(self._tmpl_attrs.get("tools")),
+ output_parser=copy.deepcopy(self._tmpl_attrs.get("output_parser")),
+ chat_history=copy.deepcopy(self._tmpl_attrs.get("chat_history")),
+ model_kwargs=copy.deepcopy(self._tmpl_attrs.get("model_kwargs")),
+ model_tool_kwargs=copy.deepcopy(self._tmpl_attrs.get("model_tool_kwargs")),
+ agent_executor_kwargs=copy.deepcopy(
+ self._tmpl_attrs.get("agent_executor_kwargs")
+ ),
+ runnable_kwargs=copy.deepcopy(self._tmpl_attrs.get("runnable_kwargs")),
+ model_builder=self._tmpl_attrs.get("model_builder"),
+ runnable_builder=self._tmpl_attrs.get("runnable_builder"),
+ enable_tracing=self._tmpl_attrs.get("enable_tracing"),
+ instrumentor_builder=self._tmpl_attrs.get("instrumentor_builder"),
+ )
+
+ def query(
+ self,
+ *,
+ input: Union[str, Mapping[str, Any]],
+ config: Optional["RunnableConfig"] = None,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ """Queries the Agent with the given input and config.
+
+ Args:
+ input (Union[str, Mapping[str, Any]]):
+ Required. The input to be passed to the Agent.
+ config (langchain_core.runnables.RunnableConfig):
+ Optional. The config (if any) to be used for invoking the Agent.
+ **kwargs:
+ Optional. Any additional keyword arguments to be passed to the
+ `.invoke()` method of the corresponding AgentExecutor.
+
+ Returns:
+ The output of querying the Agent with the given input and config.
+ """
+ try:
+ from langchain_core.load import dumpd
+ except ImportError:
+ from langchain.load import dump as langchain_load_dump
+
+ dumpd = langchain_load_dump.dumpd
+
+ if isinstance(input, str):
+ input = {"input": input}
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+ return dumpd(
+ self._tmpl_attrs.get("runnable").invoke(
+ input=input, config=config, **kwargs
+ )
+ )
+
+ def stream_query(
+ self,
+ *,
+ input: Union[str, Mapping[str, Any]],
+ config: Optional["RunnableConfig"] = None,
+ **kwargs,
+ ) -> Iterable[Any]:
+ """Stream queries the Agent with the given input and config.
+
+ Args:
+ input (Union[str, Mapping[str, Any]]):
+ Required. The input to be passed to the Agent.
+ config (langchain_core.runnables.RunnableConfig):
+ Optional. The config (if any) to be used for invoking the Agent.
+ **kwargs:
+ Optional. Any additional keyword arguments to be passed to the
+ `.invoke()` method of the corresponding AgentExecutor.
+
+ Yields:
+ The output of querying the Agent with the given input and config.
+ """
+ try:
+ from langchain_core.load import dumpd
+ except ImportError:
+ from langchain.load import dump as langchain_load_dump
+
+ dumpd = langchain_load_dump.dumpd
+
+ if isinstance(input, str):
+ input = {"input": input}
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+ for chunk in self._tmpl_attrs.get("runnable").stream(
+ input=input,
+ config=config,
+ **kwargs,
+ ):
+ yield dumpd(chunk)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/langgraph.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/langgraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdfb417a8ea354cd59ee33a8c94a33f5013952ba
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/agent_engines/templates/langgraph.py
@@ -0,0 +1,709 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ Mapping,
+ Optional,
+ Sequence,
+ Union,
+)
+
+if TYPE_CHECKING:
+ try:
+ from langchain_core.language_models import base as lc_language_models
+
+ BaseLanguageModel = lc_language_models.BaseLanguageModel
+ except ImportError:
+ BaseLanguageModel = Any
+
+ try:
+ from langchain_google_genai.functions_utils import _ToolsType
+
+ _ToolLike = _ToolsType
+ except ImportError:
+ try:
+ from langchain_google_vertexai.functions_utils import _ToolsType
+
+ _ToolLike = _ToolsType
+ except ImportError:
+ _ToolLike = Any
+
+ try:
+ from opentelemetry.sdk import trace
+
+ TracerProvider = trace.TracerProvider
+ SpanProcessor = trace.SpanProcessor
+ SynchronousMultiSpanProcessor = trace.SynchronousMultiSpanProcessor
+ except ImportError:
+ TracerProvider = Any
+ SpanProcessor = Any
+ SynchronousMultiSpanProcessor = Any
+
+ try:
+ from langgraph_checkpoint.checkpoint import base
+
+ BaseCheckpointSaver = base.BaseCheckpointSaver
+ except ImportError:
+ try:
+ from langgraph.checkpoint import base
+
+ BaseCheckpointSaver = base.BaseCheckpointSaver
+ except ImportError:
+ BaseCheckpointSaver = Any
+
+
+def _default_model_builder(
+ model_name: str,
+ *,
+ project: str,
+ location: str,
+ model_kwargs: Optional[Mapping[str, Any]] = None,
+) -> "BaseLanguageModel":
+ """Default callable for building a language model.
+
+ Args:
+ model_name (str):
+ Required. The name of the model (e.g. "gemini-1.0-pro").
+ project (str):
+ Required. The Google Cloud project ID.
+ location (str):
+ Required. The Google Cloud location.
+ model_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ chat_models.ChatVertexAI.
+
+ Returns:
+ BaseLanguageModel: The language model.
+ """
+ model_kwargs = model_kwargs or {}
+ try:
+ from langchain_google_genai import ChatGoogleGenerativeAI
+
+ model = ChatGoogleGenerativeAI(
+ model=model_name,
+ project=project,
+ location=location,
+ vertexai=True,
+ **model_kwargs,
+ )
+ return model
+ except ImportError:
+ import agentplatform
+ from google.cloud.aiplatform import initializer
+ from langchain_google_vertexai import ChatVertexAI
+
+ current_project = initializer.global_config.project
+ current_location = initializer.global_config.location
+ agentplatform.init(project=project, location=location)
+ model = ChatVertexAI(model_name=model_name, **model_kwargs)
+ agentplatform.init(project=current_project, location=current_location)
+ return model
+
+
+def _default_runnable_builder(
+ model: "BaseLanguageModel",
+ *,
+ tools: Optional[Sequence["_ToolLike"]] = None,
+ checkpointer: Optional[Any] = None,
+ model_tool_kwargs: Optional[Mapping[str, Any]] = None,
+ runnable_kwargs: Optional[Mapping[str, Any]] = None,
+):
+ """Default callable for building a runnable.
+
+ Args:
+ model (BaseLanguageModel):
+ Required. The language model.
+ tools (Optional[Sequence[_ToolLike]]):
+ Optional. The tools for the agent to be able to use.
+ checkpointer (Optional[Checkpointer]):
+ Optional. The checkpointer for the agent.
+ model_tool_kwargs (Optional[Mapping[str, Any]]):
+ Optional. Additional keyword arguments when binding tools to the model.
+ runnable_kwargs (Optional[Mapping[str, Any]]):
+ Optional. Additional keyword arguments for the runnable.
+
+ Returns:
+ RunnableSerializable: The runnable.
+ """
+ from langgraph import prebuilt as langgraph_prebuilt
+
+ model_tool_kwargs = model_tool_kwargs or {}
+ runnable_kwargs = runnable_kwargs or {}
+ if tools:
+ model = model.bind_tools(tools=tools, **model_tool_kwargs)
+ else:
+ tools = []
+ if checkpointer:
+ if "checkpointer" in runnable_kwargs:
+ from google.cloud.aiplatform import base
+
+ base.Logger(__name__).warning(
+ "checkpointer is being specified in both checkpointer_builder "
+ "and runnable_kwargs. Please specify it in only one of them. "
+ "Overriding the checkpointer in runnable_kwargs."
+ )
+ runnable_kwargs["checkpointer"] = checkpointer
+ return langgraph_prebuilt.create_react_agent(
+ model,
+ tools=tools,
+ **runnable_kwargs,
+ )
+
+
+def _default_instrumentor_builder(project_id: str):
+ from agentplatform.agent_engines import _utils
+
+ cloud_trace_exporter = _utils._import_cloud_trace_exporter_or_warn()
+ cloud_trace_v2 = _utils._import_cloud_trace_v2_or_warn()
+ openinference_langchain = _utils._import_openinference_langchain_or_warn()
+ opentelemetry = _utils._import_opentelemetry_or_warn()
+ opentelemetry_sdk_trace = _utils._import_opentelemetry_sdk_trace_or_warn()
+ if all(
+ (
+ cloud_trace_exporter,
+ cloud_trace_v2,
+ openinference_langchain,
+ opentelemetry,
+ opentelemetry_sdk_trace,
+ )
+ ):
+ import google.auth
+
+ credentials, _ = google.auth.default()
+ span_exporter = cloud_trace_exporter.CloudTraceSpanExporter(
+ project_id=project_id,
+ client=cloud_trace_v2.TraceServiceClient(
+ credentials=credentials.with_quota_project(project_id),
+ ),
+ )
+ span_processor: SpanProcessor = (
+ opentelemetry_sdk_trace.export.SimpleSpanProcessor(
+ span_exporter=span_exporter,
+ )
+ )
+ tracer_provider: TracerProvider = opentelemetry.trace.get_tracer_provider()
+ # Get the appropriate tracer provider:
+ # 1. If _TRACER_PROVIDER is already set, use that.
+ # 2. Otherwise, if the OTEL_PYTHON_TRACER_PROVIDER environment
+ # variable is set, use that.
+ # 3. As a final fallback, use _PROXY_TRACER_PROVIDER.
+ # If none of the above is set, we log a warning, and
+ # create a tracer provider.
+ if not tracer_provider:
+ from google.cloud.aiplatform import base
+
+ base.Logger(__name__).warning(
+ "No tracer provider. By default, "
+ "we should get one of the following providers: "
+ "OTEL_PYTHON_TRACER_PROVIDER, _TRACER_PROVIDER, "
+ "or _PROXY_TRACER_PROVIDER."
+ )
+ tracer_provider = opentelemetry_sdk_trace.TracerProvider()
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids AttributeError:
+ # 'ProxyTracerProvider' and 'NoOpTracerProvider' objects has no
+ # attribute 'add_span_processor'.
+ if _utils.is_noop_or_proxy_tracer_provider(tracer_provider):
+ tracer_provider = opentelemetry_sdk_trace.TracerProvider()
+ opentelemetry.trace.set_tracer_provider(tracer_provider)
+ # Avoids OpenTelemetry client already exists error.
+ _override_active_span_processor(
+ tracer_provider,
+ opentelemetry_sdk_trace.SynchronousMultiSpanProcessor(),
+ )
+ tracer_provider.add_span_processor(span_processor)
+ # Keep the instrumentation up-to-date.
+ # When creating multiple LangchainAgents,
+ # we need to keep the instrumentation up-to-date.
+ # We deliberately override the instrument each time,
+ # so that if different agents end up using different
+ # instrumentations, we guarantee that the user is always
+ # working with the most recent agent's instrumentation.
+ instrumentor = openinference_langchain.LangChainInstrumentor()
+ if instrumentor.is_instrumented_by_opentelemetry:
+ instrumentor.uninstrument()
+ instrumentor.instrument()
+ return instrumentor
+ else:
+ from google.cloud.aiplatform import base
+
+ _LOGGER = base.Logger(__name__)
+ _LOGGER.warning(
+ "enable_tracing=True but proceeding with tracing disabled "
+ "because not all packages for tracing have been installed"
+ )
+ return None
+
+
+def _validate_callable_parameters_are_annotated(callable: Callable):
+ """Validates that the parameters of the callable have type annotations.
+
+ This ensures that they can be used for constructing LangChain tools that are
+ usable with Gemini function calling.
+
+ Args:
+ callable (Callable): The callable to validate.
+
+ Raises:
+ TypeError: If any parameter is not annotated.
+ """
+ import inspect
+
+ parameters = dict(inspect.signature(callable).parameters)
+ for name, parameter in parameters.items():
+ if parameter.annotation == inspect.Parameter.empty:
+ raise TypeError(
+ f"Callable={callable.__name__} has untyped input_arg={name}. "
+ f"Please specify a type when defining it, e.g. `{name}: str`."
+ )
+
+
+def _validate_tools(tools: Sequence["_ToolLike"]):
+ """Validates that the tools are usable for tool calling.
+
+ Args:
+ tools (Sequence[_ToolLike]): The tools to validate.
+
+ Raises:
+ TypeError: If any tool is a callable with untyped parameters.
+ """
+ for tool in tools:
+ if isinstance(tool, Callable):
+ _validate_callable_parameters_are_annotated(tool)
+
+
+def _override_active_span_processor(
+ tracer_provider: "TracerProvider",
+ active_span_processor: "SynchronousMultiSpanProcessor",
+):
+ """Overrides the active span processor.
+
+ When working with multiple LangchainAgents in the same environment,
+ it's crucial to manage trace exports carefully.
+ Each agent needs its own span processor tied to a unique project ID.
+ While we add a new span processor for each agent, this can lead to
+ unexpected behavior.
+ For instance, with two agents linked to different projects, traces from the
+ second agent might be sent to both projects.
+ To prevent this and guarantee traces go to the correct project, we overwrite
+ the active span processor whenever a new LangchainAgent is created.
+
+ Args:
+ tracer_provider (TracerProvider):
+ The tracer provider to use for the project.
+ active_span_processor (SynchronousMultiSpanProcessor):
+ The active span processor overrides the tracer provider's
+ active span processor.
+ """
+ if tracer_provider._active_span_processor:
+ tracer_provider._active_span_processor.shutdown()
+ tracer_provider._active_span_processor = active_span_processor
+
+
+class LanggraphAgent:
+ """A LangGraph Agent."""
+
+ agent_framework = "langgraph"
+
+ def __init__(
+ self,
+ model: str,
+ *,
+ tools: Optional[Sequence["_ToolLike"]] = None,
+ model_kwargs: Optional[Mapping[str, Any]] = None,
+ model_tool_kwargs: Optional[Mapping[str, Any]] = None,
+ model_builder: Optional[Callable[..., "BaseLanguageModel"]] = None,
+ runnable_kwargs: Optional[Mapping[str, Any]] = None,
+ runnable_builder: Optional[Callable[..., Any]] = None,
+ checkpointer_kwargs: Optional[Mapping[str, Any]] = None,
+ checkpointer_builder: Optional[Callable[..., "BaseCheckpointSaver"]] = None,
+ enable_tracing: bool = False,
+ instrumentor_builder: Optional[Callable[..., Any]] = None,
+ ):
+ """Initializes the LangGraph Agent.
+
+ Under-the-hood, assuming .set_up() is called, this will correspond to
+ ```python
+ model = model_builder(model_name=model, model_kwargs=model_kwargs)
+ runnable = runnable_builder(
+ model=model,
+ tools=tools,
+ model_tool_kwargs=model_tool_kwargs,
+ runnable_kwargs=runnable_kwargs,
+ )
+ ```
+
+ When everything is based on their default values, this corresponds to
+ ```python
+ # model_builder
+ from langchain_google_vertexai import ChatVertexAI
+ llm = ChatVertexAI(model_name=model, **model_kwargs)
+
+ # runnable_builder
+ from langgraph.prebuilt import create_react_agent
+ llm_with_tools = llm.bind_tools(tools=tools, **model_tool_kwargs)
+ runnable = create_react_agent(
+ llm_with_tools,
+ tools=tools,
+ **runnable_kwargs,
+ )
+ ```
+
+ By default, no checkpointer is used (i.e. there is no state history). To
+ enable checkpointing, provide a `checkpointer_builder` function that
+ returns a checkpointer instance.
+
+ **Example using Spanner:**
+ ```python
+ def checkpointer_builder(instance_id, database_id, project_id, **kwargs):
+ from langchain_google_spanner import SpannerCheckpointSaver
+
+ checkpointer = SpannerCheckpointSaver(instance_id, database_id, project_id)
+ with checkpointer.cursor() as cur:
+ cur.execute("DROP TABLE IF EXISTS checkpoints")
+ cur.execute("DROP TABLE IF EXISTS checkpoint_writes")
+ checkpointer.setup()
+
+ return checkpointer
+ ```
+
+ **Example using an in-memory checkpointer:**
+ ```python
+ def checkpointer_builder(**kwargs):
+ from langgraph.checkpoint.memory import MemorySaver
+
+ return MemorySaver()
+ ```
+
+ The `checkpointer_builder` function will be called with any keyword
+ arguments passed to the agent's constructor. Ensure your
+ `checkpointer_builder` function accepts `**kwargs` to handle these
+ arguments, even if unused.
+
+ Args:
+ model (str):
+ Optional. The name of the model (e.g. "gemini-1.0-pro").
+ tools (Sequence[langchain_core.tools.BaseTool, Callable]):
+ Optional. The tools for the agent to be able to use. All input
+ callables (e.g. function or class method) will be converted
+ to a langchain.tools.base.StructuredTool. Defaults to None.
+ model_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ chat_models.ChatVertexAI. An example would be
+ ```
+ {
+ # temperature (float): Sampling temperature, it controls the
+ # degree of randomness in token selection.
+ "temperature": 0.28,
+ # max_output_tokens (int): Token limit determines the
+ # maximum amount of text output from one prompt.
+ "max_output_tokens": 1000,
+ # top_p (float): Tokens are selected from most probable to
+ # least, until the sum of their probabilities equals the
+ # top_p value.
+ "top_p": 0.95,
+ # top_k (int): How the model selects tokens for output, the
+ # next token is selected from among the top_k most probable
+ # tokens.
+ "top_k": 40,
+ }
+ ```
+ model_tool_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments when binding tools to the
+ model using `model.bind_tools()`.
+ model_builder (Callable[..., BaseLanguageModel]):
+ Optional. Callable that returns a new language model. Defaults
+ to a a callable that returns ChatVertexAI based on `model`,
+ `model_kwargs` and the parameters in `agentplatform.init`.
+ runnable_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ langchain.runnables.history.RunnableWithMessageHistory if
+ chat_history is specified. If chat_history is None, this will be
+ ignored.
+ runnable_builder (Callable[..., RunnableSerializable]):
+ Optional. Callable that returns a new runnable. This can be used
+ for customizing the orchestration logic of the Agent based on
+ the model returned by `model_builder` and the rest of the input
+ arguments.
+ checkpointer_kwargs (Mapping[str, Any]):
+ Optional. Additional keyword arguments for the constructor of
+ the checkpointer returned by `checkpointer_builder`.
+ checkpointer_builder (Callable[..., "BaseCheckpointSaver"]):
+ Optional. Callable that returns a checkpointer. This can be used
+ for defining the checkpointer of the Agent. Defaults to None.
+ enable_tracing (bool):
+ Optional. Whether to enable tracing in Cloud Trace. Defaults to
+ False.
+ instrumentor_builder (Callable[..., Any]):
+ Optional. Callable that returns a new instrumentor. This can be
+ used for customizing the instrumentation logic of the Agent.
+ If not provided, a default instrumentor builder will be used.
+ This parameter is ignored if `enable_tracing` is False.
+
+ Raises:
+ TypeError: If there is an invalid tool (e.g. function with an input
+ that did not specify its type).
+ """
+ from google.cloud.aiplatform import initializer
+
+ self._tmpl_attrs: dict[str, Any] = {
+ "project": initializer.global_config.project,
+ "location": initializer.global_config.location,
+ "tools": [],
+ "model_name": model,
+ "model_kwargs": model_kwargs,
+ "model_tool_kwargs": model_tool_kwargs,
+ "runnable_kwargs": runnable_kwargs,
+ "checkpointer_kwargs": checkpointer_kwargs,
+ "model": None,
+ "model_builder": model_builder,
+ "runnable": None,
+ "runnable_builder": runnable_builder,
+ "checkpointer": None,
+ "checkpointer_builder": checkpointer_builder,
+ "enable_tracing": enable_tracing,
+ "instrumentor": None,
+ "instrumentor_builder": instrumentor_builder,
+ }
+ if tools:
+ # We validate tools at initialization for actionable feedback before
+ # they are deployed.
+ _validate_tools(tools)
+ self._tmpl_attrs["tools"] = tools
+
+ def set_up(self):
+ """Sets up the agent for execution of queries at runtime.
+
+ It initializes the model, binds the model with tools, and connects it
+ with the prompt template and output parser.
+
+ This method should not be called for an object that being passed to
+ the ReasoningEngine service for deployment, as it initializes clients
+ that can not be serialized.
+ """
+ if self._tmpl_attrs.get("enable_tracing"):
+ instrumentor_builder = (
+ self._tmpl_attrs.get("instrumentor_builder")
+ or _default_instrumentor_builder
+ )
+ self._tmpl_attrs["instrumentor"] = instrumentor_builder(
+ project_id=self._tmpl_attrs.get("project")
+ )
+ model_builder = self._tmpl_attrs.get("model_builder") or _default_model_builder
+ self._tmpl_attrs["model"] = model_builder(
+ model_name=self._tmpl_attrs.get("model_name"),
+ model_kwargs=self._tmpl_attrs.get("model_kwargs"),
+ project=self._tmpl_attrs.get("project"),
+ location=self._tmpl_attrs.get("location"),
+ )
+ checkpointer_builder = self._tmpl_attrs.get("checkpointer_builder")
+ if checkpointer_builder:
+ checkpointer_kwargs = self._tmpl_attrs.get("checkpointer_kwargs") or {}
+ self._tmpl_attrs["checkpointer"] = checkpointer_builder(
+ **checkpointer_kwargs
+ )
+ runnable_builder = (
+ self._tmpl_attrs.get("runnable_builder") or _default_runnable_builder
+ )
+ self._tmpl_attrs["runnable"] = runnable_builder(
+ model=self._tmpl_attrs.get("model"),
+ tools=self._tmpl_attrs.get("tools"),
+ checkpointer=self._tmpl_attrs.get("checkpointer"),
+ model_tool_kwargs=self._tmpl_attrs.get("model_tool_kwargs"),
+ runnable_kwargs=self._tmpl_attrs.get("runnable_kwargs"),
+ )
+
+ def clone(self) -> "LanggraphAgent":
+ """Returns a clone of the LanggraphAgent."""
+ import copy
+
+ return LanggraphAgent(
+ model=self._tmpl_attrs.get("model_name"),
+ tools=copy.deepcopy(self._tmpl_attrs.get("tools")),
+ model_kwargs=copy.deepcopy(self._tmpl_attrs.get("model_kwargs")),
+ model_tool_kwargs=copy.deepcopy(self._tmpl_attrs.get("model_tool_kwargs")),
+ runnable_kwargs=copy.deepcopy(self._tmpl_attrs.get("runnable_kwargs")),
+ checkpointer_kwargs=copy.deepcopy(
+ self._tmpl_attrs.get("checkpointer_kwargs")
+ ),
+ model_builder=self._tmpl_attrs.get("model_builder"),
+ runnable_builder=self._tmpl_attrs.get("runnable_builder"),
+ checkpointer_builder=self._tmpl_attrs.get("checkpointer_builder"),
+ enable_tracing=self._tmpl_attrs.get("enable_tracing"),
+ instrumentor_builder=self._tmpl_attrs.get("instrumentor_builder"),
+ )
+
+ def query(
+ self,
+ *,
+ input: Union[str, Mapping[str, Any]],
+ config: Optional[dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ """Queries the Agent with the given input and config.
+
+ Args:
+ input (Union[str, Mapping[str, Any]]):
+ Required. The input to be passed to the Agent.
+ config (langchain_core.runnables.RunnableConfig):
+ Optional. The config (if any) to be used for invoking the Agent.
+ **kwargs:
+ Optional. Any additional keyword arguments to be passed to the
+ `.invoke()` method of the corresponding AgentExecutor.
+
+ Returns:
+ The output of querying the Agent with the given input and config.
+ """
+ try:
+ from langchain_core.load import dumpd
+ except ImportError:
+ from langchain.load.dump import dumpd
+
+ if isinstance(input, str):
+ input = {"input": input, "messages": [("user", input)]}
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+ return dumpd(
+ self._tmpl_attrs.get("runnable").invoke(
+ input=input, config=config, **kwargs
+ )
+ )
+
+ def stream_query(
+ self,
+ *,
+ input: Union[str, Mapping[str, Any]],
+ config: Optional[dict[str, Any]] = None,
+ **kwargs,
+ ) -> Iterable[Any]:
+ """Stream queries the Agent with the given input and config.
+
+ Args:
+ input (Union[str, Mapping[str, Any]]):
+ Required. The input to be passed to the Agent.
+ config (langchain_core.runnables.RunnableConfig):
+ Optional. The config (if any) to be used for invoking the Agent.
+ **kwargs:
+ Optional. Any additional keyword arguments to be passed to the
+ `.invoke()` method of the corresponding AgentExecutor.
+
+ Yields:
+ The output of querying the Agent with the given input and config.
+ """
+ try:
+ from langchain_core.load import dumpd
+ except ImportError:
+ from langchain.load.dump import dumpd
+
+ if isinstance(input, str):
+ input = {"input": input, "messages": [("user", input)]}
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+ for chunk in self._tmpl_attrs.get("runnable").stream(
+ input=input,
+ config=config,
+ **kwargs,
+ ):
+ yield dumpd(chunk)
+
+ def get_state_history(
+ self,
+ config: Optional[dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Iterable[Any]:
+ """Gets the state history of the Agent.
+
+ Args:
+ config (Optional[RunnableConfig]):
+ Optional. The config for invoking the Agent.
+ **kwargs:
+ Optional. Additional keyword arguments for the `.invoke()` method.
+
+ Yields:
+ Dict[str, Any]: The state history of the Agent.
+ """
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+ for state_snapshot in self._tmpl_attrs.get("runnable").get_state_history(
+ config=config,
+ **kwargs,
+ ):
+ yield state_snapshot._asdict()
+
+ def get_state(
+ self,
+ config: Optional[dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ """Gets the current state of the Agent.
+
+ Args:
+ config (Optional[RunnableConfig]):
+ Optional. The config for invoking the Agent.
+ **kwargs:
+ Optional. Additional keyword arguments for the `.invoke()` method.
+
+ Returns:
+ Dict[str, Any]: The current state of the Agent.
+ """
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+ return (
+ self._tmpl_attrs.get("runnable")
+ .get_state(config=config, **kwargs)
+ ._asdict()
+ )
+
+ def update_state(
+ self,
+ config: Optional[dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ """Updates the state of the Agent.
+
+ Args:
+ config (Optional[RunnableConfig]):
+ Optional. The config for invoking the Agent.
+ **kwargs:
+ Optional. Additional keyword arguments for the `.invoke()` method.
+
+ Returns:
+ Dict[str, Any]: The updated state of the Agent.
+ """
+ if not self._tmpl_attrs.get("runnable"):
+ self.set_up()
+ return self._tmpl_attrs.get("runnable").update_state(config=config, **kwargs)
+
+ def register_operations(self) -> Mapping[str, Sequence[str]]:
+ """Registers the operations of the Agent.
+
+ This mapping defines how different operation modes (e.g., "", "stream")
+ are implemented by specific methods of the Agent. The "default" mode,
+ represented by the empty string ``, is associated with the `query` API,
+ while the "stream" mode is associated with the `stream_query` API.
+
+ Returns:
+ Mapping[str, Sequence[str]]: A mapping of operation modes to a list
+ of method names that implement those operation modes.
+ """
+ return {
+ "": ["query", "get_state", "update_state"],
+ "stream": ["stream_query", "get_state_history"],
+ }
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d2817228b7b7c690b38d474a022435f6775a54c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__init__.py
@@ -0,0 +1,25 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Classes for batch prediction."""
+
+# We just want to re-export certain classes
+# pylint: disable=g-multiple-import,g-importing-member
+from agentplatform.batch_prediction._batch_prediction import (
+ BatchPredictionJob,
+)
+
+__all__ = [
+ "BatchPredictionJob",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbde433b62592f994dd57ea1d434bcdf3ca32389
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__pycache__/_batch_prediction.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__pycache__/_batch_prediction.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a32c89304213fd2a4c699a908129a924846e344c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/__pycache__/_batch_prediction.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/_batch_prediction.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/_batch_prediction.py
new file mode 100644
index 0000000000000000000000000000000000000000..e164b1d999a4d48a4e08058d2ace2fac770d139a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/batch_prediction/_batch_prediction.py
@@ -0,0 +1,428 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Class to support Batch Prediction with GenAI models."""
+# pylint: disable=protected-access
+
+import logging
+import re
+from typing import List, Optional, Union
+
+from google.cloud.aiplatform import base as aiplatform_base
+from google.cloud.aiplatform import initializer as aiplatform_initializer
+from google.cloud.aiplatform import jobs
+from google.cloud.aiplatform import models
+from google.cloud.aiplatform import utils as aiplatform_utils
+from google.cloud.aiplatform_v1 import types as gca_types
+
+from google.rpc import status_pb2
+
+
+_LOGGER = aiplatform_base.Logger(__name__)
+
+_GEMINI_MODEL_PATTERN = r"publishers/google/models/gemini"
+_LLAMA_MODEL_PATTERN = r"publishers/meta/models/llama"
+_CLAUDE_MODEL_PATTERN = r"publishers/anthropic/models/claude"
+_GPT_MODEL_PATTERN = r"publishers/openai/models/gpt"
+_QWEN_MODEL_PATTERN = r"publishers/qwen/models/qwen"
+_DEEPSEEK_MODEL_PATTERN = r"publishers/deepseek-ai/models/deepseek"
+_E5_MODEL_PATTERN = r"publishers/intfloat/models/multilingual"
+_GEMINI_TUNED_MODEL_PATTERN = r"^projects/[0-9]+?/locations/[0-9a-z-]+?/models/[0-9]+?$"
+
+
+class BatchPredictionJob(aiplatform_base._VertexAiResourceNounPlus):
+ """Represents a BatchPredictionJob that runs with GenAI models."""
+
+ _resource_noun = "batchPredictionJobs"
+ _getter_method = "get_batch_prediction_job"
+ _list_method = "list_batch_prediction_jobs"
+ _delete_method = "delete_batch_prediction_job"
+ _job_type = "batch-predictions"
+ _parse_resource_name_method = "parse_batch_prediction_job_path"
+ _format_resource_name_method = "batch_prediction_job_path"
+
+ client_class = aiplatform_utils.JobClientWithOverride
+
+ def __init__(self, batch_prediction_job_name: str):
+ """Retrieves a BatchPredictionJob resource that runs with a GenAI model.
+
+ Args:
+ batch_prediction_job_name (str):
+ Required. A fully-qualified BatchPredictionJob resource name or
+ ID. Example: "projects/.../locations/.../batchPredictionJobs/456"
+ or "456" when project and location are initialized.
+
+ Raises:
+ ValueError: If batch_prediction_job_name represents a BatchPredictionJob
+ resource that runs with another type of model.
+ """
+ super().__init__(resource_name=batch_prediction_job_name)
+ self._gca_resource = self._get_gca_resource(
+ resource_name=batch_prediction_job_name
+ )
+ if not self._is_genai_model(self.model_name):
+ raise ValueError(
+ f"BatchPredictionJob '{batch_prediction_job_name}' "
+ f"runs with the model '{self.model_name}', "
+ "which is not a GenAI model."
+ )
+
+ @property
+ def model_name(self) -> str:
+ """Returns the model name used for this batch prediction job."""
+ return self._gca_resource.model
+
+ @property
+ def state(self) -> gca_types.JobState:
+ """Returns the state of this batch prediction job."""
+ return self._gca_resource.state
+
+ @property
+ def has_ended(self) -> bool:
+ """Returns true if this batch prediction job has ended."""
+ return self.state in jobs._JOB_COMPLETE_STATES
+
+ @property
+ def has_succeeded(self) -> bool:
+ """Returns true if this batch prediction job has succeeded."""
+ return self.state == gca_types.JobState.JOB_STATE_SUCCEEDED
+
+ @property
+ def error(self) -> Optional[status_pb2.Status]:
+ """Returns detailed error info for this Job resource."""
+ return self._gca_resource.error
+
+ @property
+ def output_location(self) -> str:
+ """Returns the output location of this batch prediction job."""
+ return (
+ self._gca_resource.output_info.gcs_output_directory
+ or self._gca_resource.output_info.bigquery_output_table
+ )
+
+ @classmethod
+ def submit(
+ cls,
+ source_model: str,
+ input_dataset: Union[str, List[str]],
+ *,
+ output_uri_prefix: Optional[str] = None,
+ job_display_name: Optional[str] = None,
+ machine_type: Optional[str] = None,
+ accelerator_type: Optional[str] = None,
+ accelerator_count: Optional[int] = None,
+ starting_replica_count: Optional[int] = None,
+ max_replica_count: Optional[int] = None,
+ ) -> "BatchPredictionJob":
+ """Submits a batch prediction job for a GenAI model.
+
+ Args:
+ source_model (str):
+ A GenAI model name or a tuned model name for batch prediction.
+ Supported formats for model name: "gemini-1.0-pro",
+ "models/gemini-1.0-pro", and "publishers/google/models/gemini-1.0-pro"
+ Supported formats for tuned model name: "789" and
+ "projects/123/locations/456/models/789"
+ input_dataset (Union[str,List[str]]):
+ GCS URI(-s) or BigQuery URI to your input data to run batch
+ prediction on. Example: "gs://path/to/input/data.jsonl" or
+ "bq://projectId.bqDatasetId.bqTableId"
+ output_uri_prefix (str):
+ GCS or BigQuery URI prefix for the output predictions. Example:
+ "gs://path/to/output/data" or "bq://projectId.bqDatasetId"
+ If not specified, f"{STAGING_BUCKET}/gen-ai-batch-prediction" will
+ be used for GCS source and
+ f"bq://projectId.gen_ai_batch_prediction.predictions_{TIMESTAMP}"
+ will be used for BigQuery source.
+ job_display_name (str):
+ The user-defined name of the BatchPredictionJob.
+ The name can be up to 128 characters long and can be consist
+ of any UTF-8 characters.
+ machine_type (str):
+ The type of machine for running batch prediction job.
+ accelerator_type (str):
+ The type of accelerator for running batch prediction job.
+ accelerator_count (int):
+ The number of accelerators for running batch prediction job.
+ starting_replica_count (int):
+ The starting number of replica for running batch prediction job.
+ max_replica_count (int):
+ The maximum number of replica for running batch prediction job.
+
+ Returns:
+ Instantiated BatchPredictionJob.
+
+ Raises:
+ ValueError: If source_model is not a GenAI model.
+ Or if input_dataset or output_uri_prefix are not in supported formats.
+ Or if output_uri_prefix is not specified and staging_bucket is not
+ set in agentplatform.init().
+ """
+ # Handle model name
+ model_name = cls._reconcile_model_name(source_model)
+ if not cls._is_genai_model(model_name):
+ raise ValueError(f"Model '{model_name}' is not a Generative AI model.")
+
+ # Handle input URI
+ gcs_source = None
+ bigquery_source = None
+ first_input_uri = (
+ input_dataset if isinstance(input_dataset, str) else input_dataset[0]
+ )
+ if first_input_uri.startswith("gs://"):
+ gcs_source = input_dataset
+ elif first_input_uri.startswith("bq://"):
+ if not isinstance(input_dataset, str):
+ raise ValueError("Multiple BigQuery input datasets are not supported.")
+ bigquery_source = input_dataset
+ else:
+ raise ValueError(
+ f"Unsupported input URI: {input_dataset}. "
+ "Supported formats: 'gs://path/to/input/data.jsonl' and "
+ "'bq://projectId.bqDatasetId.bqTableId'"
+ )
+
+ # Handle output URI
+ gcs_destination_prefix = None
+ bigquery_destination_prefix = None
+ if output_uri_prefix:
+ if output_uri_prefix.startswith("gs://"):
+ gcs_destination_prefix = output_uri_prefix
+ elif output_uri_prefix.startswith("bq://"):
+ # Temporarily handle this in SDK, will remove once b/338423462 is fixed.
+ bigquery_destination_prefix = cls._complete_bq_uri(output_uri_prefix)
+ else:
+ raise ValueError(
+ f"Unsupported output URI: {output_uri_prefix}. "
+ "Supported formats: 'gs://path/to/output/data' and "
+ "'bq://projectId.bqDatasetId'"
+ )
+ else:
+ if first_input_uri.startswith("gs://"):
+ if not aiplatform_initializer.global_config.staging_bucket:
+ raise ValueError(
+ "Please either specify output_uri_prefix or "
+ "set staging_bucket in agentplatform.init()."
+ )
+ gcs_destination_prefix = (
+ aiplatform_initializer.global_config.staging_bucket.rstrip("/")
+ + "/gen-ai-batch-prediction"
+ )
+ else:
+ bigquery_destination_prefix = cls._complete_bq_uri()
+
+ # Reuse aiplatform class to submit the job (override _LOGGER)
+ logging.getLogger("google.cloud.aiplatform.jobs").disabled = True
+ try:
+ aiplatform_job = jobs.BatchPredictionJob.submit(
+ model_name=model_name,
+ job_display_name=job_display_name,
+ gcs_source=gcs_source,
+ bigquery_source=bigquery_source,
+ gcs_destination_prefix=gcs_destination_prefix,
+ bigquery_destination_prefix=bigquery_destination_prefix,
+ machine_type=machine_type,
+ accelerator_type=accelerator_type,
+ accelerator_count=accelerator_count,
+ starting_replica_count=starting_replica_count,
+ max_replica_count=max_replica_count,
+ )
+ job = cls._empty_constructor()
+ job._gca_resource = aiplatform_job._gca_resource
+
+ _LOGGER.log_create_complete(
+ cls, job._gca_resource, "job", module_name="batch_prediction"
+ )
+ _LOGGER.info("View Batch Prediction Job:\n%s" % job._dashboard_uri())
+
+ return job
+ finally:
+ logging.getLogger("google.cloud.aiplatform.jobs").disabled = False
+
+ def refresh(self) -> "BatchPredictionJob":
+ """Refreshes the batch prediction job from the service."""
+ self._sync_gca_resource()
+ return self
+
+ def cancel(self):
+ """Cancels this BatchPredictionJob.
+
+ Success of cancellation is not guaranteed. Use `job.refresh()` and
+ `job.state` to verify if cancellation was successful.
+ """
+ _LOGGER.log_action_start_against_resource("Cancelling", "run", self)
+ self.api_client.cancel_batch_prediction_job(name=self.resource_name)
+
+ def delete(self):
+ """Deletes this BatchPredictionJob resource.
+
+ WARNING: This deletion is permanent.
+ """
+ self._delete()
+
+ @classmethod
+ def list(cls, filter=None) -> List["BatchPredictionJob"]:
+ """Lists all BatchPredictionJob instances that run with GenAI models."""
+ return cls._list(
+ cls_filter=lambda gca_resource: cls._is_genai_model(gca_resource.model),
+ filter=filter,
+ )
+
+ def _dashboard_uri(self) -> Optional[str]:
+ """Returns the Google Cloud console URL where job can be viewed."""
+ fields = self._parse_resource_name(self.resource_name)
+ location = fields.pop("location")
+ project = fields.pop("project")
+ job = list(fields.values())[0]
+ return (
+ "https://console.cloud.google.com/agent-platform/locations/"
+ f"{location}/{self._job_type}/{job}?project={project}"
+ )
+
+ @classmethod
+ def _reconcile_model_name(cls, model_name: str) -> str:
+ """Reconciles model name to a publisher model resource name or a tuned model resource name."""
+ if not model_name:
+ raise ValueError("model_name must not be empty")
+
+ if "/" not in model_name:
+ # model name (e.g., gemini-1.0-pro)
+ if model_name.startswith("gemini"):
+ return "publishers/google/models/" + model_name
+ else:
+ raise ValueError(
+ "Abbreviated model names are only supported for Gemini models. "
+ "Please provide the full publisher model name."
+ )
+ elif model_name.startswith("models/"):
+ # publisher model name (e.g., models/gemini-1.0-pro)
+ return "publishers/google/" + model_name
+ elif (
+ re.match(
+ r"^publishers/(?P[^/]+)/models/(?P[^@]+)@(?P[^@]+)$",
+ model_name,
+ )
+ or model_name.startswith("publishers/google/models/")
+ or model_name.startswith("publishers/meta/models/")
+ or model_name.startswith("publishers/anthropic/models/")
+ or model_name.startswith("publishers/openai/models/")
+ or model_name.startswith("publishers/qwen/models/")
+ or model_name.startswith("publishers/deepseek-ai/models/")
+ or model_name.startswith("publishers/intfloat/models/")
+ or re.search(_GEMINI_TUNED_MODEL_PATTERN, model_name)
+ ):
+ return model_name
+ else:
+ raise ValueError(f"Invalid format for model name: {model_name}.")
+
+ @classmethod
+ def _is_genai_model(cls, model_name: str) -> bool:
+ """Validates if a given model_name represents a GenAI model."""
+ if re.search(_GEMINI_MODEL_PATTERN, model_name):
+ # Model is a Gemini model.
+ return True
+
+ if re.search(_GEMINI_TUNED_MODEL_PATTERN, model_name):
+ model = models.Model(model_name)
+ if (
+ model.gca_resource.model_source_info.source_type
+ == gca_types.model.ModelSourceInfo.ModelSourceType.GENIE
+ ):
+ # Model is a tuned Gemini model.
+ return True
+
+ if re.search(_LLAMA_MODEL_PATTERN, model_name):
+ # Model is a Llama3 model.
+ return True
+
+ if re.search(_CLAUDE_MODEL_PATTERN, model_name):
+ # Model is a claude model.
+ return True
+
+ if re.search(_GPT_MODEL_PATTERN, model_name):
+ # Model is a GPT model.
+ return True
+
+ if re.search(_QWEN_MODEL_PATTERN, model_name):
+ # Model is a Qwen model.
+ return True
+
+ if re.search(_DEEPSEEK_MODEL_PATTERN, model_name):
+ # Model is a DeepSeek model.
+ return True
+
+ if re.search(_E5_MODEL_PATTERN, model_name):
+ # Model is an E5 model.
+ return True
+
+ if re.match(
+ r"^publishers/(?P[^/]+)/models/(?P[^@]+)@(?P[^@]+)$",
+ model_name,
+ ):
+ # Model is a self-hosted model.
+ return True
+
+ return False
+
+ @classmethod
+ def num_pending_jobs(cls) -> int:
+ """Returns the number of pending batch prediction jobs.
+
+ The pending jobs are those defined in _JOB_PENDING_STATES from
+ google/cloud/aiplatform/jobs.py
+ e.g. JOB_STATE_QUEUED, JOB_STATE_PENDING, JOB_STATE_RUNNING,
+ JOB_STATE_CANCELLING, JOB_STATE_UPDATING.
+ It will be used to manage the number of concurrent batch that is limited
+ according to
+ https://cloud.google.com/vertex-ai/generative-ai/docs/quotas#concurrent-batch-requests
+ """
+ return len(
+ cls._list(
+ cls_filter=lambda gca_resource: cls._is_genai_model(gca_resource.model),
+ filter=" OR ".join(
+ f'state="{pending_state.name}"'
+ for pending_state in jobs._JOB_PENDING_STATES
+ ),
+ )
+ )
+
+ @classmethod
+ def _complete_bq_uri(cls, uri: Optional[str] = None):
+ """Completes a BigQuery uri to a BigQuery table uri."""
+ uri_parts = uri.split(".") if uri else []
+ uri_len = len(uri_parts)
+ if len(uri_parts) > 3:
+ raise ValueError(
+ f"Invalid URI: {uri}. "
+ "Supported formats: 'bq://projectId.bqDatasetId.bqTableId'"
+ )
+
+ schema_and_project = (
+ uri_parts[0]
+ if uri_len >= 1
+ else f"bq://{aiplatform_initializer.global_config.project}"
+ )
+ if not schema_and_project.startswith("bq://"):
+ raise ValueError("URI must start with 'bq://'")
+
+ dataset = uri_parts[1] if uri_len >= 2 else "gen_ai_batch_prediction"
+
+ table = (
+ uri_parts[2]
+ if uri_len >= 3
+ else f"predictions_{aiplatform_utils.timestamped_unique_name()}"
+ )
+
+ return f"{schema_and_project}.{dataset}.{table}"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..589f3f77fa667a726524b614f830afda0a7e2854
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Classes and functions for working with Model Garden."""
+
+# We just want to re-export certain classes
+# pylint: disable=g-multiple-import,g-importing-member
+from agentplatform.model_garden import _model_garden
+
+OpenModel = _model_garden.OpenModel
+PartnerModel = _model_garden.PartnerModel
+list_deployable_models = _model_garden.list_deployable_models
+list_models = _model_garden.list_models
+
+__all__ = ("OpenModel", "PartnerModel", "list_deployable_models", "list_models")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0726d87c7509c9c155910dee9649290190dc29b3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__pycache__/_model_garden.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__pycache__/_model_garden.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7abe0fa2df4ae5a6202cbc0af3f937478072ee1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/__pycache__/_model_garden.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/_model_garden.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/_model_garden.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b80f7e71d3a24891e78cea70782b8056e620a60
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/model_garden/_model_garden.py
@@ -0,0 +1,1537 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# pylint: disable=bad-continuation, line-too-long, protected-access
+"""Class for interacting with Model Garden OSS models."""
+
+import datetime
+import functools
+import re
+from typing import Dict, List, Optional, Sequence, Union
+
+from google.cloud import aiplatform
+from google.cloud.aiplatform import base
+from google.cloud.aiplatform import compat
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform import models as aiplatform_models
+from google.cloud.aiplatform import utils
+from google.cloud.aiplatform_v1beta1 import types
+from google.cloud.aiplatform_v1beta1.services import model_garden_service
+from google.cloud.aiplatform_v1beta1.services import model_service
+from agentplatform import batch_prediction
+
+
+from google.protobuf import duration_pb2
+
+
+_LOGGER = base.Logger(__name__)
+_DEFAULT_VERSION = compat.V1BETA1
+_DEFAULT_TIMEOUT = 2 * 60 * 60 # 2 hours, same as UI one-click deployment.
+_DEFAULT_RECOMMEND_SPEC_TIMEOUT = 1 * 60 # 1 minute.
+_DEFAULT_EXPORT_TIMEOUT = 1 * 60 * 60 # 1 hour.
+_HF_WILDCARD_FILTER = "is_hf_wildcard(true)"
+_NATIVE_MODEL_FILTER = "is_hf_wildcard(false)"
+_VERIFIED_DEPLOYMENT_FILTER = (
+ "labels.VERIFIED_DEPLOYMENT_CONFIG=VERIFIED_DEPLOYMENT_SUCCEED"
+)
+
+
+def list_deployable_models(
+ *, list_hf_models: bool = False, model_filter: Optional[str] = None
+) -> List[str]:
+ """Lists the deployable models in Model Garden.
+
+ Args:
+ list_hf_models: Whether to list the Hugging Face models.
+ model_filter: Optional. A string to filter the models by.
+
+ Returns:
+ The names of the deployable models in Model Garden in the format of
+ `{publisher}/{model}@{version}` or Hugging Face model ID in the format
+ of `{organization}/{model}`.
+ """
+
+ filter_str = _NATIVE_MODEL_FILTER
+ if list_hf_models:
+ filter_str = " AND ".join([_HF_WILDCARD_FILTER, _VERIFIED_DEPLOYMENT_FILTER])
+ if model_filter:
+ filter_str = (
+ f'{filter_str} AND (model_user_id=~"(?i).*{model_filter}.*" OR'
+ f' display_name=~"(?i).*{model_filter}.*")'
+ )
+
+ request = types.ListPublisherModelsRequest(
+ parent="publishers/*",
+ list_all_versions=True,
+ filter=filter_str,
+ )
+ client = initializer.global_config.create_client(
+ client_class=_ModelGardenClientWithOverride,
+ credentials=initializer.global_config.credentials,
+ location_override="us-central1",
+ )
+ response = client.list_publisher_models(request)
+ output = []
+ for page in response.pages:
+ for model in page.publisher_models:
+ if model.supported_actions.multi_deploy_vertex.multi_deploy_vertex:
+ output.append(
+ re.sub(r"publishers/(hf-|)|models/", "", model.name)
+ + ("" if list_hf_models else ("@" + model.version_id))
+ )
+ return output
+
+
+def list_models(
+ *, list_hf_models: bool = False, model_filter: Optional[str] = None
+) -> List[str]:
+ """Lists the models in Model Garden.
+
+ Args:
+ list_hf_models: Whether to list the Hugging Face models.
+ model_filter: Optional. A string to filter the models by.
+
+ Returns:
+ The names of the models in Model Garden in the format of
+ `{publisher}/{model}@{version}` or Hugging Face model ID in the format
+ of `{organization}/{model}`.
+ """
+ filter_str = _NATIVE_MODEL_FILTER
+ if list_hf_models:
+ filter_str = _HF_WILDCARD_FILTER
+ if model_filter:
+ filter_str = (
+ f'{filter_str} AND (model_user_id=~"(?i).*{model_filter}.*" OR'
+ f' display_name=~"(?i).*{model_filter}.*")'
+ )
+
+ request = types.ListPublisherModelsRequest(
+ parent="publishers/*",
+ list_all_versions=True,
+ filter=filter_str,
+ )
+ client = initializer.global_config.create_client(
+ client_class=_ModelGardenClientWithOverride,
+ credentials=initializer.global_config.credentials,
+ location_override="us-central1",
+ )
+ response = client.list_publisher_models(request)
+ output = []
+ for page in response.pages:
+ for model in page.publisher_models:
+ output.append(
+ re.sub(r"publishers/(hf-|)|models/", "", model.name)
+ + ("" if list_hf_models else ("@" + model.version_id))
+ )
+ return output
+
+
+def _is_hugging_face_model(model_name: str) -> bool:
+ """Returns whether the model is a Hugging Face model."""
+ return re.match(r"^(?P[^/]+)/(?P[^/@]+)$", model_name)
+
+
+def _get_publisher_model_resource_name(publisher: str, model: str) -> str:
+ """Returns the resource name.
+
+ Args:
+ publisher: Publisher of the model.
+ model: Model name, may or may not include version.
+
+ Returns:
+ The resource name in the format of
+ `publishers/{publisher}/models/{model_user_id}@{version_id}`.
+ """
+ return f"publishers/{publisher}/models/{model}"
+
+
+def _reconcile_model_name(model_name: str) -> str:
+ """Returns the resource name from the model name.
+
+ Args:
+ model_name: Model Garden model resource name in the format of
+ `publishers/{publisher}/models/{model}@{version}`, or a simplified
+ resource name in the format of `{publisher}/{model}@{version}`, or a
+ Hugging Face model ID in the format of `{organization}/{model}`.
+
+ Returns:
+ The resource name in the format of
+ `publishers/{publisher}/models/{model}@{version}`.
+ """
+ model_name = model_name.lower() # Use lower case for Hugging Face.
+ full_resource_name_match = re.match(
+ r"^publishers/(?P[^/]+)/models/(?P[^@]+)@(?P[^@]+)$",
+ model_name,
+ )
+ if full_resource_name_match:
+ return _get_publisher_model_resource_name(
+ full_resource_name_match.group("publisher"),
+ full_resource_name_match.group("model")
+ + "@"
+ + full_resource_name_match.group("version"),
+ )
+ else:
+ simplified_name_match = re.match(
+ r"^(?P[^/]+)/(?P[^@]+)(?:@(?P.+))?$",
+ model_name,
+ )
+ if simplified_name_match:
+ if simplified_name_match.group("version"):
+ return _get_publisher_model_resource_name(
+ publisher=simplified_name_match.group("publisher"),
+ model=simplified_name_match.group("model")
+ + "@"
+ + simplified_name_match.group("version"),
+ )
+ else:
+ return _get_publisher_model_resource_name(
+ publisher=simplified_name_match.group("publisher"),
+ model=simplified_name_match.group("model"),
+ )
+ else:
+ raise ValueError(f"`{model_name}` is not a valid Open Model name")
+
+
+def _construct_serving_container_spec(
+ serving_container_image_uri: Optional[str] = None,
+ serving_container_predict_route: Optional[str] = None,
+ serving_container_health_route: Optional[str] = None,
+ serving_container_command: Optional[Sequence[str]] = None,
+ serving_container_args: Optional[Sequence[str]] = None,
+ serving_container_environment_variables: Optional[Dict[str, str]] = None,
+ serving_container_ports: Optional[Sequence[int]] = None,
+ serving_container_grpc_ports: Optional[Sequence[int]] = None,
+ serving_container_deployment_timeout: Optional[int] = None,
+ serving_container_shared_memory_size_mb: Optional[int] = None,
+ serving_container_startup_probe_exec: Optional[Sequence[str]] = None,
+ serving_container_startup_probe_period_seconds: Optional[int] = None,
+ serving_container_startup_probe_timeout_seconds: Optional[int] = None,
+ serving_container_health_probe_exec: Optional[Sequence[str]] = None,
+ serving_container_health_probe_period_seconds: Optional[int] = None,
+ serving_container_health_probe_timeout_seconds: Optional[int] = None,
+) -> types.ModelContainerSpec:
+ """Constructs a ServingContainerSpec from the proto."""
+ env = None
+ ports = None
+ grpc_ports = None
+ deployment_timeout = (
+ duration_pb2.Duration(seconds=serving_container_deployment_timeout)
+ if serving_container_deployment_timeout
+ else None
+ )
+ startup_probe = None
+ health_probe = None
+
+ if serving_container_environment_variables:
+ env = [
+ types.EnvVar(name=str(key), value=str(value))
+ for key, value in serving_container_environment_variables.items()
+ ]
+ if serving_container_ports:
+ ports = [types.Port(container_port=port) for port in serving_container_ports]
+ if serving_container_grpc_ports:
+ grpc_ports = [
+ types.Port(container_port=port) for port in serving_container_grpc_ports
+ ]
+ if (
+ serving_container_startup_probe_exec
+ or serving_container_startup_probe_period_seconds
+ or serving_container_startup_probe_timeout_seconds
+ ):
+ startup_probe_exec = None
+ if serving_container_startup_probe_exec:
+ startup_probe_exec = types.Probe.ExecAction(
+ command=serving_container_startup_probe_exec
+ )
+ startup_probe = types.Probe(
+ exec=startup_probe_exec,
+ period_seconds=serving_container_startup_probe_period_seconds,
+ timeout_seconds=serving_container_startup_probe_timeout_seconds,
+ )
+ if (
+ serving_container_health_probe_exec
+ or serving_container_health_probe_period_seconds
+ or serving_container_health_probe_timeout_seconds
+ ):
+ health_probe_exec = None
+ if serving_container_health_probe_exec:
+ health_probe_exec = types.Probe.ExecAction(
+ command=serving_container_health_probe_exec
+ )
+ health_probe = types.Probe(
+ exec=health_probe_exec,
+ period_seconds=serving_container_health_probe_period_seconds,
+ timeout_seconds=serving_container_health_probe_timeout_seconds,
+ )
+
+ return types.ModelContainerSpec(
+ image_uri=serving_container_image_uri,
+ command=serving_container_command,
+ args=serving_container_args,
+ env=env,
+ ports=ports,
+ grpc_ports=grpc_ports,
+ predict_route=serving_container_predict_route,
+ health_route=serving_container_health_route,
+ deployment_timeout=deployment_timeout,
+ shared_memory_size_mb=serving_container_shared_memory_size_mb,
+ startup_probe=startup_probe,
+ health_probe=health_probe,
+ )
+
+
+class _ModelGardenClientWithOverride(utils.ClientWithOverride):
+ _is_temporary = True
+ _default_version = _DEFAULT_VERSION
+ _version_map = (
+ (
+ _DEFAULT_VERSION,
+ model_garden_service.ModelGardenServiceClient,
+ ),
+ )
+
+
+class _ModelServiceClientWithOverride(utils.ClientWithOverride):
+ _is_temporary = True
+ _default_version = _DEFAULT_VERSION
+ _version_map = (
+ (
+ _DEFAULT_VERSION,
+ model_service.ModelServiceClient,
+ ),
+ )
+
+
+class OpenModel:
+ """Represents a Model Garden Open model.
+
+ Attributes:
+ model_name: Model Garden model resource name in the format of
+ `publishers/{publisher}/models/{model}@{version}`, or a simplified
+ resource name in the format of `{publisher}/{model}@{version}`, or a
+ Hugging Face model ID in the format of `{organization}/{model}`.
+ """
+
+ __module__ = "agentplatform.model_garden"
+
+ def __init__(
+ self,
+ model_name: str,
+ ):
+ r"""Initializes a Model Garden model.
+
+ Usage:
+
+ ```
+ model = OpenModel("publishers/google/models/gemma2@gemma-2-2b-it")
+ ```
+
+ Args:
+ model_name: Model Garden model resource name in the format of
+ `publishers/{publisher}/models/{model}@{version}`, or a simplified
+ resource name in the format of `{publisher}/{model}@{version}`, or a
+ Hugging Face model ID in the format of `{organization}/{model}`.
+ """
+ project = initializer.global_config.project
+ location = initializer.global_config.location
+ credentials = initializer.global_config.credentials
+
+ self._model_name = model_name
+ self._is_hugging_face_model = _is_hugging_face_model(model_name)
+ self._publisher_model_name = _reconcile_model_name(model_name)
+ self._project = project
+ self._location = location
+ self._credentials = credentials
+
+ @functools.cached_property
+ def _model_garden_client(
+ self,
+ ) -> model_garden_service.ModelGardenServiceClient:
+ """Returns the Model Garden client."""
+ return initializer.global_config.create_client(
+ client_class=_ModelGardenClientWithOverride,
+ credentials=self._credentials,
+ location_override=self._location,
+ )
+
+ @functools.cached_property
+ def _us_central1_model_garden_client(
+ self,
+ ) -> model_garden_service.ModelGardenServiceClient:
+ """Returns the Model Garden client in us-central1."""
+ return initializer.global_config.create_client(
+ client_class=_ModelGardenClientWithOverride,
+ credentials=self._credentials,
+ location_override="us-central1",
+ )
+
+ def export(
+ self,
+ target_gcs_path: str = "",
+ export_request_timeout: Optional[float] = None,
+ ) -> str:
+ """Exports an Open Model to a google cloud storage bucket.
+
+ Args:
+ target_gcs_path: target gcs path.
+ export_request_timeout: The timeout for the deploy request. Default is 2
+ hours.
+
+ Returns:
+ str: the target gcs bucket where the model weights are downloaded to
+
+
+ Raises:
+ ValueError: If ``target_gcs_path`` is not specified
+ """
+ if not target_gcs_path:
+ raise ValueError("target_gcs_path is required.")
+
+ request = types.ExportPublisherModelRequest(
+ parent=f"projects/{self._project}/locations/{self._location}",
+ name=self._publisher_model_name,
+ destination=types.GcsDestination(output_uri_prefix=target_gcs_path),
+ )
+ request_headers = [
+ ("x-goog-user-project", "{}".format(initializer.global_config.project)),
+ ]
+
+ _LOGGER.info(f"Exporting model weights: {self._model_name}")
+
+ operation_future = self._model_garden_client.export_publisher_model(
+ request, metadata=request_headers
+ )
+ _LOGGER.info(f"LRO: {operation_future.operation.name}")
+
+ _LOGGER.info(f"Start time: {datetime.datetime.now()}")
+ export_publisher_model_response = operation_future.result(
+ timeout=export_request_timeout or _DEFAULT_EXPORT_TIMEOUT
+ )
+ _LOGGER.info(f"End time: {datetime.datetime.now()}")
+ _LOGGER.info(f"Response: {export_publisher_model_response}")
+
+ return export_publisher_model_response.destination_uri
+
+ def deploy(
+ self,
+ accept_eula: bool = False,
+ hugging_face_access_token: Optional[str] = None,
+ machine_type: Optional[str] = None,
+ min_replica_count: int = 1,
+ max_replica_count: int = 1,
+ accelerator_type: Optional[str] = None,
+ accelerator_count: Optional[int] = None,
+ spot: bool = False,
+ reservation_affinity_type: Optional[str] = None,
+ reservation_affinity_key: Optional[str] = None,
+ reservation_affinity_values: Optional[List[str]] = None,
+ use_dedicated_endpoint: Optional[bool] = False,
+ dedicated_endpoint_disabled: Optional[bool] = False,
+ fast_tryout_enabled: Optional[bool] = False,
+ system_labels: Optional[Dict[str, str]] = None,
+ endpoint_display_name: Optional[str] = None,
+ model_display_name: Optional[str] = None,
+ deploy_request_timeout: Optional[float] = None,
+ serving_container_spec: Optional[types.ModelContainerSpec] = None,
+ serving_container_image_uri: Optional[str] = None,
+ serving_container_predict_route: Optional[str] = None,
+ serving_container_health_route: Optional[str] = None,
+ serving_container_command: Optional[Sequence[str]] = None,
+ serving_container_args: Optional[Sequence[str]] = None,
+ serving_container_environment_variables: Optional[Dict[str, str]] = None,
+ serving_container_ports: Optional[Sequence[int]] = None,
+ serving_container_grpc_ports: Optional[Sequence[int]] = None,
+ serving_container_deployment_timeout: Optional[int] = None,
+ serving_container_shared_memory_size_mb: Optional[int] = None,
+ serving_container_startup_probe_exec: Optional[Sequence[str]] = None,
+ serving_container_startup_probe_period_seconds: Optional[int] = None,
+ serving_container_startup_probe_timeout_seconds: Optional[int] = None,
+ serving_container_health_probe_exec: Optional[Sequence[str]] = None,
+ serving_container_health_probe_period_seconds: Optional[int] = None,
+ serving_container_health_probe_timeout_seconds: Optional[int] = None,
+ enable_private_service_connect: bool = False,
+ psc_project_allow_list: Optional[Sequence[str]] = None,
+ ) -> aiplatform.Endpoint:
+ """Deploys an Open Model to an endpoint.
+
+ Args:
+ accept_eula (bool): Whether to accept the End User License Agreement.
+ hugging_face_access_token (str): The access token to access Hugging Face
+ models. Reference: https://huggingface.co/docs/hub/en/security-tokens
+ machine_type (str): Optional. The type of machine. Not specifying
+ machine type will result in model to be deployed with automatic
+ resources.
+ min_replica_count (int): Optional. The minimum number of machine
+ replicas this deployed model will be always deployed on. If traffic
+ against it increases, it may dynamically be deployed onto more
+ replicas, and as traffic decreases, some of these extra replicas may
+ be freed.
+ max_replica_count (int): Optional. The maximum number of replicas this
+ deployed model may be deployed on when the traffic against it
+ increases. If requested value is too large, the deployment will error,
+ but if deployment succeeds then the ability to scale the model to that
+ many replicas is guaranteed (barring service outages). If traffic
+ against the deployed model increases beyond what its replicas at
+ maximum may handle, a portion of the traffic will be dropped. If this
+ value is not provided, the larger value of min_replica_count or 1 will
+ be used. If value provided is smaller than min_replica_count, it will
+ automatically be increased to be min_replica_count.
+ accelerator_type (str): Optional. Hardware accelerator type. Must also
+ set accelerator_count if used. One of ACCELERATOR_TYPE_UNSPECIFIED,
+ NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100,
+ NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
+ accelerator_count (int): Optional. The number of accelerators to attach
+ to a worker replica.
+ spot (bool): Optional. Whether to schedule the deployment workload on
+ spot VMs.
+ reservation_affinity_type (str): Optional. The type of reservation
+ affinity. One of NO_RESERVATION, ANY_RESERVATION,
+ SPECIFIC_RESERVATION, SPECIFIC_THEN_ANY_RESERVATION,
+ SPECIFIC_THEN_NO_RESERVATION
+ reservation_affinity_key (str): Optional. Corresponds to the label key
+ of a reservation resource. To target a SPECIFIC_RESERVATION by name,
+ use `compute.googleapis.com/reservation-name` as the key and specify
+ the name of your reservation as its value.
+ reservation_affinity_values (List[str]): Optional. Corresponds to the
+ label values of a reservation resource. This must be the full resource
+ name of the reservation.
+ Format:
+ 'projects/{project_id_or_number}/zones/{zone}/reservations/{reservation_name}'
+ use_dedicated_endpoint (bool): Optional. Default value is False. If set
+ to True, the underlying prediction call will be made using the
+ dedicated endpoint dns.
+ dedicated_endpoint_disabled (bool): Optional. Default value is False. If set
+ to False, the underlying prediction call will be made using the
+ dedicated endpoint dns. Otherwise, the prediction call will be made
+ using the shared endpoint dns.
+ fast_tryout_enabled (bool): Optional. Defaults to False. If True, model
+ will be deployed using faster deployment path. Useful for quick
+ experiments. Not for production workloads. Only available for most
+ popular models with certain machine types.
+ system_labels (Dict[str, str]): Optional. System labels for Model Garden
+ deployments. These labels are managed by Google and for tracking
+ purposes only.
+ endpoint_display_name: The display name of the created endpoint.
+ model_display_name: The display name of the uploaded model.
+ deploy_request_timeout: The timeout for the deploy request. Default is 2
+ hours.
+ serving_container_spec (types.ModelContainerSpec): Optional. The
+ container specification for the model instance. This specification
+ overrides the default container specification and other serving
+ container parameters.
+ serving_container_image_uri (str): Optional. The URI of the Model
+ serving container. This parameter is required if the parameter
+ `local_model` is not specified.
+ serving_container_predict_route (str): Optional. An HTTP path to send
+ prediction requests to the container, and which must be supported by
+ it. If not specified a default HTTP path will be used by Gemini Enterprise Agent Platform.
+ serving_container_health_route (str): Optional. An HTTP path to send
+ health check requests to the container, and which must be supported by
+ it. If not specified a standard HTTP path will be used by Gemini Enterprise Agent Platform.
+ serving_container_command: Optional[Sequence[str]]=None, The command
+ with which the container is run. Not executed within a shell. The
+ Docker image's ENTRYPOINT is used if this is not provided. Variable
+ references $(VAR_NAME) are expanded using the container's environment.
+ If a variable cannot be resolved, the reference in the input string
+ will be unchanged. The $(VAR_NAME) syntax can be escaped with a double
+ $$, ie: $$(VAR_NAME). Escaped references will never be expanded,
+ regardless of whether the variable exists or not.
+ serving_container_args: Optional[Sequence[str]]=None, The arguments to
+ the command. The Docker image's CMD is used if this is not provided.
+ Variable references $(VAR_NAME) are expanded using the container's
+ environment. If a variable cannot be resolved, the reference in the
+ input string will be unchanged. The $(VAR_NAME) syntax can be escaped
+ with a double $$, ie: $$(VAR_NAME). Escaped references will never be
+ expanded, regardless of whether the variable exists or not.
+ serving_container_environment_variables: Optional[Dict[str, str]]=None,
+ The environment variables that are to be present in the container.
+ Should be a dictionary where keys are environment variable names and
+ values are environment variable values for those names.
+ serving_container_ports: Optional[Sequence[int]]=None, Declaration of
+ ports that are exposed by the container. This field is primarily
+ informational, it gives Gemini Enterprise Agent Platform information about the network
+ connections the container uses. Listing or not a port here has no
+ impact on whether the port is actually exposed, any port listening on
+ the default "0.0.0.0" address inside a container will be accessible
+ from the network.
+ serving_container_grpc_ports: Optional[Sequence[int]]=None, Declaration
+ of ports that are exposed by the container. Gemini Enterprise Agent
+ Platform sends gRPC
+ prediction requests that it receives to the first port on this list.
+ Gemini Enterprise Agent Platform also sends liveness and health checks to this port. If you
+ do not specify this field, gRPC requests to the container will be
+ disabled. Gemini Enterprise Agent Platform does not use ports other than the first one
+ listed. This field corresponds to the `ports` field of the Kubernetes
+ Containers v1 core API.
+ serving_container_deployment_timeout (int): Optional. Deployment timeout
+ in seconds.
+ serving_container_shared_memory_size_mb (int): Optional. The amount of
+ the VM memory to reserve as the shared memory for the model in
+ megabytes.
+ serving_container_startup_probe_exec (Sequence[str]): Optional. Exec
+ specifies the action to take. Used by startup probe. An example of
+ this argument would be ["cat", "/tmp/healthy"]
+ serving_container_startup_probe_period_seconds (int): Optional. How
+ often (in seconds) to perform the startup probe. Default to 10
+ seconds. Minimum value is 1.
+ serving_container_startup_probe_timeout_seconds (int): Optional. Number
+ of seconds after which the startup probe times out. Defaults to 1
+ second. Minimum value is 1.
+ serving_container_health_probe_exec (Sequence[str]): Optional. Exec
+ specifies the action to take. Used by health probe. An example of this
+ argument would be ["cat", "/tmp/healthy"]
+ serving_container_health_probe_period_seconds (int): Optional. How often
+ (in seconds) to perform the health probe. Default to 10 seconds.
+ Minimum value is 1.
+ serving_container_health_probe_timeout_seconds (int): Optional. Number
+ of seconds after which the health probe times out. Defaults to 1
+ second. Minimum value is 1.
+ enable_private_service_connect (bool): Whether to enable private service
+ connect.
+ psc_project_allow_list (Sequence[str]): The list of projects that are
+ allowed to access the endpoint over private service connect.
+
+ Returns:
+ endpoint (aiplatform.Endpoint):
+ Created endpoint.
+
+ Raises:
+ ValueError: If ``serving_container_spec`` is specified but
+ ``serving_container_spec.image_uri``
+ is ``None``, or if ``serving_container_spec`` is specified but other
+ serving container parameters are specified.
+ """
+ request = types.DeployRequest(
+ destination=f"projects/{self._project}/locations/{self._location}",
+ )
+ if self._is_hugging_face_model:
+ request.hugging_face_model_id = self._model_name.lower()
+ else:
+ request.publisher_model_name = self._publisher_model_name
+
+ if endpoint_display_name:
+ request.endpoint_config.endpoint_display_name = endpoint_display_name
+ if model_display_name:
+ request.model_config.model_display_name = model_display_name
+
+ if accept_eula:
+ request.model_config.accept_eula = accept_eula
+
+ if hugging_face_access_token:
+ request.model_config.hugging_face_access_token = hugging_face_access_token
+
+ provided_custom_machine_spec = (
+ machine_type or accelerator_type or accelerator_count
+ )
+ if provided_custom_machine_spec:
+ dedicated_resources = types.DedicatedResources(
+ machine_spec=types.MachineSpec(
+ machine_type=machine_type,
+ accelerator_type=accelerator_type,
+ accelerator_count=accelerator_count,
+ ),
+ min_replica_count=min_replica_count,
+ max_replica_count=max_replica_count,
+ )
+ request.deploy_config.dedicated_resources = dedicated_resources
+ if spot:
+ request.deploy_config.dedicated_resources.spot = True
+
+ if reservation_affinity_type:
+ request.deploy_config.dedicated_resources.machine_spec.reservation_affinity.reservation_affinity_type = (
+ reservation_affinity_type
+ )
+ if reservation_affinity_key and reservation_affinity_values:
+ request.deploy_config.dedicated_resources.machine_spec.reservation_affinity.key = (
+ reservation_affinity_key
+ )
+ request.deploy_config.dedicated_resources.machine_spec.reservation_affinity.values = (
+ reservation_affinity_values
+ )
+
+ # TODO(b/417560875): Remove this once notebooks are migrated to use dedicated_endpoint_disabled.
+ if use_dedicated_endpoint:
+ request.endpoint_config.dedicated_endpoint_enabled = use_dedicated_endpoint
+
+ if dedicated_endpoint_disabled:
+ request.endpoint_config.dedicated_endpoint_disabled = (
+ dedicated_endpoint_disabled
+ )
+
+ if enable_private_service_connect and psc_project_allow_list:
+ request.endpoint_config.private_service_connect_config = (
+ types.PrivateServiceConnectConfig(
+ enable_private_service_connect=enable_private_service_connect,
+ project_allowlist=psc_project_allow_list,
+ )
+ )
+
+ if fast_tryout_enabled:
+ request.deploy_config.fast_tryout_enabled = fast_tryout_enabled
+
+ if system_labels:
+ request.deploy_config.system_labels = system_labels
+
+ if serving_container_spec:
+ if not serving_container_spec.image_uri:
+ raise ValueError(
+ "Serving container image uri is required for the serving container"
+ " spec."
+ )
+ if serving_container_image_uri:
+ raise ValueError(
+ "Serving container image uri is already set in the serving"
+ " container spec."
+ )
+ request.model_config.container_spec = serving_container_spec
+
+ if serving_container_image_uri:
+ request.model_config.container_spec = _construct_serving_container_spec(
+ serving_container_image_uri,
+ serving_container_predict_route,
+ serving_container_health_route,
+ serving_container_command,
+ serving_container_args,
+ serving_container_environment_variables,
+ serving_container_ports,
+ serving_container_grpc_ports,
+ serving_container_deployment_timeout,
+ serving_container_shared_memory_size_mb,
+ serving_container_startup_probe_exec,
+ serving_container_startup_probe_period_seconds,
+ serving_container_startup_probe_timeout_seconds,
+ serving_container_health_probe_exec,
+ serving_container_health_probe_period_seconds,
+ serving_container_health_probe_timeout_seconds,
+ )
+
+ _LOGGER.info(f"Deploying model: {self._model_name}")
+
+ operation_future = self._model_garden_client.deploy(request)
+ _LOGGER.info(f"LRO: {operation_future.operation.name}")
+
+ _LOGGER.info(f"Start time: {datetime.datetime.now()}")
+ deploy_response = operation_future.result(
+ timeout=deploy_request_timeout or _DEFAULT_TIMEOUT
+ )
+ _LOGGER.info(f"End time: {datetime.datetime.now()}")
+
+ self._endpoint_name = deploy_response.endpoint
+ _LOGGER.info(f"Endpoint: {self._endpoint_name}")
+ endpoint = aiplatform.Endpoint._construct_sdk_resource_from_gapic(
+ aiplatform_models.gca_endpoint_compat.Endpoint(name=self._endpoint_name),
+ )
+ return endpoint
+
+ def list_deploy_options(
+ self,
+ concise: bool = False,
+ serving_container_image_uri_filter: Optional[Union[str, List[str]]] = None,
+ machine_type_filter: Optional[str] = None,
+ accelerator_type_filter: Optional[str] = None,
+ ) -> Union[str, Sequence[types.PublisherModel.CallToAction.Deploy]]:
+ """Lists the verified deploy options for the model.
+
+ Args:
+ concise: If true, returns a human-readable string with container and
+ machine specs.
+ serving_container_image_uri_filter: If specified, only return the
+ deploy options where the serving container image URI contains one of
+ the specified keyword(s) (e.g., "vllm" or ["vllm", "tgi"]). The
+ filter is case-insensitive.
+ machine_type_filter: If specified, only return the deploy options
+ where the machine type contains one of the specified keyword(s)
+ (e.g., "n1" or ["n1", "g2"]). The filter is case-insensitive.
+ accelerator_type_filter: If specified, only return the deploy options
+ where the accelerator type contains one of the specified keyword(s)
+ (e.g., "T4" or ["T4", "L4"]). The filter is case-insensitive.
+
+ Returns:
+ A list of deploy options or a concise formatted string.
+ """
+ request = types.GetPublisherModelRequest(
+ name=self._publisher_model_name,
+ is_hugging_face_model=bool(self._is_hugging_face_model),
+ include_equivalent_model_garden_model_deployment_configs=True,
+ )
+ response = self._us_central1_model_garden_client.get_publisher_model(request)
+ deploy_options = (
+ response.supported_actions.multi_deploy_vertex.multi_deploy_vertex
+ )
+
+ if not deploy_options:
+ raise ValueError(
+ "Model does not support deployment. "
+ "Use `list_deployable_models()` to find supported models."
+ )
+
+ if serving_container_image_uri_filter:
+ if isinstance(serving_container_image_uri_filter, str):
+ serving_container_image_uri_filter = [
+ serving_container_image_uri_filter
+ ]
+ serving_container_image_uri_filter = [
+ f.lower() for f in serving_container_image_uri_filter
+ ]
+ deploy_options = [
+ option
+ for option in deploy_options
+ if option.container_spec
+ and any(
+ f in option.container_spec.image_uri.lower()
+ for f in serving_container_image_uri_filter
+ )
+ ]
+
+ if machine_type_filter:
+ filters = (
+ [machine_type_filter]
+ if isinstance(machine_type_filter, str)
+ else machine_type_filter
+ )
+ deploy_options = [
+ option
+ for option in deploy_options
+ if option.dedicated_resources
+ and option.dedicated_resources.machine_spec
+ and any(
+ f.lower()
+ in option.dedicated_resources.machine_spec.machine_type.lower()
+ for f in filters
+ )
+ ]
+
+ if accelerator_type_filter:
+ filters = (
+ [accelerator_type_filter]
+ if isinstance(accelerator_type_filter, str)
+ else accelerator_type_filter
+ )
+ deploy_options = [
+ option
+ for option in deploy_options
+ if option.dedicated_resources
+ and option.dedicated_resources.machine_spec
+ and option.dedicated_resources.machine_spec.accelerator_type
+ and any(
+ f.lower()
+ in option.dedicated_resources.machine_spec.accelerator_type.name.lower()
+ for f in filters
+ )
+ ]
+
+ if not deploy_options:
+ raise ValueError("No deploy options found.")
+
+ if not concise:
+ return deploy_options
+
+ def _extract_config(option):
+ container = (
+ option.container_spec.image_uri if option.container_spec else None
+ )
+ machine = (
+ option.dedicated_resources.machine_spec
+ if option.dedicated_resources
+ else None
+ )
+ option_name = getattr(option, "deploy_task_name", None)
+
+ return {
+ "option_name": option_name,
+ "serving_container_image_uri": container,
+ "machine_type": getattr(machine, "machine_type", None),
+ "accelerator_type": getattr(
+ getattr(machine, "accelerator_type", None), "name", None
+ ),
+ "accelerator_count": getattr(machine, "accelerator_count", None),
+ }
+
+ concise_deploy_options = [_extract_config(opt) for opt in deploy_options]
+ return "\n\n".join(
+ (
+ f"[Option {i + 1}: {config['option_name']}]\n"
+ if config.get("option_name")
+ else f"[Option {i + 1}]\n"
+ )
+ + "\n".join(
+ f' {k}="{v}",' if k != "accelerator_count" else f" {k}={v},"
+ for k, v in config.items()
+ if v is not None and k != "option_name"
+ )
+ for i, config in enumerate(concise_deploy_options)
+ )
+
+ def batch_predict(
+ self,
+ input_dataset: Union[str, List[str]],
+ *,
+ output_uri_prefix: Optional[str] = None,
+ job_display_name: Optional[str] = None,
+ machine_type: Optional[str] = None,
+ accelerator_type: Optional[str] = None,
+ accelerator_count: Optional[int] = None,
+ starting_replica_count: Optional[int] = None,
+ max_replica_count: Optional[int] = None,
+ ) -> batch_prediction.BatchPredictionJob:
+ """Perform batch prediction on the model.
+
+ Args:
+ input_dataset (Union[str, List[str]]): GCS URI(-s) or BigQuery URI to
+ your input data to run batch prediction on. Example:
+ "gs://path/to/input/data.jsonl" or
+ "bq://projectId.bqDatasetId.bqTableId"
+ output_uri_prefix (Optional[str]): GCS or BigQuery URI prefix for the
+ output predictions. Example: "gs://path/to/output/data" or
+ "bq://projectId.bqDatasetId" If not specified,
+ f"{STAGING_BUCKET}/gen-ai-batch-prediction" will be used for GCS
+ source and
+ f"bq://projectId.gen_ai_batch_prediction.predictions_{TIMESTAMP}" will
+ be used for BigQuery source.
+ job_display_name (Optional[str]): The user-defined name of the
+ BatchPredictionJob. The name can be up to 128 characters long and can
+ be consist of any UTF-8 characters.
+ machine_type (Optional[str]): The machine type for the batch prediction
+ job.
+ accelerator_type (Optional[str]): The accelerator type for the batch
+ prediction job.
+ accelerator_count (Optional[int]): The accelerator count for the batch
+ prediction job.
+ starting_replica_count (Optional[int]): The starting replica count for
+ the batch prediction job.
+ max_replica_count (Optional[int]): The maximum replica count for the
+ batch prediction job.
+
+ Returns:
+ batch_prediction.BatchPredictionJob:
+ The batch prediction job.
+ """
+ return batch_prediction.BatchPredictionJob.submit(
+ source_model=self._publisher_model_name,
+ input_dataset=input_dataset,
+ output_uri_prefix=output_uri_prefix,
+ job_display_name=job_display_name,
+ machine_type=machine_type,
+ accelerator_type=accelerator_type,
+ accelerator_count=accelerator_count,
+ starting_replica_count=starting_replica_count,
+ max_replica_count=max_replica_count,
+ )
+
+ def check_license_agreement_status(self) -> bool:
+ """Check whether the project has accepted the license agreement of the model.
+
+ EULA (End User License Agreement) is a legal document that the user must
+ accept before using the model. For Models having license restrictions,
+ the user must accept the EULA before using the model. You can check the
+ details of the License in Model Garden.
+
+ Returns:
+ bool : True if the project has accepted the End User License
+ Agreement, False otherwise.
+ """
+ request = types.CheckPublisherModelEulaAcceptanceRequest(
+ parent=f"projects/{self._project}",
+ publisher_model=self._publisher_model_name,
+ )
+ response = self._model_garden_client.check_publisher_model_eula_acceptance(
+ request
+ )
+ return response.publisher_model_eula_acked
+
+ def accept_model_license_agreement(
+ self,
+ ) -> types.model_garden_service.PublisherModelEulaAcceptance:
+ """Accepts the EULA(End User License Agreement) of the model for the project.
+
+ For Models having license restrictions, the user must accept the EULA
+ before using the model. Calling this method will mark the EULA as accepted
+ for the project.
+
+ Returns:
+ types.model_garden_service.PublisherModelEulaAcceptance:
+ The response of the accept_eula call, containing project number,
+ model name and acceptance status.
+ """
+ request = types.AcceptPublisherModelEulaRequest(
+ parent=f"projects/{self._project}",
+ publisher_model=self._publisher_model_name,
+ )
+ return self._model_garden_client.accept_publisher_model_eula(request)
+
+
+class CustomModel:
+ """Represents a Model Garden Custom model."""
+
+ def __init__(
+ self,
+ gcs_uri: Optional[str] = None,
+ ):
+ r"""Initializes a Model Garden Custom model.
+
+ Usage:
+
+ ```
+ model = agentplatform.CustomModel(
+ gcs_uri = 'gs://tuning-job-output/node-0/checkpoints/final')
+ ```
+
+ Args:
+ gcs_uri: The GCS URI of the custom model, storing weights and config
+ files
+ """
+ if not gcs_uri:
+ raise ValueError("gcs_uri must be specified.")
+
+ project = initializer.global_config.project
+ location = initializer.global_config.location
+ credentials = initializer.global_config.credentials
+
+ self._gcs_uri = gcs_uri
+ self._project = project
+ self._location = location
+ self._credentials = credentials
+
+ @functools.cached_property
+ def _model_garden_client(
+ self,
+ ) -> model_garden_service.ModelGardenServiceClient:
+ """Returns the Model Garden client."""
+ return initializer.global_config.create_client(
+ client_class=_ModelGardenClientWithOverride,
+ credentials=self._credentials,
+ location_override=self._location,
+ )
+
+ @functools.cached_property
+ def _model_service_client(
+ self,
+ ) -> model_service.ModelServiceClient:
+ """Returns the Model Service client."""
+ return initializer.global_config.create_client(
+ client_class=_ModelServiceClientWithOverride,
+ credentials=self._credentials,
+ location_override=self._location,
+ )
+
+ def list_deploy_options(
+ self,
+ available_machines: bool = True,
+ filter_by_user_quota: bool = True,
+ request_timeout: Optional[float] = None,
+ ) -> str:
+ """Lists the deploy options for the model.
+
+ Args:
+ available_machines: If true, only return the deploy options for
+ available machines.
+ filter_by_user_quota: If true, only return the deploy options for
+ machines that the user has quota for.
+ request_timeout: The timeout for the recommend spec request.
+ Default is 60 seconds.
+
+ Returns:
+ str: A string of the deploy options represented by
+ machine spec and container spec.
+
+ """
+
+ def _extract_spec(spec):
+ machine_spec = spec.machine_spec
+ return {
+ "machine_type": getattr(machine_spec, "machine_type", None),
+ "accelerator_type": getattr(
+ getattr(machine_spec, "accelerator_type", None), "name", None
+ ),
+ "accelerator_count": getattr(machine_spec, "accelerator_count", None),
+ }
+
+ def _extract_recommendation(recommendation):
+ extracted_spec = _extract_spec(recommendation.spec)
+ extracted_spec["region"] = getattr(recommendation, "region", None)
+ if (
+ recommendation.user_quota_state
+ and recommendation.user_quota_state
+ != types.RecommendSpecResponse.Recommendation.QuotaState.QUOTA_STATE_UNSPECIFIED
+ ):
+ extracted_spec["user_quota_state"] = getattr(
+ getattr(recommendation, "user_quota_state", None), "name", None
+ )
+ return extracted_spec
+
+ request = types.RecommendSpecRequest(
+ gcs_uri=self._gcs_uri,
+ parent=f"projects/{self._project}/locations/{self._location}",
+ check_machine_availability=available_machines,
+ check_user_quota=filter_by_user_quota,
+ )
+ try:
+ response = self._model_service_client.recommend_spec(
+ request, timeout=request_timeout or _DEFAULT_RECOMMEND_SPEC_TIMEOUT
+ )
+ options = []
+ if response.recommendations:
+ options = [
+ _extract_recommendation(recommendation)
+ for recommendation in response.recommendations
+ if recommendation.spec
+ ]
+ if filter_by_user_quota:
+ options = [
+ option
+ for option in options
+ if option.get("user_quota_state")
+ == "QUOTA_STATE_USER_HAS_QUOTA"
+ ]
+ elif response.specs:
+ options = [_extract_spec(spec) for spec in response.specs if spec]
+ return "\n\n".join(
+ f"[Option {i + 1}]\n"
+ + ",\n".join(
+ f' {k}="{v}"' if k != "accelerator_count" else f" {k}={v}"
+ for k, v in config.items()
+ if v is not None
+ )
+ for i, config in enumerate(options)
+ )
+
+ except Exception as e:
+ _LOGGER.error(f"Failed to list deploy options: {e}")
+ raise e
+
+ def deploy(
+ self,
+ machine_type: Optional[str] = None,
+ min_replica_count: int = 1,
+ max_replica_count: int = 1,
+ accelerator_type: Optional[str] = None,
+ accelerator_count: Optional[int] = None,
+ reservation_affinity_type: Optional[str] = None,
+ reservation_affinity_key: Optional[str] = None,
+ reservation_affinity_values: Optional[List[str]] = None,
+ system_labels: Optional[Dict[str, str]] = None,
+ endpoint_display_name: Optional[str] = None,
+ model_display_name: Optional[str] = None,
+ enable_private_service_connect: bool = False,
+ psc_project_allow_list: Optional[List[str]] = None,
+ deploy_request_timeout: Optional[float] = None,
+ ) -> aiplatform.Endpoint:
+ """Deploys a Custom Model to an endpoint.
+
+ Args:
+ machine_type (str): Optional. The type of machine. Not specifying
+ machine type will result in model to be deployed with automatic
+ resources.
+ min_replica_count (int): Optional. The minimum number of machine
+ replicas this deployed model will be always deployed on. If traffic
+ against it increases, it may dynamically be deployed onto more
+ replicas, and as traffic decreases, some of these extra replicas may
+ be freed.
+ max_replica_count (int): Optional. The maximum number of replicas this
+ deployed model may be deployed on when the traffic against it
+ increases. If requested value is too large, the deployment will error,
+ but if deployment succeeds then the ability to scale the model to that
+ many replicas is guaranteed (barring service outages). If traffic
+ against the deployed model increases beyond what its replicas at
+ maximum may handle, a portion of the traffic will be dropped. If this
+ value is not provided, the larger value of min_replica_count or 1 will
+ be used. If value provided is smaller than min_replica_count, it will
+ automatically be increased to be min_replica_count.
+ accelerator_type (str): Optional. Hardware accelerator type. Must also
+ set accelerator_count if used.
+ accelerator_count (int): Optional. The number of accelerators to attach
+ to a worker replica.
+ reservation_affinity_type (str): Optional. The type of reservation
+ affinity. One of NO_RESERVATION, ANY_RESERVATION,
+ SPECIFIC_RESERVATION, SPECIFIC_THEN_ANY_RESERVATION,
+ SPECIFIC_THEN_NO_RESERVATION
+ reservation_affinity_key (str): Optional. Corresponds to the label key
+ of a reservation resource. To target a SPECIFIC_RESERVATION by name,
+ use `compute.googleapis.com/reservation-name` as the key and specify
+ the name of your reservation as its value.
+ reservation_affinity_values (List[str]): Optional. Corresponds to the
+ label values of a reservation resource. This must be the full resource
+ name of the reservation.
+ Format:
+ 'projects/{project_id_or_number}/zones/{zone}/reservations/{reservation_name}'
+ system_labels (Dict[str, str]): Optional. System labels for Model Garden deployments.
+ endpoint_display_name: The display name of the created endpoint.
+ model_display_name: The display name of the custom model.
+ enable_private_service_connect (bool): Whether to enable private service
+ connect.
+ psc_project_allow_list (List[str]): The list of projects that are allowed to
+ access the endpoint over private service connect.
+ deploy_request_timeout: The timeout for the deploy request. Default is 2
+ hours.
+
+ Returns:
+ endpoint (aiplatform.Endpoint):
+ Created endpoint.
+ """
+ return self._deploy_gcs_uri(
+ machine_type=machine_type,
+ min_replica_count=min_replica_count,
+ max_replica_count=max_replica_count,
+ accelerator_type=accelerator_type,
+ accelerator_count=accelerator_count,
+ reservation_affinity_type=reservation_affinity_type,
+ reservation_affinity_key=reservation_affinity_key,
+ reservation_affinity_values=reservation_affinity_values,
+ system_labels=system_labels,
+ endpoint_display_name=endpoint_display_name,
+ model_display_name=model_display_name,
+ enable_private_service_connect=enable_private_service_connect,
+ psc_project_allow_list=psc_project_allow_list,
+ deploy_request_timeout=deploy_request_timeout,
+ )
+
+ def _deploy_model_registry_model(self) -> aiplatform.Endpoint:
+ """Deploys a Model Registry model to an endpoint."""
+ raise NotImplementedError(
+ "Not implemented yet. Please provide gcs_uri in CustomModel constructor."
+ )
+
+ def _deploy_gcs_uri(
+ self,
+ machine_type: Optional[str] = None,
+ min_replica_count: int = 1,
+ max_replica_count: int = 1,
+ accelerator_type: Optional[str] = None,
+ accelerator_count: Optional[int] = None,
+ enable_private_service_connect: bool = False,
+ psc_project_allow_list: Optional[List[str]] = None,
+ reservation_affinity_type: Optional[str] = None,
+ reservation_affinity_key: Optional[str] = None,
+ reservation_affinity_values: Optional[List[str]] = None,
+ system_labels: Optional[Dict[str, str]] = None,
+ endpoint_display_name: Optional[str] = None,
+ model_display_name: Optional[str] = None,
+ deploy_request_timeout: Optional[float] = None,
+ ) -> aiplatform.Endpoint:
+ """Deploys a Custom Model to an endpoint.
+
+ Args:
+ machine_type (str): Optional. The type of machine. Not specifying
+ machine type will result in model to be deployed with automatic
+ resources.
+ min_replica_count (int): Optional. The minimum number of machine
+ replicas this deployed model will be always deployed on. If traffic
+ against it increases, it may dynamically be deployed onto more
+ replicas, and as traffic decreases, some of these extra replicas may
+ be freed.
+ max_replica_count (int): Optional. The maximum number of replicas this
+ deployed model may be deployed on when the traffic against it
+ increases. If requested value is too large, the deployment will error,
+ but if deployment succeeds then the ability to scale the model to that
+ many replicas is guaranteed (barring service outages). If traffic
+ against the deployed model increases beyond what its replicas at
+ maximum may handle, a portion of the traffic will be dropped. If this
+ value is not provided, the larger value of min_replica_count or 1 will
+ be used. If value provided is smaller than min_replica_count, it will
+ automatically be increased to be min_replica_count.
+ accelerator_type (str): Optional. Hardware accelerator type. Must also
+ set accelerator_count if used. One of ACCELERATOR_TYPE_UNSPECIFIED,
+ NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100,
+ NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
+ accelerator_count (int): Optional. The number of accelerators to attach
+ to a worker replica.
+ reservation_affinity_type (str): Optional. The type of reservation
+ affinity. One of NO_RESERVATION, ANY_RESERVATION,
+ SPECIFIC_RESERVATION, SPECIFIC_THEN_ANY_RESERVATION,
+ SPECIFIC_THEN_NO_RESERVATION
+ reservation_affinity_key (str): Optional. Corresponds to the label key
+ of a reservation resource. To target a SPECIFIC_RESERVATION by name,
+ use `compute.googleapis.com/reservation-name` as the key and specify
+ the name of your reservation as its value.
+ reservation_affinity_values (List[str]): Optional. Corresponds to the
+ label values of a reservation resource. This must be the full resource
+ name of the reservation.
+ Format:
+ 'projects/{project_id_or_number}/zones/{zone}/reservations/{reservation_name}'
+ system_labels (Dict[str, str]): Optional. System labels for Model Garden deployments.
+ endpoint_display_name: The display name of the created endpoint.
+ model_display_name: The display name of the custom model.
+ enable_private_service_connect (bool): Whether to enable private service
+ connect.
+ psc_project_allow_list (List[str]): The list of projects that are allowed to
+ access the endpoint over private service connect.
+ deploy_request_timeout: The timeout for the deploy request. Default is 2
+ hours.
+
+ Returns:
+ endpoint (aiplatform.Endpoint):
+ Created endpoint.
+ """
+
+ # Validation on machine type, accelerator type and count.
+ # Return true if all three of them have value or are None.
+ def has_all_or_none_values(var1, var2, var3) -> bool:
+ return (var1 and var2 and var3) or (not var1 and not var2 and not var3)
+
+ if not has_all_or_none_values(
+ machine_type, accelerator_type, accelerator_count
+ ):
+ raise ValueError(
+ "machine_type, accelerator_type and accelerator_count must all be provided or not provided."
+ )
+
+ request = types.DeployRequest(
+ destination=f"projects/{self._project}/locations/{self._location}",
+ )
+ request.custom_model = types.DeployRequest.CustomModel(gcs_uri=self._gcs_uri)
+ if endpoint_display_name:
+ request.endpoint_config.endpoint_display_name = endpoint_display_name
+ if model_display_name:
+ request.model_config.model_display_name = model_display_name
+ if system_labels:
+ request.deploy_config.system_labels = system_labels
+
+ if enable_private_service_connect and psc_project_allow_list:
+ request.endpoint_config.private_service_connect_config = (
+ types.PrivateServiceConnectConfig(
+ enable_private_service_connect=enable_private_service_connect,
+ project_allowlist=psc_project_allow_list,
+ )
+ )
+
+ if machine_type and accelerator_type and accelerator_count:
+ request.deploy_config.dedicated_resources = types.DedicatedResources(
+ machine_spec=types.MachineSpec(
+ machine_type=machine_type,
+ accelerator_type=accelerator_type,
+ accelerator_count=accelerator_count,
+ )
+ )
+ if min_replica_count:
+ request.deploy_config.dedicated_resources.min_replica_count = (
+ min_replica_count
+ )
+ if max_replica_count:
+ request.deploy_config.dedicated_resources.max_replica_count = (
+ max_replica_count
+ )
+
+ if reservation_affinity_type:
+ request.deploy_config.dedicated_resources.machine_spec.reservation_affinity.reservation_affinity_type = (
+ reservation_affinity_type
+ )
+ if reservation_affinity_key and reservation_affinity_values:
+ request.deploy_config.dedicated_resources.machine_spec.reservation_affinity.key = (
+ reservation_affinity_key
+ )
+ request.deploy_config.dedicated_resources.machine_spec.reservation_affinity.values = (
+ reservation_affinity_values
+ )
+
+ _LOGGER.info(f"Deploying custom model: {self._gcs_uri}")
+
+ try:
+ operation_future = self._model_garden_client.deploy(request)
+ _LOGGER.info(f"LRO: {operation_future.operation.name}")
+ deploy_response = operation_future.result(
+ timeout=deploy_request_timeout or _DEFAULT_TIMEOUT
+ )
+ _LOGGER.info(f"End time: {datetime.datetime.now()}")
+ self._endpoint_name = deploy_response.endpoint
+ _LOGGER.info(f"Endpoint: {self._endpoint_name}")
+ endpoint = aiplatform.Endpoint._construct_sdk_resource_from_gapic(
+ aiplatform_models.gca_endpoint_compat.Endpoint(
+ name=self._endpoint_name
+ ),
+ )
+ return endpoint
+ except ValueError as e:
+ _LOGGER.error(f"Failed to deploy custom model: {e}")
+ raise e
+
+
+class PartnerModel:
+ """Represents a Model Garden Partner model."""
+
+ def __init__(
+ self,
+ model_name: str,
+ ):
+ r"""Initializes a Model Garden partner model.
+
+ Usage:
+
+ ```
+ model = PartnerModel("publishers/ai21/models/jamba-large-1.6@001")
+ ```
+
+ Args:
+ model_name: Model Garden model resource name in the format of
+ `publishers/{publisher}/models/{model}@{version}`, or a simplified
+ resource name in the format of `{publisher}/{model}@{version}`.
+ """
+ project = initializer.global_config.project
+ location = initializer.global_config.location
+ credentials = initializer.global_config.credentials
+
+ self._model_name = model_name
+ self._publisher_model_name = _reconcile_model_name(model_name)
+ self._project = project
+ self._location = location
+ self._credentials = credentials
+
+ @functools.cached_property
+ def _model_garden_client(
+ self,
+ ) -> model_garden_service.ModelGardenServiceClient:
+ """Returns the Model Garden client."""
+ return initializer.global_config.create_client(
+ client_class=_ModelGardenClientWithOverride,
+ credentials=self._credentials,
+ location_override=self._location,
+ )
+
+ def deploy(
+ self,
+ machine_type: Optional[str] = None,
+ min_replica_count: int = 1,
+ max_replica_count: int = 1,
+ accelerator_type: Optional[str] = None,
+ accelerator_count: Optional[int] = None,
+ endpoint_display_name: Optional[str] = None,
+ model_display_name: Optional[str] = None,
+ deploy_request_timeout: Optional[float] = None,
+ ) -> aiplatform.Endpoint:
+ """Deploys an Open Model to an endpoint.
+
+ Args:
+ machine_type (str): Optional. The type of machine. Not specifying
+ machine type will result in model to be deployed with automatic
+ resources.
+ min_replica_count (int): Optional. The minimum number of machine
+ replicas this deployed model will be always deployed on. If traffic
+ against it increases, it may dynamically be deployed onto more
+ replicas, and as traffic decreases, some of these extra replicas may
+ be freed.
+ max_replica_count (int): Optional. The maximum number of replicas this
+ deployed model may be deployed on when the traffic against it
+ increases. If requested value is too large, the deployment will error,
+ but if deployment succeeds then the ability to scale the model to that
+ many replicas is guaranteed (barring service outages). If traffic
+ against the deployed model increases beyond what its replicas at
+ maximum may handle, a portion of the traffic will be dropped. If this
+ value is not provided, the larger value of min_replica_count or 1 will
+ be used. If value provided is smaller than min_replica_count, it will
+ automatically be increased to be min_replica_count.
+ accelerator_type (str): Optional. Hardware accelerator type. Must also
+ set accelerator_count if used. One of ACCELERATOR_TYPE_UNSPECIFIED,
+ NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100,
+ NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
+ accelerator_count (int): Optional. The number of accelerators to attach
+ to a worker replica.
+ endpoint_display_name: The display name of the created endpoint.
+ model_display_name: The display name of the uploaded model.
+ deploy_request_timeout: The timeout for the deploy request. Default is 2
+ hours.
+
+ Returns:
+ endpoint (aiplatform.Endpoint):
+ Created endpoint.
+ """
+ request = types.DeployRequest(
+ destination=f"projects/{self._project}/locations/{self._location}",
+ )
+ request.publisher_model_name = self._publisher_model_name
+
+ if endpoint_display_name:
+ request.endpoint_config.endpoint_display_name = endpoint_display_name
+ if model_display_name:
+ request.model_config.model_display_name = model_display_name
+
+ provided_custom_machine_spec = (
+ machine_type or accelerator_type or accelerator_count
+ )
+ if provided_custom_machine_spec:
+ dedicated_resources = types.DedicatedResources(
+ machine_spec=types.MachineSpec(
+ machine_type=machine_type,
+ accelerator_type=accelerator_type,
+ accelerator_count=accelerator_count,
+ ),
+ min_replica_count=min_replica_count,
+ max_replica_count=max_replica_count,
+ )
+ request.deploy_config.dedicated_resources = dedicated_resources
+
+ _LOGGER.info(f"Deploying model: {self._model_name}")
+
+ operation_future = self._model_garden_client.deploy(request)
+ _LOGGER.info(f"LRO: {operation_future.operation.name}")
+
+ _LOGGER.info(f"Start time: {datetime.datetime.now()}")
+ deploy_response = operation_future.result(
+ timeout=deploy_request_timeout or _DEFAULT_TIMEOUT
+ )
+ _LOGGER.info(f"End time: {datetime.datetime.now()}")
+
+ self._endpoint_name = deploy_response.endpoint
+ _LOGGER.info(f"Endpoint: {self._endpoint_name}")
+ endpoint = aiplatform.Endpoint._construct_sdk_resource_from_gapic(
+ aiplatform_models.gca_endpoint_compat.Endpoint(name=self._endpoint_name),
+ )
+ return endpoint
+
+
+class Model:
+ """Represents a Model Garden model."""
+
+ def __init__(
+ self,
+ model_name: Optional[str] = None,
+ ):
+ r"""Initializes a Model Garden model.
+
+ Usage:
+
+ ```
+ model = Model("publishers/google/models/gemma3@gemma-3-27b-it")
+ model = Model("google/gemma3@gemma-3-27b-it")
+ model = Model("deepseek-ai/DeepSeek-V3-0324")
+ model = Model("gs://fine-tuning-output/node-0/checkpoints/final")
+ model = Model("projects/123/locations/us-central1/models/456")
+ ```
+
+ Args:
+ model_name: Name of the model artifact.
+
+ It can be:
+ 1. A pretrained model
+ 1.1 Model Garden model resource name in the format of
+ `publishers/{publisher}/models/{model}@{version}`, or
+ 1.2 a simplified resource name in the format of `{publisher}/{model}@{version}`, or
+ 1.3 a Hugging Face model ID in the format of `{organization}/{model}`.
+ 2. A custom model weights like gs://fine-tuning-output/node-0/checkpoints/final
+ 3. A Model Registry model like projects/123/locations/us-central1/models/456
+ """
+ if not model_name:
+ raise ValueError("model_name must be specified.")
+
+ if re.match(r"^gs://", model_name):
+ self._model = CustomModel(gcs_uri=model_name)
+ elif re.match(r"^projects/.*/locations/.*/models/.*", model_name):
+ raise NotImplementedError("Model Registry models are not supported yet.")
+ else:
+ self._model = OpenModel(model_name)
+
+ def deploy(
+ self,
+ **kwargs,
+ ) -> aiplatform.Endpoint:
+ """Deploys the model to an endpoint."""
+ return self._model.deploy(**kwargs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..26dad00a3bc8d3a900edb6b47631c7f90d429bce
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The agentplatform.preview module."""
\ No newline at end of file
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa481f86eee82a471e5a34f1dfbec61bf9110ded
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__pycache__/model_garden.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__pycache__/model_garden.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ecaefe0d937ed5650bb0bfe0d1797dbd57b105a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/__pycache__/model_garden.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/model_garden.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/model_garden.py
new file mode 100644
index 0000000000000000000000000000000000000000..870104ec73dd3973819307eafd9c08a370f519b6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/model_garden.py
@@ -0,0 +1,31 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Classes and functions for working with Model Garden."""
+
+# pylint: disable=g-multiple-import,g-importing-member
+from agentplatform.model_garden._model_garden import (
+ Model,
+ CustomModel,
+ OpenModel,
+ list_deployable_models,
+)
+
+
+__all__ = (
+ "Model",
+ "CustomModel",
+ "OpenModel",
+ "list_deployable_models",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..282fc65523538b550a06399ce085581ca9e0efc0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__init__.py
@@ -0,0 +1,169 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from agentplatform.preview.rag.rag_data import (
+ batch_create_data_schemas,
+ batch_create_metadata,
+ batch_delete_data_schemas,
+ batch_delete_metadata,
+ create_corpus,
+ delete_corpus,
+ delete_file,
+ get_corpus,
+ get_file,
+ get_rag_engine_config,
+ import_files,
+ import_files_async,
+ list_corpora,
+ list_data_schemas,
+ list_files,
+ list_metadata,
+ update_corpus,
+ update_metadata,
+ update_rag_engine_config,
+ upload_file,
+)
+from agentplatform.preview.rag.rag_retrieval import (
+ ask_contexts,
+ async_retrieve_contexts,
+ retrieval_query,
+)
+from agentplatform.preview.rag.rag_store import (
+ Retrieval,
+ VertexRagStore,
+)
+from agentplatform.preview.rag.utils.resources import (
+ ANN,
+ Basic,
+ ChunkingConfig,
+ DocumentCorpus,
+ EmbeddingModelConfig,
+ Filter,
+ HybridSearch,
+ JiraQuery,
+ JiraSource,
+ KNN,
+ LayoutParserConfig,
+ LlmParserConfig,
+ LlmRanker,
+ MemoryCorpus,
+ MetadataValue,
+ Pinecone,
+ RagCorpus,
+ RagCorpusTypeConfig,
+ RagDataSchema,
+ RagEmbeddingModelConfig,
+ RagEngineConfig,
+ RagFile,
+ RagManagedDb,
+ RagManagedDbConfig,
+ RagManagedVertexVectorSearch,
+ RagMetadata,
+ RagMetadataSchemaDetails,
+ RagResource,
+ RagRetrievalConfig,
+ RagVectorDbConfig,
+ RankService,
+ Ranking,
+ Scaled,
+ Serverless,
+ SharePointSource,
+ SharePointSources,
+ SlackChannel,
+ SlackChannelsSource,
+ Spanner,
+ TransformationConfig,
+ Unprovisioned,
+ UserSpecifiedMetadata,
+ VertexAiSearchConfig,
+ VertexFeatureStore,
+ VertexPredictionEndpoint,
+ VertexVectorSearch,
+ Weaviate,
+)
+
+__all__ = (
+ "ANN",
+ "Basic",
+ "ChunkingConfig",
+ "DocumentCorpus",
+ "EmbeddingModelConfig",
+ "Filter",
+ "HybridSearch",
+ "JiraQuery",
+ "JiraSource",
+ "KNN",
+ "LayoutParserConfig",
+ "LlmParserConfig",
+ "LlmRanker",
+ "MemoryCorpus",
+ "MetadataValue",
+ "Pinecone",
+ "RagEngineConfig",
+ "RagCorpus",
+ "RagCorpusTypeConfig",
+ "RagDataSchema",
+ "RagEmbeddingModelConfig",
+ "RagFile",
+ "RagManagedDb",
+ "RagManagedDbConfig",
+ "RagManagedVertexVectorSearch",
+ "RagMetadata",
+ "RagMetadataSchemaDetails",
+ "RagResource",
+ "RagRetrievalConfig",
+ "RagVectorDbConfig",
+ "Ranking",
+ "RankService",
+ "Retrieval",
+ "Scaled",
+ "Serverless",
+ "SharePointSource",
+ "SharePointSources",
+ "SlackChannel",
+ "SlackChannelsSource",
+ "Spanner",
+ "TransformationConfig",
+ "Unprovisioned",
+ "UserSpecifiedMetadata",
+ "VertexAiSearchConfig",
+ "VertexFeatureStore",
+ "VertexPredictionEndpoint",
+ "VertexRagStore",
+ "VertexVectorSearch",
+ "Weaviate",
+ "ask_contexts",
+ "batch_create_data_schemas",
+ "batch_create_metadata",
+ "batch_delete_data_schemas",
+ "batch_delete_metadata",
+ "create_corpus",
+ "delete_corpus",
+ "delete_file",
+ "get_corpus",
+ "get_file",
+ "import_files",
+ "import_files_async",
+ "list_corpora",
+ "list_data_schemas",
+ "list_files",
+ "list_metadata",
+ "retrieval_query",
+ "async_retrieve_contexts",
+ "upload_file",
+ "update_corpus",
+ "update_metadata",
+ "update_rag_engine_config",
+ "get_rag_engine_config",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94bb37170cc5c42bae5779f0166204cc875a7b1f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_data.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_data.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ade46d8b8b170600b61e251ab9bfeabceb543160
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_data.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_retrieval.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_retrieval.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..925ec76b4cea7cb9b486dea75a5e6c2396e02f1b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_retrieval.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69f1d96a41602900a8fa193bcf53dc62a75814d8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/__pycache__/rag_store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_data.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb9a2248f4b49d844e892d07d70098238bb3997c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_data.py
@@ -0,0 +1,1235 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""RAG data management SDK."""
+#
+from typing import Optional, Sequence, Union
+from google import auth
+from google.api_core import operation_async
+from google.auth.transport import requests as google_auth_requests
+from google.cloud import aiplatform
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform import utils
+from google.cloud.aiplatform_v1beta1 import (
+ BatchCreateRagDataSchemasRequest,
+ BatchCreateRagMetadataRequest,
+ BatchDeleteRagDataSchemasRequest,
+ BatchDeleteRagMetadataRequest,
+ CreateRagCorpusRequest,
+ CreateRagDataSchemaRequest,
+ CreateRagMetadataRequest,
+ DeleteRagCorpusRequest,
+ DeleteRagFileRequest,
+ GetRagCorpusRequest,
+ GetRagEngineConfigRequest,
+ GetRagFileRequest,
+ ImportRagFilesResponse,
+ ListRagCorporaRequest,
+ ListRagDataSchemasRequest,
+ ListRagFilesRequest,
+ ListRagMetadataRequest,
+ RagCorpus as GapicRagCorpus,
+ UpdateRagCorpusRequest,
+ UpdateRagEngineConfigRequest,
+ UpdateRagMetadataRequest,
+)
+from google.cloud.aiplatform_v1beta1.services.vertex_rag_data_service.pagers import (
+ ListRagCorporaPager,
+ ListRagDataSchemasPager,
+ ListRagFilesPager,
+ ListRagMetadataPager,
+)
+from google.cloud.aiplatform_v1beta1.types import EncryptionSpec
+from agentplatform.preview.rag.utils import (
+ _gapic_utils,
+)
+from agentplatform.preview.rag.utils.resources import (
+ EmbeddingModelConfig,
+ JiraSource,
+ LayoutParserConfig,
+ LlmParserConfig,
+ Pinecone,
+ RagCorpus,
+ RagCorpusTypeConfig,
+ RagDataSchema,
+ RagEngineConfig,
+ RagFile,
+ RagManagedDb,
+ RagManagedVertexVectorSearch,
+ RagMetadata,
+ RagVectorDbConfig,
+ SharePointSources,
+ SlackChannelsSource,
+ TransformationConfig,
+ VertexAiSearchConfig,
+ VertexFeatureStore,
+ VertexVectorSearch,
+ Weaviate,
+)
+
+
+def create_corpus(
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ corpus_type_config: Optional[RagCorpusTypeConfig] = None,
+ vertex_ai_search_config: Optional[VertexAiSearchConfig] = None,
+ backend_config: Optional[RagVectorDbConfig] = None,
+ encryption_spec: Optional[EncryptionSpec] = None,
+ timeout: int = 600,
+) -> RagCorpus:
+ """Creates a new RagCorpus resource.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+
+ agentplatform.init(project="my-project")
+
+ rag_corpus = rag.create_corpus(
+ display_name="my-corpus-1",
+ )
+ ```
+
+ Args:
+ display_name: If not provided, SDK will create one. The display name of
+ the RagCorpus. The name can be up to 128 characters long and can consist
+ of any UTF-8 characters.
+ description: The description of the RagCorpus.
+ corpus_type_config: The corpus type config of the RagCorpus.
+ vertex_ai_search_config: The Vertex AI Search config of the RagCorpus.
+ backend_config: The backend config of the RagCorpus. It can specify a
+ Vector DB and/or the embedding model config.
+ encryption_spec: The encryption spec of the RagCorpus.
+ timeout: Default is 600 seconds.
+
+ Returns:
+ RagCorpus.
+ Raises:
+ RuntimeError: Failed in RagCorpus creation due to exception.
+ RuntimeError: Failed in RagCorpus creation due to operation error.
+ """
+ if not display_name:
+ display_name = "vertex-" + utils.timestamped_unique_name()
+ parent = initializer.global_config.common_location_path(project=None, location=None)
+
+ rag_corpus = GapicRagCorpus(display_name=display_name, description=description)
+
+ if corpus_type_config:
+ _gapic_utils.set_corpus_type_config(
+ corpus_type_config=corpus_type_config,
+ rag_corpus=rag_corpus,
+ )
+
+ if vertex_ai_search_config and backend_config:
+ raise ValueError(
+ "Only one of vertex_ai_search_config or backend_config can be set."
+ )
+
+ if backend_config:
+ _gapic_utils.set_backend_config(
+ backend_config=backend_config,
+ rag_corpus=rag_corpus,
+ )
+
+ if vertex_ai_search_config:
+ _gapic_utils.set_vertex_ai_search_config(
+ vertex_ai_search_config=vertex_ai_search_config,
+ rag_corpus=rag_corpus,
+ )
+ else:
+ _gapic_utils.set_vector_db(
+ vector_db=None,
+ rag_corpus=rag_corpus,
+ )
+
+ if encryption_spec:
+ _gapic_utils.set_encryption_spec(
+ encryption_spec=encryption_spec,
+ rag_corpus=rag_corpus,
+ )
+
+ request = CreateRagCorpusRequest(
+ parent=parent,
+ rag_corpus=rag_corpus,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+
+ try:
+ response = client.create_rag_corpus(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagCorpus creation due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_corpus(response.result(timeout=timeout))
+
+
+def update_corpus(
+ corpus_name: str,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ vector_db: Optional[
+ Union[
+ Weaviate,
+ VertexFeatureStore,
+ VertexVectorSearch,
+ Pinecone,
+ RagManagedDb,
+ ]
+ ] = None,
+ vertex_ai_search_config: Optional[VertexAiSearchConfig] = None,
+ backend_config: Optional[RagVectorDbConfig] = None,
+ timeout: int = 600,
+) -> RagCorpus:
+ """Updates a RagCorpus resource.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+
+ agentplatform.init(project="my-project")
+
+ rag_corpus = rag.update_corpus(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ display_name="my-corpus-1",
+ )
+ ```
+
+ Args:
+ corpus_name: The name of the RagCorpus resource to update. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`` or
+ ``{rag_corpus}``.
+ display_name: If not provided, the display name will not be updated. The
+ display name of the RagCorpus. The name can be up to 128 characters long
+ and can consist of any UTF-8 characters.
+ description: The description of the RagCorpus. If not provided, the
+ description will not be updated.
+ vector_db: The vector db config of the RagCorpus. If not provided, the
+ vector db will not be updated.
+ vertex_ai_search_config: The Vertex AI Search config of the RagCorpus. If
+ not provided, the Vertex AI Search config will not be updated.
+ Note: embedding_model_config or vector_db cannot be set if
+ vertex_ai_search_config is specified.
+ backend_config: The backend config of the RagCorpus. Specifies a Vector DB
+ and/or the embedding model config.
+ timeout: Default is 600 seconds.
+
+ Returns:
+ RagCorpus.
+ Raises:
+ RuntimeError: Failed in RagCorpus update due to exception.
+ RuntimeError: Failed in RagCorpus update due to operation error.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ if display_name and description:
+ rag_corpus = GapicRagCorpus(
+ name=corpus_name, display_name=display_name, description=description
+ )
+ elif display_name:
+ rag_corpus = GapicRagCorpus(name=corpus_name, display_name=display_name)
+ elif description:
+ rag_corpus = GapicRagCorpus(name=corpus_name, description=description)
+ else:
+ rag_corpus = GapicRagCorpus(name=corpus_name)
+
+ if vertex_ai_search_config and vector_db:
+ raise ValueError("Only one of vertex_ai_search_config or vector_db can be set.")
+
+ if backend_config:
+ _gapic_utils.set_backend_config(
+ backend_config=backend_config,
+ rag_corpus=rag_corpus,
+ )
+
+ if vertex_ai_search_config:
+ _gapic_utils.set_vertex_ai_search_config(
+ vertex_ai_search_config=vertex_ai_search_config,
+ rag_corpus=rag_corpus,
+ )
+ else:
+ _gapic_utils.set_vector_db(
+ vector_db=vector_db,
+ rag_corpus=rag_corpus,
+ )
+
+ request = UpdateRagCorpusRequest(
+ rag_corpus=rag_corpus,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+
+ try:
+ response = client.update_rag_corpus(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagCorpus update due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_corpus_no_embedding_model_config(
+ response.result(timeout=timeout)
+ )
+
+
+def get_corpus(name: str) -> RagCorpus:
+ """
+ Get an existing RagCorpus.
+
+ Args:
+ name: An existing RagCorpus resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ Returns:
+ RagCorpus.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(name)
+ request = GetRagCorpusRequest(name=corpus_name)
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.get_rag_corpus(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in getting the RagCorpus due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_corpus(response)
+
+
+def list_corpora(
+ page_size: Optional[int] = None, page_token: Optional[str] = None
+) -> ListRagCorporaPager:
+ """
+ List all RagCorpora in the same project and location.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+
+ agentplatform.init(project="my-project")
+
+ # List all corpora.
+ rag_corpora = list(rag.list_corpora())
+
+ # Alternatively, return a ListRagCorporaPager.
+ pager_1 = rag.list_corpora(page_size=10)
+ # Then get the next page, use the generated next_page_token from the last pager.
+ pager_2 = rag.list_corpora(page_size=10, page_token=pager_1.next_page_token)
+
+ ```
+ Args:
+ page_size: The standard list page size. Leaving out the page_size
+ causes all of the results to be returned.
+ page_token: The standard list page token.
+
+ Returns:
+ ListRagCorporaPager.
+ """
+ parent = initializer.global_config.common_location_path(project=None, location=None)
+ request = ListRagCorporaRequest(
+ parent=parent,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ pager = client.list_rag_corpora(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in listing the RagCorpora due to: ", e) from e
+
+ return pager
+
+
+def delete_corpus(name: str) -> None:
+ """
+ Delete an existing RagCorpus.
+
+ Args:
+ name: An existing RagCorpus resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(name)
+ request = DeleteRagCorpusRequest(name=corpus_name)
+
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ client.delete_rag_corpus(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagCorpus deletion due to: ", e) from e
+ return None
+
+
+def upload_file(
+ corpus_name: str,
+ path: Union[str, Sequence[str]],
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ transformation_config: Optional[TransformationConfig] = None,
+) -> RagFile:
+ """
+ Synchronous file upload to an existing RagCorpus.
+
+ Example usage:
+
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+
+ agentplatform.init(project="my-project")
+
+ # Optional.
+ transformation_config = TransformationConfig(
+ chunking_config=ChunkingConfig(
+ chunk_size=1024,
+ chunk_overlap=200,
+ ),
+ )
+
+ rag_file = rag.upload_file(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ display_name="my_file.txt",
+ path="usr/home/my_file.txt",
+ transformation_config=transformation_config,
+ )
+ ```
+
+ Args:
+ corpus_name: The name of the RagCorpus resource into which to upload the file.
+ Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ path: A local file path. For example,
+ "usr/home/my_file.txt".
+ display_name: The display name of the data file.
+ description: The description of the RagFile.
+ transformation_config: The config for transforming the RagFile, such as chunking.
+ Returns:
+ RagFile.
+ Raises:
+ RuntimeError: Failed in RagFile upload.
+ ValueError: RagCorpus is not found.
+ RuntimeError: Failed in indexing the RagFile.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ location = initializer.global_config.location
+ # GAPIC doesn't expose a path (scotty). Use requests API instead
+ if display_name is None:
+ display_name = "vertex-" + utils.timestamped_unique_name()
+ headers = {"X-Goog-Upload-Protocol": "multipart"}
+ if not initializer.global_config.api_endpoint:
+ request_endpoint = "{}-{}".format(
+ location, aiplatform.constants.base.API_BASE_PATH
+ )
+ else:
+ request_endpoint = initializer.global_config.api_endpoint
+ upload_request_uri = "https://{}/upload/v1beta1/{}/ragFiles:upload".format(
+ request_endpoint,
+ corpus_name,
+ )
+ js_rag_file = {"rag_file": {"display_name": display_name}}
+
+ if description:
+ js_rag_file["rag_file"]["description"] = description
+
+ if transformation_config and transformation_config.chunking_config:
+ chunk_size = transformation_config.chunking_config.chunk_size
+ chunk_overlap = transformation_config.chunking_config.chunk_overlap
+ js_rag_file["upload_rag_file_config"] = {
+ "rag_file_transformation_config": {
+ "rag_file_chunking_config": {
+ "fixed_length_chunking": {
+ "chunk_size": chunk_size,
+ "chunk_overlap": chunk_overlap,
+ }
+ }
+ }
+ }
+ files = {
+ "metadata": (None, str(js_rag_file)),
+ "file": open(path, "rb"),
+ }
+ credentials, _ = auth.default(
+ scopes=["https://www.googleapis.com/auth/cloud-platform"]
+ )
+ authorized_session = google_auth_requests.AuthorizedSession(credentials=credentials)
+ try:
+ response = authorized_session.post(
+ url=upload_request_uri,
+ files=files,
+ headers=headers,
+ )
+ except Exception as e:
+ raise RuntimeError("Failed in uploading the RagFile due to: ", e) from e
+
+ if response.status_code == 404:
+ raise ValueError(
+ "RagCorpus '%s' is not found: %s", corpus_name, upload_request_uri
+ )
+ if response.json().get("error"):
+ raise RuntimeError(
+ "Failed in indexing the RagFile due to: ", response.json().get("error")
+ )
+ return _gapic_utils.convert_json_to_rag_file(response.json())
+
+
+def import_files(
+ corpus_name: str,
+ paths: Optional[Sequence[str]] = None,
+ source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
+ transformation_config: Optional[TransformationConfig] = None,
+ timeout: int = 600,
+ max_embedding_requests_per_min: int = 1000,
+ global_max_embedding_requests_per_min: Optional[int] = None,
+ layout_parser: Optional[LayoutParserConfig] = None,
+ llm_parser: Optional[LlmParserConfig] = None,
+ rebuild_ann_index: Optional[bool] = False,
+) -> ImportRagFilesResponse:
+ """
+ Import files to an existing RagCorpus, wait until completion.
+
+ Example usage:
+
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+ from google.protobuf import timestamp_pb2
+
+ agentplatform.init(project="my-project")
+ # Google Drive example
+ paths = [
+ "https://drive.google.com/file/d/123",
+ "https://drive.google.com/drive/folders/456"
+ ]
+ # Google Cloud Storage example
+ paths = ["gs://my_bucket/my_files_dir", ...]
+
+ transformation_config = TransformationConfig(
+ chunking_config=ChunkingConfig(
+ chunk_size=1024,
+ chunk_overlap=200,
+ ),
+ )
+
+ response = rag.import_files(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ paths=paths,
+ transformation_config=transformation_config,
+ )
+
+ # Slack example
+ start_time = timestamp_pb2.Timestamp()
+ start_time.FromJsonString('2020-12-31T21:33:44Z')
+ end_time = timestamp_pb2.Timestamp()
+ end_time.GetCurrentTime()
+ source = rag.SlackChannelsSource(
+ channels = [
+ SlackChannel("channel1", "api_key1"),
+ SlackChannel("channel2", "api_key2", start_time, end_time)
+ ],
+ )
+ # Jira Example
+ jira_query = rag.JiraQuery(
+ email="xxx@yyy.com",
+ jira_projects=["project1", "project2"],
+ custom_queries=["query1", "query2"],
+ api_key="api_key",
+ server_uri="server.atlassian.net"
+ )
+ source = rag.JiraSource(
+ queries=[jira_query],
+ )
+
+ response = rag.import_files(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ source=source,
+ transformation_config=transformation_config,
+ )
+
+ # SharePoint Example.
+ sharepoint_query = rag.SharePointSource(
+ sharepoint_folder_path="https://my-sharepoint-site.com/my-folder",
+ sharepoint_site_name="my-sharepoint-site.com",
+ client_id="my-client-id",
+ client_secret="my-client-secret",
+ tenant_id="my-tenant-id",
+ drive_id="my-drive-id",
+ )
+ source = rag.SharePointSources(
+ share_point_sources=[sharepoint_query],
+ )
+
+ # Return the number of imported RagFiles after completion.
+ print(response.imported_rag_files_count)
+
+ ```
+ Args:
+ corpus_name: The name of the RagCorpus resource into which to import files.
+ Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ paths: A list of uris. Eligible uris will be Google Cloud Storage
+ directory ("gs://my-bucket/my_dir") or a Google Drive url for file
+ (https://drive.google.com/file/... or folder
+ "https://drive.google.com/corp/drive/folders/...").
+ source: The source of the Slack or Jira import.
+ Must be either a SlackChannelsSource or JiraSource.
+ transformation_config: The config for transforming the imported
+ RagFiles.
+ max_embedding_requests_per_min:
+ Optional. The max number of queries per
+ minute that this job is allowed to make to the
+ embedding model specified on the corpus. This
+ value is specific to this job and not shared
+ across other import jobs. Consult the Quotas
+ page on the project to set an appropriate value
+ here. If unspecified, a default value of 1,000
+ QPM would be used.
+ global_max_embedding_requests_per_min:
+ Optional. The max number of queries per minute that the indexing
+ pipeline job is allowed to make to the embedding model specified in
+ the project. Please follow the quota usage guideline of the embedding
+ model you use to set the value properly. If this value is not specified,
+ max_embedding_requests_per_min will be used by indexing pipeline job
+ as the global limit and this means parallel import jobs are not allowed.
+ timeout: Default is 600 seconds.
+ layout_parser: Configuration for the Document AI Layout Parser Processor
+ to use for document parsing. Optional.
+ If not None, the other parser configs must be None.
+ llm_parser: Configuration for the LLM Parser to use for document parsing.
+ Optional.
+ If not None, the other parser configs must be None.
+ rebuild_ann_index: Rebuilds the ANN index to optimize for recall on the
+ imported data. Only applicable for RagCorpora running on
+ RagManagedDb with ``retrieval_strategy`` set to ``ANN``. The
+ rebuild will be performed using the existing ANN config set
+ on the RagCorpus. To change the ANN config, please use the
+ UpdateRagCorpus API. Optional.Default is false, i.e., index is not
+ rebuilt.
+ Returns:
+ ImportRagFilesResponse.
+ """
+ if source is not None and paths is not None:
+ raise ValueError("Only one of source or paths must be passed in at a time")
+ if source is None and paths is None:
+ raise ValueError("One of source or paths must be passed in")
+ if layout_parser is not None and llm_parser is not None:
+ raise ValueError(
+ "Only one of layout_parser or llm_parser may be passed in at a time"
+ )
+
+ rebuild_ann_index_request = (
+ rebuild_ann_index if rebuild_ann_index is not None else False
+ )
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ request = _gapic_utils.prepare_import_files_request(
+ corpus_name=corpus_name,
+ paths=paths,
+ source=source,
+ chunk_size=1024,
+ chunk_overlap=200,
+ transformation_config=transformation_config,
+ max_embedding_requests_per_min=max_embedding_requests_per_min,
+ global_max_embedding_requests_per_min=global_max_embedding_requests_per_min,
+ use_advanced_pdf_parsing=False,
+ layout_parser=layout_parser,
+ llm_parser=llm_parser,
+ rebuild_ann_index=rebuild_ann_index_request,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.import_rag_files(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in importing the RagFiles due to: ", e) from e
+
+ return response.result(timeout=timeout)
+
+
+async def import_files_async(
+ corpus_name: str,
+ paths: Optional[Sequence[str]] = None,
+ source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
+ transformation_config: Optional[TransformationConfig] = None,
+ max_embedding_requests_per_min: int = 1000,
+ global_max_embedding_requests_per_min: Optional[int] = None,
+ layout_parser: Optional[LayoutParserConfig] = None,
+ llm_parser: Optional[LlmParserConfig] = None,
+ rebuild_ann_index: Optional[bool] = False,
+) -> operation_async.AsyncOperation:
+ """
+ Import files to an existing RagCorpus asynchronously.
+
+ Example usage:
+
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+ from google.protobuf import timestamp_pb2
+
+ agentplatform.init(project="my-project")
+
+ # Google Drive example
+ paths = [
+ "https://drive.google.com/file/d/123",
+ "https://drive.google.com/drive/folders/456"
+ ]
+ # Google Cloud Storage example
+ paths = ["gs://my_bucket/my_files_dir", ...]
+
+ transformation_config = TransformationConfig(
+ chunking_config=ChunkingConfig(
+ chunk_size=1024,
+ chunk_overlap=200,
+ ),
+ )
+
+ response = await rag.import_files_async(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ paths=paths,
+ transformation_config=transformation_config,
+ )
+
+ # Slack example
+ start_time = timestamp_pb2.Timestamp()
+ start_time.FromJsonString('2020-12-31T21:33:44Z')
+ end_time = timestamp_pb2.Timestamp()
+ end_time.GetCurrentTime()
+ source = rag.SlackChannelsSource(
+ channels = [
+ SlackChannel("channel1", "api_key1"),
+ SlackChannel("channel2", "api_key2", start_time, end_time)
+ ],
+ )
+ # Jira Example
+ jira_query = rag.JiraQuery(
+ email="xxx@yyy.com",
+ jira_projects=["project1", "project2"],
+ custom_queries=["query1", "query2"],
+ api_key="api_key",
+ server_uri="server.atlassian.net"
+ )
+ source = rag.JiraSource(
+ queries=[jira_query],
+ )
+
+ response = await rag.import_files_async(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ source=source,
+ transformation_config=transformation_config,
+ )
+
+ # SharePoint Example.
+ sharepoint_query = rag.SharePointSource(
+ sharepoint_folder_path="https://my-sharepoint-site.com/my-folder",
+ sharepoint_site_name="my-sharepoint-site.com",
+ client_id="my-client-id",
+ client_secret="my-client-secret",
+ tenant_id="my-tenant-id",
+ drive_id="my-drive-id",
+ )
+ source = rag.SharePointSources(
+ share_point_sources=[sharepoint_query],
+ )
+
+ # Get the result.
+ await response.result()
+
+ ```
+ Args:
+ corpus_name: The name of the RagCorpus resource into which to import files.
+ Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ paths: A list of uris. Eligible uris will be Google Cloud Storage
+ directory ("gs://my-bucket/my_dir") or a Google Drive url for file
+ (https://drive.google.com/file/... or folder
+ "https://drive.google.com/corp/drive/folders/...").
+ source: The source of the Slack or Jira import.
+ Must be either a SlackChannelsSource or JiraSource.
+ transformation_config: The config for transforming the imported
+ RagFiles.
+ max_embedding_requests_per_min:
+ Optional. The max number of queries per
+ minute that this job is allowed to make to the
+ embedding model specified on the corpus. This
+ value is specific to this job and not shared
+ across other import jobs. Consult the Quotas
+ page on the project to set an appropriate value
+ here. If unspecified, a default value of 1,000
+ QPM would be used.
+ global_max_embedding_requests_per_min:
+ Optional. The max number of queries per minute that the indexing
+ pipeline job is allowed to make to the embedding model specified in
+ the project. Please follow the quota usage guideline of the embedding
+ model you use to set the value properly. If this value is not specified,
+ max_embedding_requests_per_min will be used by indexing pipeline job
+ as the global limit and this means parallel import jobs are not allowed.
+ layout_parser: Configuration for the Document AI Layout Parser Processor
+ to use for document parsing. Optional.
+ If not None, the other parser configs must be None.
+ llm_parser: Configuration for the LLM Parser to use for document parsing.
+ Optional.
+ If not None, the other parser configs must be None.
+ rebuild_ann_index: Rebuilds the ANN index to optimize for recall on the
+ imported data. Only applicable for RagCorpora running on
+ RagManagedDb with ``retrieval_strategy`` set to ``ANN``. The
+ rebuild will be performed using the existing ANN config set
+ on the RagCorpus. To change the ANN config, please use the
+ UpdateRagCorpus API. Optional.Default is false, i.e., index is not
+ rebuilt.
+ Returns:
+ operation_async.AsyncOperation.
+ """
+ if source is not None and paths is not None:
+ raise ValueError("Only one of source or paths must be passed in at a time")
+ if source is None and paths is None:
+ raise ValueError("One of source or paths must be passed in")
+ if layout_parser is not None and llm_parser is not None:
+ raise ValueError(
+ "Only one of layout_parser or llm_parser may be passed in at a time"
+ )
+ rebuild_ann_index_request = (
+ rebuild_ann_index if rebuild_ann_index is not None else False
+ )
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ request = _gapic_utils.prepare_import_files_request(
+ corpus_name=corpus_name,
+ paths=paths,
+ source=source,
+ chunk_size=1024,
+ chunk_overlap=200,
+ transformation_config=transformation_config,
+ max_embedding_requests_per_min=max_embedding_requests_per_min,
+ global_max_embedding_requests_per_min=global_max_embedding_requests_per_min,
+ use_advanced_pdf_parsing=False,
+ layout_parser=layout_parser,
+ llm_parser=llm_parser,
+ rebuild_ann_index=rebuild_ann_index_request,
+ )
+ async_client = _gapic_utils.create_rag_data_service_async_client()
+ try:
+ response = await async_client.import_rag_files(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in importing the RagFiles due to: ", e) from e
+ return response
+
+
+def get_file(name: str, corpus_name: Optional[str] = None) -> RagFile:
+ """
+ Get an existing RagFile.
+
+ Args:
+ name: Either a full RagFile resource name must be provided, or a RagCorpus
+ name and a RagFile name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}``
+ or ``{rag_file}``.
+ corpus_name: If `name` is not a full resource name, an existing RagCorpus
+ name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ Returns:
+ RagFile.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ name = _gapic_utils.get_file_name(name, corpus_name)
+ request = GetRagFileRequest(name=name)
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.get_rag_file(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in getting the RagFile due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_file(response)
+
+
+def list_files(
+ corpus_name: str, page_size: Optional[int] = None, page_token: Optional[str] = None
+) -> ListRagFilesPager:
+ """
+ List all RagFiles in an existing RagCorpus.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+ # List all corpora.
+ rag_corpora = list(rag.list_corpora())
+
+ # List all files of the first corpus.
+ rag_files = list(rag.list_files(corpus_name=rag_corpora[0].name))
+
+ # Alternatively, return a ListRagFilesPager.
+ pager_1 = rag.list_files(
+ corpus_name=rag_corpora[0].name,
+ page_size=10
+ )
+ # Then get the next page, use the generated next_page_token from the last pager.
+ pager_2 = rag.list_files(
+ corpus_name=rag_corpora[0].name,
+ page_size=10,
+ page_token=pager_1.next_page_token
+ )
+
+ ```
+
+ Args:
+ corpus_name: An existing RagCorpus name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ page_size: The standard list page size. Leaving out the page_size
+ causes all of the results to be returned.
+ page_token: The standard list page token.
+ Returns:
+ ListRagFilesPager.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ request = ListRagFilesRequest(
+ parent=corpus_name,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ pager = client.list_rag_files(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in listing the RagFiles due to: ", e) from e
+
+ return pager
+
+
+def delete_file(name: str, corpus_name: Optional[str] = None) -> None:
+ """
+ Delete RagFile from an existing RagCorpus.
+
+ Args:
+ name: Either a full RagFile resource name must be provided, or a RagCorpus
+ name and a RagFile name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}``
+ or ``{rag_file}``.
+ corpus_name: If `name` is not a full resource name, an existing RagCorpus
+ name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ name = _gapic_utils.get_file_name(name, corpus_name)
+ request = DeleteRagFileRequest(name=name)
+
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ client.delete_rag_file(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagFile deletion due to: ", e) from e
+ return None
+
+
+def batch_create_data_schemas(
+ corpus_name: str,
+ requests: Sequence[RagDataSchema],
+ timeout: int = 600,
+) -> Sequence[RagDataSchema]:
+ """Batch creates RagDataSchema resources.
+
+ Args:
+ corpus_name: The name of the RagCorpus resource to create the
+ RagDataSchemas in. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`` or
+ ``{rag_corpus}``.
+ requests: The RagDataSchemas to create.
+ timeout: Default is 600 seconds.
+
+ Returns:
+ Sequence of RagDataSchema.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ gapic_requests = []
+ for request in requests:
+ gapic_requests.append(
+ CreateRagDataSchemaRequest(
+ parent=corpus_name,
+ rag_data_schema=_gapic_utils.convert_rag_data_schema_to_gapic(request),
+ )
+ )
+ request = BatchCreateRagDataSchemasRequest(
+ parent=corpus_name,
+ requests=gapic_requests,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.batch_create_rag_data_schemas(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagDataSchema batch creation due to: ", e) from e
+ result = response.result(timeout=timeout)
+ if result.rag_data_schemas:
+ return [
+ _gapic_utils.convert_gapic_to_rag_data_schema(schema)
+ for schema in result.rag_data_schemas
+ ]
+ return []
+
+
+def batch_delete_data_schemas(
+ corpus_name: str,
+ names: Sequence[str],
+ timeout: int = 600,
+) -> None:
+ """Batch deletes RagDataSchema resources.
+
+ Args:
+ corpus_name: The name of the RagCorpus resource from which to delete the
+ RagDataSchemas. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`` or
+ ``{rag_corpus}``.
+ names: The RagDataSchema resource names to delete.
+ timeout: Default is 600 seconds.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ full_names = [
+ _gapic_utils.get_data_schema_name(name, corpus_name) for name in names
+ ]
+ request = BatchDeleteRagDataSchemasRequest(
+ parent=corpus_name,
+ names=full_names,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.batch_delete_rag_data_schemas(request=request)
+ response.result(timeout=timeout)
+ except Exception as e:
+ raise RuntimeError("Failed in RagDataSchema batch deletion due to: ", e) from e
+ return None
+
+
+def list_data_schemas(
+ corpus_name: str,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+) -> ListRagDataSchemasPager:
+ """Lists RagDataSchemas in an existing RagCorpus.
+
+ Args:
+ corpus_name: An existing RagCorpus name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`` or
+ ``{rag_corpus}``.
+ page_size: The standard list page size.
+ page_token: The standard list page token.
+
+ Returns:
+ ListRagDataSchemasPager.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ request = ListRagDataSchemasRequest(
+ parent=corpus_name,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ pager = client.list_rag_data_schemas(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in listing the RagDataSchemas due to: ", e) from e
+ return pager
+
+
+def batch_create_metadata(
+ corpus_name: str,
+ file_name: str,
+ requests: Sequence[RagMetadata],
+ timeout: int = 600,
+) -> Sequence[RagMetadata]:
+ """Batch creates RagMetadata resources.
+
+ Args:
+ corpus_name: The name of the RagCorpus resource.
+ file_name: The name of the RagFile resource.
+ requests: The RagMetadata to create.
+ timeout: Default is 600 seconds.
+
+ Returns:
+ Sequence of RagMetadata.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ file_name = _gapic_utils.get_file_name(file_name, corpus_name)
+ gapic_requests = []
+ for request in requests:
+ gapic_requests.append(
+ CreateRagMetadataRequest(
+ parent=file_name,
+ rag_metadata=_gapic_utils.convert_rag_metadata_to_gapic(request),
+ )
+ )
+ request = BatchCreateRagMetadataRequest(
+ parent=file_name,
+ requests=gapic_requests,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.batch_create_rag_metadata(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagMetadata batch creation due to: ", e) from e
+ result = response.result(timeout=timeout)
+ if result.rag_metadata:
+ return [
+ _gapic_utils.convert_gapic_to_rag_metadata(metadata)
+ for metadata in result.rag_metadata
+ ]
+ return []
+
+
+def batch_delete_metadata(
+ corpus_name: str,
+ file_name: str,
+ names: Sequence[str],
+ timeout: int = 600,
+) -> None:
+ """Batch deletes RagMetadata resources.
+
+ Args:
+ corpus_name: The name of the RagCorpus resource.
+ file_name: The name of the RagFile resource.
+ names: The RagMetadata resource names to delete.
+ timeout: Default is 600 seconds.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ file_name = _gapic_utils.get_file_name(file_name, corpus_name)
+ full_names = [
+ _gapic_utils.get_metadata_name(name, corpus_name, file_name) for name in names
+ ]
+ request = BatchDeleteRagMetadataRequest(
+ parent=file_name,
+ names=full_names,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.batch_delete_rag_metadata(request=request)
+ response.result(timeout=timeout)
+ except Exception as e:
+ raise RuntimeError("Failed in RagMetadata batch deletion due to: ", e) from e
+ return None
+
+
+def list_metadata(
+ corpus_name: str,
+ file_name: str,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+) -> ListRagMetadataPager:
+ """Lists RagMetadata in an existing RagFile.
+
+ Args:
+ corpus_name: An existing RagCorpus name.
+ file_name: An existing RagFile name.
+ page_size: The standard list page size.
+ page_token: The standard list page token.
+
+ Returns:
+ ListRagMetadataPager.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ file_name = _gapic_utils.get_file_name(file_name, corpus_name)
+ request = ListRagMetadataRequest(
+ parent=file_name,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ pager = client.list_rag_metadata(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in listing the RagMetadata due to: ", e) from e
+ return pager
+
+
+def update_metadata(
+ rag_metadata: RagMetadata,
+) -> RagMetadata:
+ """Updates a RagMetadata resource.
+
+ Args:
+ rag_metadata: The RagMetadata which replaces the resource on the server.
+
+ Returns:
+ RagMetadata.
+ """
+ request = UpdateRagMetadataRequest(
+ rag_metadata=_gapic_utils.convert_rag_metadata_to_gapic(rag_metadata),
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.update_rag_metadata(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagMetadata update due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_metadata(response)
+
+
+def update_rag_engine_config(
+ rag_engine_config: RagEngineConfig,
+ timeout: int = 600,
+) -> RagEngineConfig:
+ """Update RagEngineConfig.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+ agentplatform.init(project="my-project")
+ rag_engine_config = rag.RagEngineConfig(
+ rag_managed_db_config=rag.RagManagedDbConfig(
+ rag_managed_db=rag.RagManagedDb(
+ db_basic_tier=rag.Basic(),
+ ),
+ )
+ ),
+ )
+ rag.update_rag_engine_config(rag_engine_config=rag_engine_config)
+ ```
+
+ Args:
+ rag_engine_config: The RagEngineConfig to update.
+ timeout: Default is 600 seconds.
+
+ Raises:
+ RuntimeError: Failed in RagEngineConfig update due to exception.
+ """
+ gapic_rag_engine_config = _gapic_utils.convert_rag_engine_config_to_gapic(
+ rag_engine_config
+ )
+ request = UpdateRagEngineConfigRequest(
+ rag_engine_config=gapic_rag_engine_config,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.update_rag_engine_config(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagEngineConfig update due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_engine_config(
+ response.result(timeout=timeout)
+ )
+
+
+def get_rag_engine_config(name: str) -> RagEngineConfig:
+ """Get an existing RagEngineConfig.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform.preview import rag
+ agentplatform.init(project="my-project")
+ rag_engine_config = rag.get_rag_engine_config(
+ name="projects/my-project/locations/us-central1/ragEngineConfig"
+ )
+ ```
+ Args:
+ name: The RagEngineConfig resource name pattern of the singleton resource.
+
+ Returns:
+ RagEngineConfig.
+ Raises:
+ RuntimeError: Failed in getting the RagEngineConfig.
+ """
+ request = GetRagEngineConfigRequest(name=name)
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.get_rag_engine_config(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in getting the RagEngineConfig due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_engine_config(response)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_retrieval.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_retrieval.py
new file mode 100644
index 0000000000000000000000000000000000000000..6860b0247e3f86cbdc1e610dc90847dce62e236a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_retrieval.py
@@ -0,0 +1,536 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Retrieval query to get relevant contexts."""
+
+import re
+from typing import List, Optional
+import warnings
+
+from google.cloud import aiplatform_v1beta1
+from google.cloud.aiplatform import initializer
+from agentplatform.preview.rag.utils import _gapic_utils
+from agentplatform.preview.rag.utils import resources
+
+from google.protobuf import any_pb2
+
+
+def retrieval_query(
+ text: str,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+) -> aiplatform_v1beta1.RetrieveContextsResponse:
+ """Retrieve top k relevant docs/chunks.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ # Using RagRetrievalConfig.
+ config = agentplatform.preview.rag.RagRetrievalConfig(
+ top_k=2,
+ filter=agentplatform.preview.rag.Filter(
+ vector_distance_threshold=0.5
+ ),
+ hybrid_search=agentplatform.preview.rag.rag_retrieval_config.hybrid_search(
+ alpha=0.5
+ ),
+ ranking=vertex.preview.rag.Ranking(
+ llm_ranker=agentplatform.preview.rag.LlmRanker(
+ model_name="gemini-1.5-flash-002"
+ )
+ )
+ )
+
+ results = agentplatform.preview.rag.retrieval_query(
+ text="Why is the sky blue?",
+ rag_resources=[agentplatform.preview.rag.RagResource(
+ rag_corpus="projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1",
+ rag_file_ids=["rag-file-1", "rag-file-2", ...],
+ )],
+ rag_retrieval_config=config,
+ )
+ ```
+
+ Args:
+ text: The query in text format to get relevant contexts.
+ rag_resources: A list of RagResource. It can be used to specify corpus
+ only or ragfiles. Currently only support one corpus or multiple files
+ from one corpus. In the future we may open up multiple corpora support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including top_k, vector_distance_threshold, and alpha.
+
+ Returns:
+ RetrieveContextsResonse.
+ """
+ parent = initializer.global_config.common_location_path()
+
+ client = _gapic_utils.create_rag_service_client()
+
+ if rag_resources:
+ if len(rag_resources) > 1:
+ raise ValueError("Currently only support 1 RagResource.")
+ name = rag_resources[0].rag_corpus
+ else:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client()
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match(
+ "^{}$".format(
+ _gapic_utils._VALID_RESOURCE_NAME_REGEX # pylint: disable=protected-access
+ ),
+ name,
+ ):
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should be:"
+ " projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}"
+ )
+
+ gapic_rag_resource = (
+ aiplatform_v1beta1.RetrieveContextsRequest.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resources[0].rag_file_ids,
+ )
+ )
+ vertex_rag_store = aiplatform_v1beta1.RetrieveContextsRequest.VertexRagStore(
+ rag_resources=[gapic_rag_resource],
+ )
+
+ if not rag_retrieval_config:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ else:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ if rag_retrieval_config.top_k:
+ api_retrival_config.top_k = rag_retrieval_config.top_k
+ if (
+ rag_retrieval_config.hybrid_search
+ and rag_retrieval_config.hybrid_search.alpha
+ ):
+ api_retrival_config.hybrid_search.alpha = (
+ rag_retrieval_config.hybrid_search.alpha
+ )
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ ):
+ api_retrival_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ api_retrival_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+ if rag_retrieval_config.filter and rag_retrieval_config.filter.metadata_filter:
+ api_retrival_config.filter.metadata_filter = (
+ rag_retrieval_config.filter.metadata_filter
+ )
+
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.llm_ranker
+ ):
+ raise ValueError("Only one of rank_service and llm_ranker can be set.")
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.rank_service:
+ api_retrival_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ elif rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrival_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+ query = aiplatform_v1beta1.RagQuery(
+ text=text,
+ rag_retrieval_config=api_retrival_config,
+ )
+ request = aiplatform_v1beta1.RetrieveContextsRequest(
+ vertex_rag_store=vertex_rag_store,
+ parent=parent,
+ query=query,
+ )
+ try:
+ response = client.retrieve_contexts(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in retrieving contexts due to: ", e) from e
+
+ return response
+
+
+async def async_retrieve_contexts(
+ text: str,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+ timeout: int = 600,
+) -> aiplatform_v1beta1.RetrieveContextsResponse:
+ """Retrieve top k relevant docs/chunks asynchronously.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ config = agentplatform.preview.rag.RagRetrievalConfig(
+ top_k=2,
+ )
+
+ results = await agentplatform.preview.rag.async_retrieve_contexts(
+ text="Why is the sky blue?",
+ rag_resources=[agentplatform.preview.rag.RagResource(
+ rag_corpus="projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1",
+ rag_file_ids=["rag-file-1", "rag-file-2", ...],
+ )],
+ rag_retrieval_config=config,
+ )
+ ```
+
+ Args:
+ text: Required. The query in text format to get relevant contexts.
+ rag_resources: Optional. A list of RagResource. It can be used to specify
+ corpus only or ragfiles. Currently only support one corpus or multiple
+ files from one corpus. In the future we may open up multiple corpora
+ support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including top_k, vector_distance_threshold, and alpha.
+ timeout: Optional. The timeout for the request in seconds. Default is 600.
+
+ Returns:
+ RetrieveContextsResponse.
+ """
+ parent = initializer.global_config.common_location_path()
+
+ client = _gapic_utils.create_rag_service_async_client()
+
+ if not rag_resources:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client()
+
+ gapic_rag_resources = []
+ if rag_resources:
+ for rag_resource in rag_resources:
+ name = rag_resource.rag_corpus
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match(
+ "^{}$".format(
+ _gapic_utils._VALID_RESOURCE_NAME_REGEX # pylint: disable=protected-access
+ ),
+ name,
+ ):
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should be:"
+ " projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}"
+ )
+ gapic_rag_resources.append(
+ aiplatform_v1beta1.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resource.rag_file_ids,
+ )
+ )
+ vertex_rag_store = aiplatform_v1beta1.VertexRagStore(
+ rag_resources=gapic_rag_resources,
+ )
+
+ if not rag_retrieval_config:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ else:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ if rag_retrieval_config.top_k:
+ api_retrival_config.top_k = rag_retrieval_config.top_k
+
+ if (
+ rag_retrieval_config.hybrid_search
+ and rag_retrieval_config.hybrid_search.alpha
+ ):
+ api_retrival_config.hybrid_search.alpha = (
+ rag_retrieval_config.hybrid_search.alpha
+ )
+
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ ):
+ api_retrival_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ api_retrival_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.llm_ranker
+ ):
+ raise ValueError("Only one of rank_service and llm_ranker can be set.")
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.rank_service:
+ api_retrival_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ elif rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrival_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+ if rag_retrieval_config.filter and rag_retrieval_config.filter.metadata_filter:
+ api_retrival_config.filter.metadata_filter = (
+ rag_retrieval_config.filter.metadata_filter
+ )
+
+ query = aiplatform_v1beta1.RagQuery(
+ text=text,
+ rag_retrieval_config=api_retrival_config,
+ )
+
+ vertex_rag_store.rag_retrieval_config = api_retrival_config
+
+ tool = aiplatform_v1beta1.Tool(
+ retrieval=aiplatform_v1beta1.Retrieval(
+ vertex_rag_store=vertex_rag_store,
+ )
+ )
+
+ request = aiplatform_v1beta1.AsyncRetrieveContextsRequest(
+ parent=parent,
+ query=query,
+ tools=[tool],
+ )
+ try:
+ response_lro = await client.async_retrieve_contexts(
+ request=request, timeout=timeout
+ )
+ try:
+ response = await response_lro.result(timeout=timeout)
+ except Exception as e:
+ if response_lro.done():
+ raw_op = response_lro.operation
+ if raw_op.WhichOneof("result") == "response":
+ any_response = raw_op.response
+ inner_any = any_pb2.Any()
+ if any_response.Unpack(inner_any):
+ inner_any.type_url = "type.googleapis.com/google.cloud.aiplatform.v1beta1.RagContexts"
+ rag_contexts = aiplatform_v1beta1.RagContexts()
+ if inner_any.Unpack(rag_contexts._pb):
+ return aiplatform_v1beta1.AsyncRetrieveContextsResponse(
+ contexts=rag_contexts
+ )
+ raise e
+ except Exception as e:
+ raise RuntimeError(
+ "Failed in retrieving contexts asynchronously due to: ", e
+ ) from e
+
+ return response
+
+
+def ask_contexts(
+ text: str,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+ timeout: int = 600,
+) -> aiplatform_v1beta1.AskContextsResponse:
+ """Ask questions on top k relevant docs/chunks.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ config = agentplatform.preview.rag.RagRetrievalConfig(
+ top_k=2,
+ )
+
+ results = agentplatform.preview.rag.ask_contexts(
+ text="Why is the sky blue?",
+ rag_resources=[agentplatform.preview.rag.RagResource(
+ rag_corpus="projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1",
+ rag_file_ids=["rag-file-1", "rag-file-2", ...],
+ )],
+ rag_retrieval_config=config,
+ )
+ ```
+
+ Args:
+ text: Required. The query in text format to get relevant contexts.
+ rag_resources: Optional. A list of RagResource. It can be used to specify
+ corpus only or ragfiles. Currently only support one corpus or multiple
+ files from one corpus. In the future we may open up multiple corpora
+ support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including top_k, vector_distance_threshold, and alpha.
+ timeout: Optional. The timeout for the request in seconds. Default is 600.
+
+ Returns:
+ AskContextsResponse.
+ """
+ parent = initializer.global_config.common_location_path()
+
+ client = _gapic_utils.create_rag_service_client()
+
+ if not rag_resources:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client()
+
+ gapic_rag_resources = []
+ if rag_resources:
+ for rag_resource in rag_resources:
+ name = rag_resource.rag_corpus
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match(
+ "^{}$".format(
+ _gapic_utils._VALID_RESOURCE_NAME_REGEX # pylint: disable=protected-access
+ ),
+ name,
+ ):
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should be:"
+ " projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}"
+ )
+ gapic_rag_resources.append(
+ aiplatform_v1beta1.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resource.rag_file_ids,
+ )
+ )
+ vertex_rag_store = aiplatform_v1beta1.VertexRagStore(
+ rag_resources=gapic_rag_resources,
+ )
+
+ if not rag_retrieval_config:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ else:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ if rag_retrieval_config.top_k:
+ api_retrival_config.top_k = rag_retrieval_config.top_k
+
+ if (
+ rag_retrieval_config.hybrid_search
+ and rag_retrieval_config.hybrid_search.alpha
+ ):
+ api_retrival_config.hybrid_search.alpha = (
+ rag_retrieval_config.hybrid_search.alpha
+ )
+
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ ):
+ api_retrival_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ api_retrival_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.llm_ranker
+ ):
+ raise ValueError("Only one of rank_service and llm_ranker can be set.")
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.rank_service:
+ api_retrival_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ elif rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrival_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+ if rag_retrieval_config.filter and rag_retrieval_config.filter.metadata_filter:
+ api_retrival_config.filter.metadata_filter = (
+ rag_retrieval_config.filter.metadata_filter
+ )
+
+ query = aiplatform_v1beta1.RagQuery(
+ text=text,
+ rag_retrieval_config=api_retrival_config,
+ )
+
+ vertex_rag_store.rag_retrieval_config = api_retrival_config
+
+ tool = aiplatform_v1beta1.Tool(
+ retrieval=aiplatform_v1beta1.Retrieval(
+ vertex_rag_store=vertex_rag_store,
+ )
+ )
+
+ request = aiplatform_v1beta1.AskContextsRequest(
+ parent=parent,
+ query=query,
+ tools=[tool],
+ )
+ try:
+ response = client.ask_contexts(request=request, timeout=timeout)
+ except Exception as e:
+ raise RuntimeError("Failed in asking contexts due to: ", e) from e
+
+ return response
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..f296def7f448a25343f06aa5254dbbc9fdad3e44
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/rag_store.py
@@ -0,0 +1,168 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""RAG retrieval tool for content generation."""
+
+import re
+from typing import List, Optional, Union
+import warnings
+
+from google.cloud import aiplatform_v1beta1
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform_v1beta1.types import tool as gapic_tool_types
+from agentplatform.preview.rag.utils import _gapic_utils
+from agentplatform.preview.rag.utils import resources
+
+
+class Retrieval:
+ """Defines a retrieval tool that a model can call to access external knowledge."""
+
+ def __init__(
+ self,
+ source: Union["VertexRagStore"],
+ disable_attribution: Optional[bool] = False,
+ ):
+ self._raw_retrieval = gapic_tool_types.Retrieval(
+ vertex_rag_store=source._raw_vertex_rag_store,
+ disable_attribution=disable_attribution,
+ )
+
+
+class VertexRagStore:
+ """Retrieve from Vertex RAG Store."""
+
+ def __init__(
+ self,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+ ):
+ """Initializes a Vertex RAG store tool.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ # Using RagRetrievalConfig.
+ config = agentplatform.preview.rag.RagRetrievalConfig(
+ top_k=2,
+ filter=agentplatform.preview.rag.RagRetrievalConfig.Filter(
+ vector_distance_threshold=0.5
+ ),
+ )
+
+ tool = Tool.from_retrieval(
+ retrieval=agentplatform.preview.rag.Retrieval(
+ source=agentplatform.preview.rag.VertexRagStore(
+ rag_resources=[
+ agentplatform.preview.rag.RagResource(
+ rag_corpus="projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1"
+ )
+ ],
+ rag_retrieval_config=config,
+ ),
+ )
+ )
+ ```
+
+ Args:
+ rag_resources: List of RagResource to retrieve from. It can be used
+ to specify corpus only or ragfiles. Currently only support one
+ corpus or multiple files from one corpus. In the future we
+ may open up multiple corpora support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including top_k and vector_distance_threshold.
+ """
+
+ if rag_resources:
+ if len(rag_resources) > 1:
+ raise ValueError("Currently only support 1 RagResource.")
+ name = rag_resources[0].rag_corpus
+ else:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client()
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match("^{}$".format(_gapic_utils._VALID_RESOURCE_NAME_REGEX), name):
+ parent = initializer.global_config.common_location_path()
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should"
+ + " be: projects/{{project}}/locations/{{location}}/ragCorpora/{{rag_corpus_id}}"
+ )
+
+ if not rag_retrieval_config:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ else:
+ api_retrival_config = aiplatform_v1beta1.RagRetrievalConfig()
+ if rag_retrieval_config.top_k:
+ api_retrival_config.top_k = rag_retrieval_config.top_k
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ ):
+ api_retrival_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ api_retrival_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.rank_service.model_name
+ and rag_retrieval_config.ranking.llm_ranker
+ and rag_retrieval_config.ranking.llm_ranker.model_name
+ ):
+ raise ValueError(
+ "Only one of rank_service or llm_ranker can be specified"
+ " at a time in rag_retrieval_config."
+ )
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ ):
+ api_retrival_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrival_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+
+ gapic_rag_resource = gapic_tool_types.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resources[0].rag_file_ids,
+ )
+ self._raw_vertex_rag_store = gapic_tool_types.VertexRagStore(
+ rag_resources=[gapic_rag_resource],
+ rag_retrieval_config=api_retrival_config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/__pycache__/_gapic_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/__pycache__/_gapic_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6eeec8db69985896e3edbab4afcf7d4c01eeb27e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/__pycache__/_gapic_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/__pycache__/resources.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/__pycache__/resources.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c24cb435e72551cb1dc23b01484679ca47cb8f66
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/__pycache__/resources.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/_gapic_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/_gapic_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef3d166730ce9275a79ccfa0ff9c4eb313ab1be9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/_gapic_utils.py
@@ -0,0 +1,1418 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import re
+from typing import Any, Dict, Optional, Sequence, Union
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform.utils import (
+ VertexRagAsyncClientWithOverride,
+ VertexRagClientWithOverride,
+ VertexRagDataAsyncClientWithOverride,
+ VertexRagDataClientWithOverride,
+)
+
+#
+from google.cloud.aiplatform_v1beta1 import (
+ GoogleDriveSource,
+ ImportRagFilesConfig,
+ ImportRagFilesRequest,
+ JiraSource as GapicJiraSource,
+ RagCorpus as GapicRagCorpus,
+ RagEmbeddingModelConfig as GapicRagEmbeddingModelConfig,
+ RagEngineConfig as GapicRagEngineConfig,
+ RagFileChunkingConfig,
+ RagFileParsingConfig,
+ RagFileTransformationConfig,
+ RagFile as GapicRagFile,
+ RagManagedDbConfig as GapicRagManagedDbConfig,
+ RagVectorDbConfig as GapicRagVectorDbConfig,
+ SharePointSources as GapicSharePointSources,
+ SlackSource as GapicSlackSource,
+ VertexAiSearchConfig as GapicVertexAiSearchConfig,
+)
+from google.cloud.aiplatform_v1beta1.types import api_auth
+from google.cloud.aiplatform_v1beta1.types import EncryptionSpec
+from google.cloud.aiplatform_v1beta1.types import (
+ vertex_rag_data as GapicRagDataTypes,
+)
+from agentplatform.preview.rag.utils.resources import (
+ ANN,
+ Basic,
+ DocumentCorpus,
+ EmbeddingModelConfig,
+ JiraSource,
+ KNN,
+ LayoutParserConfig,
+ LlmParserConfig,
+ MemoryCorpus,
+ MetadataValue,
+ Pinecone,
+ RagCorpus,
+ RagCorpusTypeConfig,
+ RagDataSchema,
+ RagEmbeddingModelConfig,
+ RagEngineConfig,
+ RagFile,
+ RagManagedDb,
+ RagManagedDbConfig,
+ RagManagedVertexVectorSearch,
+ RagMetadata,
+ RagMetadataSchemaDetails,
+ RagVectorDbConfig,
+ Scaled,
+ Serverless,
+ SharePointSources,
+ SlackChannelsSource,
+ Spanner,
+ TransformationConfig,
+ Unprovisioned,
+ UserSpecifiedMetadata,
+ VertexAiSearchConfig,
+ VertexFeatureStore,
+ VertexPredictionEndpoint,
+ VertexVectorSearch,
+ Weaviate,
+)
+
+
+_VALID_RESOURCE_NAME_REGEX = "[a-z][a-zA-Z0-9._-]{0,127}"
+_VALID_DOCUMENT_AI_PROCESSOR_NAME_REGEX = (
+ r"projects/[^/]+/locations/[^/]+/processors/[^/]+(?:/processorVersions/[^/]+)?"
+)
+
+
+def create_rag_data_service_client():
+ return initializer.global_config.create_client(
+ client_class=VertexRagDataClientWithOverride,
+ ).select_version("v1beta1")
+
+
+def create_rag_data_service_async_client():
+ return initializer.global_config.create_client(
+ client_class=VertexRagDataAsyncClientWithOverride,
+ ).select_version("v1beta1")
+
+
+def create_rag_service_client():
+ return initializer.global_config.create_client(
+ client_class=VertexRagClientWithOverride,
+ ).select_version("v1beta1")
+
+
+def create_rag_service_async_client():
+ return initializer.global_config.create_client(
+ client_class=VertexRagAsyncClientWithOverride,
+ ).select_version("v1beta1")
+
+
+def convert_gapic_to_embedding_model_config(
+ gapic_embedding_model_config: GapicRagEmbeddingModelConfig,
+) -> EmbeddingModelConfig:
+ """Convert GapicRagEmbeddingModelConfig to EmbeddingModelConfig."""
+ embedding_model_config = EmbeddingModelConfig()
+ path = gapic_embedding_model_config.vertex_prediction_endpoint.endpoint
+ publisher_model = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/publishers/google/models/(?P.+?)$",
+ path,
+ )
+ endpoint = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/endpoints/(?P.+?)$",
+ path,
+ )
+ if publisher_model:
+ embedding_model_config.publisher_model = path
+ if endpoint:
+ embedding_model_config.endpoint = path
+ embedding_model_config.model = (
+ gapic_embedding_model_config.vertex_prediction_endpoint.model
+ )
+ embedding_model_config.model_version_id = (
+ gapic_embedding_model_config.vertex_prediction_endpoint.model_version_id
+ )
+
+ return embedding_model_config
+
+
+def _check_weaviate(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("weaviate")
+ except AttributeError:
+ if "weaviate" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("weaviate")
+ return False
+
+
+def _check_rag_managed_db(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("rag_managed_db")
+ except AttributeError:
+ if "rag_managed_db" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("rag_managed_db")
+ return False
+
+
+def _check_knn(gapic_rag_managed_db: GapicRagVectorDbConfig.RagManagedDb) -> bool:
+ try:
+ return gapic_rag_managed_db.__contains__("knn")
+ except AttributeError:
+ if "knn" in gapic_rag_managed_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_rag_managed_db._pb.HasField("knn")
+ return False
+
+
+def _check_ann(gapic_rag_managed_db: GapicRagVectorDbConfig.RagManagedDb) -> bool:
+ try:
+ return gapic_rag_managed_db.__contains__("ann")
+ except AttributeError:
+ if "ann" in gapic_rag_managed_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_rag_managed_db._pb.HasField("ann")
+ return False
+
+
+def _check_vertex_feature_store(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("vertex_feature_store")
+ except AttributeError:
+ if "vertex_feature_store" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("vertex_feature_store")
+ return False
+
+
+def _check_pinecone(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("pinecone")
+ except AttributeError:
+ if "pinecone" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("pinecone")
+ return False
+
+
+def _check_vertex_vector_search(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("vertex_vector_search")
+ except AttributeError:
+ if "vertex_vector_search" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("vertex_vector_search")
+ return False
+
+
+def _check_rag_managed_vertex_vector_search(
+ gapic_vector_db: GapicRagVectorDbConfig,
+) -> bool:
+ try:
+ return gapic_vector_db.__contains__("rag_managed_vertex_vector_search")
+ except AttributeError:
+ return gapic_vector_db.rag_managed_vertex_vector_search._pb.ByteSize() > 0
+
+
+def _check_rag_embedding_model_config(
+ gapic_vector_db: GapicRagVectorDbConfig,
+) -> bool:
+ try:
+ return gapic_vector_db.__contains__("rag_embedding_model_config")
+ except AttributeError:
+ return gapic_vector_db.rag_embedding_model_config._pb.ByteSize() > 0
+
+
+def _check_document_corpus(
+ gapic_corpus_type_config: GapicRagCorpus.CorpusTypeConfig,
+) -> bool:
+ try:
+ return gapic_corpus_type_config.__contains__("document_corpus")
+ except AttributeError:
+ return gapic_corpus_type_config.document_corpus._pb.ByteSize() > 0
+
+
+def _check_memory_corpus(
+ gapic_corpus_type_config: GapicRagCorpus.CorpusTypeConfig,
+) -> bool:
+ try:
+ return gapic_corpus_type_config.__contains__("memory_corpus")
+ except AttributeError:
+ return gapic_corpus_type_config.memory_corpus._pb.ByteSize() > 0
+
+
+def _convert_gapic_to_rag_managed_db(
+ gapic_rag_managed_db: GapicRagVectorDbConfig.RagManagedDb,
+) -> RagManagedDb:
+ """Convert Gapic RagManagedDbConfig to RagManagedDb."""
+ if _check_knn(gapic_rag_managed_db):
+ return RagManagedDb(retrieval_strategy=KNN())
+ elif _check_ann(gapic_rag_managed_db):
+ return RagManagedDb(
+ retrieval_strategy=ANN(
+ tree_depth=gapic_rag_managed_db.ann.tree_depth,
+ leaf_count=gapic_rag_managed_db.ann.leaf_count,
+ )
+ )
+ else:
+ return RagManagedDb()
+
+
+def _convert_rag_managed_db_to_gapic(
+ rag_managed_db: RagManagedDb,
+) -> GapicRagVectorDbConfig.RagManagedDb:
+ """Convert RagManagedDb to Gapic RagManagedDb."""
+ if isinstance(rag_managed_db.retrieval_strategy, KNN):
+ return GapicRagVectorDbConfig.RagManagedDb(
+ knn=GapicRagVectorDbConfig.RagManagedDb.KNN()
+ )
+ elif isinstance(rag_managed_db.retrieval_strategy, ANN):
+ return GapicRagVectorDbConfig.RagManagedDb(
+ ann=GapicRagVectorDbConfig.RagManagedDb.ANN(
+ tree_depth=rag_managed_db.retrieval_strategy.tree_depth,
+ leaf_count=rag_managed_db.retrieval_strategy.leaf_count,
+ )
+ )
+ else:
+ return GapicRagVectorDbConfig.RagManagedDb()
+
+
+def convert_gapic_to_vector_db(
+ gapic_vector_db: GapicRagVectorDbConfig,
+) -> Union[Weaviate, VertexFeatureStore, VertexVectorSearch, Pinecone, RagManagedDb]:
+ """Convert Gapic GapicRagVectorDbConfig to Weaviate, VertexFeatureStore, VertexVectorSearch, RagManagedDb, or Pinecone."""
+ if _check_weaviate(gapic_vector_db):
+ return Weaviate(
+ weaviate_http_endpoint=gapic_vector_db.weaviate.http_endpoint,
+ collection_name=gapic_vector_db.weaviate.collection_name,
+ api_key=gapic_vector_db.api_auth.api_key_config.api_key_secret_version,
+ )
+ elif _check_vertex_feature_store(gapic_vector_db):
+ return VertexFeatureStore(
+ resource_name=gapic_vector_db.vertex_feature_store.feature_view_resource_name,
+ )
+ elif _check_pinecone(gapic_vector_db):
+ return Pinecone(
+ index_name=gapic_vector_db.pinecone.index_name,
+ api_key=gapic_vector_db.api_auth.api_key_config.api_key_secret_version,
+ )
+ elif _check_rag_managed_vertex_vector_search(gapic_vector_db):
+ return RagManagedVertexVectorSearch(
+ collection_name=gapic_vector_db.rag_managed_vertex_vector_search.collection_name,
+ )
+ elif _check_vertex_vector_search(gapic_vector_db):
+ return VertexVectorSearch(
+ index_endpoint=gapic_vector_db.vertex_vector_search.index_endpoint,
+ index=gapic_vector_db.vertex_vector_search.index,
+ )
+ elif _check_rag_managed_db(gapic_vector_db):
+ return _convert_gapic_to_rag_managed_db(gapic_vector_db.rag_managed_db)
+ else:
+ return None
+
+
+def convert_gapic_to_vertex_ai_search_config(
+ gapic_vertex_ai_search_config: GapicVertexAiSearchConfig,
+) -> Optional[VertexAiSearchConfig]:
+ """Convert Gapic VertexAiSearchConfig to VertexAiSearchConfig."""
+ if gapic_vertex_ai_search_config.serving_config:
+ return VertexAiSearchConfig(
+ serving_config=gapic_vertex_ai_search_config.serving_config,
+ )
+ return None
+
+
+def convert_gapic_to_rag_embedding_model_config(
+ gapic_embedding_model_config: GapicRagEmbeddingModelConfig,
+) -> RagEmbeddingModelConfig:
+ """Convert GapicRagEmbeddingModelConfig to RagEmbeddingModelConfig."""
+ embedding_model_config = RagEmbeddingModelConfig()
+ path = gapic_embedding_model_config.vertex_prediction_endpoint.endpoint
+ publisher_model = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/publishers/google/models/(?P.+?)$",
+ path,
+ )
+ endpoint = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/endpoints/(?P.+?)$",
+ path,
+ )
+ if publisher_model:
+ embedding_model_config.vertex_prediction_endpoint = VertexPredictionEndpoint(
+ publisher_model=path
+ )
+ if endpoint:
+ embedding_model_config.vertex_prediction_endpoint = VertexPredictionEndpoint(
+ endpoint=path,
+ model=gapic_embedding_model_config.vertex_prediction_endpoint.model,
+ model_version_id=gapic_embedding_model_config.vertex_prediction_endpoint.model_version_id,
+ )
+ return embedding_model_config
+
+
+def convert_gapic_to_backend_config(
+ gapic_vector_db: GapicRagVectorDbConfig,
+) -> RagVectorDbConfig:
+ """Convert Gapic RagVectorDbConfig to VertexVectorSearch, Pinecone, or RagManagedDb."""
+
+ vector_config = RagVectorDbConfig()
+ if _check_pinecone(gapic_vector_db):
+ vector_config.vector_db = Pinecone(
+ index_name=gapic_vector_db.pinecone.index_name,
+ api_key=gapic_vector_db.api_auth.api_key_config.api_key_secret_version,
+ )
+ elif _check_rag_managed_vertex_vector_search(gapic_vector_db):
+ vector_config.vector_db = RagManagedVertexVectorSearch(
+ collection_name=gapic_vector_db.rag_managed_vertex_vector_search.collection_name,
+ )
+ elif _check_vertex_vector_search(gapic_vector_db):
+ vector_config.vector_db = VertexVectorSearch(
+ index_endpoint=gapic_vector_db.vertex_vector_search.index_endpoint,
+ index=gapic_vector_db.vertex_vector_search.index,
+ )
+ elif _check_rag_managed_db(gapic_vector_db):
+ vector_config.vector_db = _convert_gapic_to_rag_managed_db(
+ gapic_vector_db.rag_managed_db
+ )
+ if _check_rag_embedding_model_config(gapic_vector_db):
+ vector_config.rag_embedding_model_config = (
+ convert_gapic_to_rag_embedding_model_config(
+ gapic_vector_db.rag_embedding_model_config
+ )
+ )
+ if (
+ vector_config.vector_db is None
+ and vector_config.rag_embedding_model_config is None
+ ):
+ return None
+ return vector_config
+
+
+def convert_gapic_to_rag_corpus_type_config(
+ gapic_rag_corpus_type_config: GapicRagCorpus.CorpusTypeConfig,
+) -> RagCorpusTypeConfig:
+ """Convert GapicRagCorpus.CorpusTypeConfig to RagCorpusTypeConfig."""
+ if _check_document_corpus(gapic_rag_corpus_type_config):
+ return RagCorpusTypeConfig(corpus_type_config=DocumentCorpus())
+ elif _check_memory_corpus(gapic_rag_corpus_type_config):
+ return RagCorpusTypeConfig(
+ corpus_type_config=MemoryCorpus(
+ llm_parser=LlmParserConfig(
+ model_name=gapic_rag_corpus_type_config.memory_corpus.llm_parser.model_name,
+ max_parsing_requests_per_min=gapic_rag_corpus_type_config.memory_corpus.llm_parser.max_parsing_requests_per_min,
+ global_max_parsing_requests_per_min=gapic_rag_corpus_type_config.memory_corpus.llm_parser.global_max_parsing_requests_per_min,
+ custom_parsing_prompt=gapic_rag_corpus_type_config.memory_corpus.llm_parser.custom_parsing_prompt,
+ )
+ )
+ )
+ return None
+
+
+def convert_gapic_to_rag_corpus(gapic_rag_corpus: GapicRagCorpus) -> RagCorpus:
+ """Convert GapicRagCorpus to RagCorpus."""
+ rag_corpus = RagCorpus(
+ name=gapic_rag_corpus.name,
+ display_name=gapic_rag_corpus.display_name,
+ description=gapic_rag_corpus.description,
+ corpus_type_config=convert_gapic_to_rag_corpus_type_config(
+ gapic_rag_corpus.corpus_type_config
+ ),
+ vertex_ai_search_config=convert_gapic_to_vertex_ai_search_config(
+ gapic_rag_corpus.vertex_ai_search_config
+ ),
+ backend_config=convert_gapic_to_backend_config(
+ gapic_rag_corpus.vector_db_config
+ ),
+ encryption_spec=gapic_rag_corpus.encryption_spec,
+ )
+ return rag_corpus
+
+
+def convert_gapic_to_rag_corpus_no_embedding_model_config(
+ gapic_rag_corpus: GapicRagCorpus,
+) -> RagCorpus:
+ """Convert GapicRagCorpus without embedding model config (for UpdateRagCorpus) to RagCorpus."""
+ vertex_ai_search_config = convert_gapic_to_vertex_ai_search_config(
+ gapic_rag_corpus.vertex_ai_search_config
+ )
+ old_config = gapic_rag_corpus.vector_db_config
+ rag_vector_db_config_no_embedding_model_config = old_config.__class__()
+ if _check_rag_managed_db(old_config):
+ rag_vector_db_config_no_embedding_model_config.rag_managed_db = (
+ old_config.rag_managed_db
+ )
+ elif _check_pinecone(old_config):
+ rag_vector_db_config_no_embedding_model_config.pinecone = old_config.pinecone
+ elif _check_vertex_vector_search(old_config):
+ rag_vector_db_config_no_embedding_model_config.vertex_vector_search = (
+ old_config.vertex_vector_search
+ )
+ elif _check_weaviate(old_config):
+ rag_vector_db_config_no_embedding_model_config.weaviate = old_config.weaviate
+ elif _check_vertex_feature_store(old_config):
+ rag_vector_db_config_no_embedding_model_config.vertex_feature_store = (
+ old_config.vertex_feature_store
+ )
+ try:
+ if old_config.__contains__("api_auth"):
+ rag_vector_db_config_no_embedding_model_config.api_auth = (
+ old_config.api_auth
+ )
+ except AttributeError:
+ pass
+ rag_corpus = RagCorpus(
+ name=gapic_rag_corpus.name,
+ display_name=gapic_rag_corpus.display_name,
+ description=gapic_rag_corpus.description,
+ vertex_ai_search_config=vertex_ai_search_config,
+ backend_config=convert_gapic_to_backend_config(
+ rag_vector_db_config_no_embedding_model_config
+ ),
+ encryption_spec=gapic_rag_corpus.encryption_spec,
+ )
+ return rag_corpus
+
+
+def convert_gapic_to_rag_file(gapic_rag_file: GapicRagFile) -> RagFile:
+ """Convert GapicRagFile to RagFile."""
+ rag_file = RagFile(
+ name=gapic_rag_file.name,
+ display_name=gapic_rag_file.display_name,
+ description=gapic_rag_file.description,
+ )
+ return rag_file
+
+
+def convert_gapic_to_rag_metadata(
+ gapic_rag_metadata: GapicRagDataTypes.RagMetadata,
+) -> RagMetadata:
+ """Convert Gapic RagMetadata to RagMetadata."""
+ return RagMetadata(
+ name=gapic_rag_metadata.name,
+ user_specified_metadata=convert_gapic_to_user_specified_metadata(
+ gapic_rag_metadata.user_specified_metadata
+ ),
+ )
+
+
+def convert_gapic_to_user_specified_metadata(
+ gapic_user_specified_metadata: GapicRagDataTypes.UserSpecifiedMetadata,
+) -> UserSpecifiedMetadata:
+ """Convert Gapic UserSpecifiedMetadata to UserSpecifiedMetadata."""
+ if not gapic_user_specified_metadata:
+ return None
+ return UserSpecifiedMetadata(
+ values={
+ gapic_user_specified_metadata.key: convert_gapic_to_metadata_value(
+ gapic_user_specified_metadata.value
+ )
+ }
+ )
+
+
+def convert_gapic_to_metadata_value(
+ gapic_metadata_value: GapicRagDataTypes.MetadataValue,
+) -> MetadataValue:
+ """Convert Gapic MetadataValue to MetadataValue."""
+ if not gapic_metadata_value:
+ return None
+ oneof_field = gapic_metadata_value._pb.WhichOneof("value")
+ if oneof_field == "str_value":
+ return MetadataValue(string_value=gapic_metadata_value.str_value)
+ elif oneof_field == "int_value":
+ return MetadataValue(int_value=gapic_metadata_value.int_value)
+ elif oneof_field == "float_value":
+ return MetadataValue(float_value=gapic_metadata_value.float_value)
+ elif oneof_field == "bool_value":
+ return MetadataValue(bool_value=gapic_metadata_value.bool_value)
+ return MetadataValue()
+
+
+def convert_rag_metadata_to_gapic(
+ rag_metadata: RagMetadata,
+) -> GapicRagDataTypes.RagMetadata:
+ """Convert RagMetadata to Gapic RagMetadata."""
+ return GapicRagDataTypes.RagMetadata(
+ name=rag_metadata.name,
+ user_specified_metadata=convert_user_specified_metadata_to_gapic(
+ rag_metadata.user_specified_metadata
+ ),
+ )
+
+
+def convert_user_specified_metadata_to_gapic(
+ user_specified_metadata: UserSpecifiedMetadata,
+) -> GapicRagDataTypes.UserSpecifiedMetadata:
+ """Convert UserSpecifiedMetadata to Gapic UserSpecifiedMetadata."""
+ if not user_specified_metadata:
+ return None
+ if user_specified_metadata.values:
+ if len(user_specified_metadata.values) > 1:
+ raise ValueError(
+ "Only one key-value pair is supported in UserSpecifiedMetadata."
+ )
+ key = list(user_specified_metadata.values.keys())[0]
+ return GapicRagDataTypes.UserSpecifiedMetadata(
+ key=key,
+ value=convert_metadata_value_to_gapic(user_specified_metadata.values[key]),
+ )
+ return GapicRagDataTypes.UserSpecifiedMetadata()
+
+
+def convert_metadata_value_to_gapic(
+ metadata_value: MetadataValue,
+) -> GapicRagDataTypes.MetadataValue:
+ """Convert MetadataValue to Gapic MetadataValue."""
+ if not metadata_value:
+ return None
+ if metadata_value.string_value is not None:
+ return GapicRagDataTypes.MetadataValue(str_value=metadata_value.string_value)
+ if metadata_value.int_value is not None:
+ return GapicRagDataTypes.MetadataValue(int_value=metadata_value.int_value)
+ if metadata_value.float_value is not None:
+ return GapicRagDataTypes.MetadataValue(float_value=metadata_value.float_value)
+ if metadata_value.bool_value is not None:
+ return GapicRagDataTypes.MetadataValue(bool_value=metadata_value.bool_value)
+ return GapicRagDataTypes.MetadataValue()
+
+
+def convert_gapic_to_rag_data_schema(
+ gapic_rag_data_schema: GapicRagDataTypes.RagDataSchema,
+) -> RagDataSchema:
+ """Convert Gapic RagDataSchema to RagDataSchema."""
+ return RagDataSchema(
+ name=gapic_rag_data_schema.name,
+ key=gapic_rag_data_schema.key,
+ schema_details=convert_gapic_to_rag_metadata_schema_details(
+ gapic_rag_data_schema.schema_details
+ ),
+ )
+
+
+def convert_gapic_to_rag_metadata_schema_details(
+ gapic_details: GapicRagDataTypes.RagMetadataSchemaDetails,
+) -> RagMetadataSchemaDetails:
+ """Convert Gapic RagMetadataSchemaDetails to RagMetadataSchemaDetails."""
+ if not gapic_details:
+ return None
+ list_config = None
+ if gapic_details.list_config:
+ list_config = RagMetadataSchemaDetails.ListConfig(
+ value_schema=convert_gapic_to_rag_metadata_schema_details(
+ gapic_details.list_config.value_schema
+ )
+ )
+ search_strategy = None
+ if gapic_details.search_strategy:
+ search_strategy = RagMetadataSchemaDetails.SearchStrategy(
+ search_strategy_type=GapicRagDataTypes.RagMetadataSchemaDetails.SearchStrategy.SearchStrategyType(
+ gapic_details.search_strategy.search_strategy_type
+ ).name
+ )
+ return RagMetadataSchemaDetails(
+ type=GapicRagDataTypes.RagMetadataSchemaDetails.DataType(
+ gapic_details.type_
+ ).name,
+ granularity=GapicRagDataTypes.RagMetadataSchemaDetails.Granularity(
+ gapic_details.granularity
+ ).name,
+ list_config=list_config,
+ search_strategy=search_strategy,
+ )
+
+
+def convert_rag_data_schema_to_gapic(
+ rag_data_schema: RagDataSchema,
+) -> GapicRagDataTypes.RagDataSchema:
+ """Convert RagDataSchema to Gapic RagDataSchema."""
+ return GapicRagDataTypes.RagDataSchema(
+ name=rag_data_schema.name,
+ key=rag_data_schema.key,
+ schema_details=convert_rag_metadata_schema_details_to_gapic(
+ rag_data_schema.schema_details
+ ),
+ )
+
+
+def convert_rag_metadata_schema_details_to_gapic(
+ details: RagMetadataSchemaDetails,
+) -> GapicRagDataTypes.RagMetadataSchemaDetails:
+ """Convert RagMetadataSchemaDetails to Gapic RagMetadataSchemaDetails."""
+ if not details:
+ return None
+ list_config = None
+ if details.list_config:
+ list_config = GapicRagDataTypes.RagMetadataSchemaDetails.ListConfig(
+ value_schema=convert_rag_metadata_schema_details_to_gapic(
+ details.list_config.value_schema
+ )
+ )
+ search_strategy = None
+ if details.search_strategy:
+ search_strategy = GapicRagDataTypes.RagMetadataSchemaDetails.SearchStrategy(
+ search_strategy_type=details.search_strategy.search_strategy_type
+ )
+ return GapicRagDataTypes.RagMetadataSchemaDetails(
+ type_=(
+ details.type
+ if details.type
+ else GapicRagDataTypes.RagMetadataSchemaDetails.DataType.DATA_TYPE_UNSPECIFIED
+ ),
+ granularity=(
+ details.granularity
+ if details.granularity
+ else GapicRagDataTypes.RagMetadataSchemaDetails.Granularity.GRANULARITY_UNSPECIFIED
+ ),
+ list_config=list_config,
+ search_strategy=search_strategy,
+ )
+
+
+def convert_json_to_rag_file(upload_rag_file_response: Dict[str, Any]) -> RagFile:
+ """Converts a JSON response to a RagFile."""
+ rag_file = RagFile(
+ name=upload_rag_file_response.get("ragFile").get("name"),
+ display_name=upload_rag_file_response.get("ragFile").get("displayName"),
+ description=upload_rag_file_response.get("ragFile").get("description"),
+ )
+ return rag_file
+
+
+def convert_path_to_resource_id(
+ path: str,
+) -> Union[str, GoogleDriveSource.ResourceId]:
+ """Converts a path to a Google Cloud storage uri or GoogleDriveSource.ResourceId."""
+ if path.startswith("gs://"):
+ # Google Cloud Storage source
+ return path
+ elif path.startswith("https://drive.google.com/"):
+ # Google Drive source
+ path_list = path.split("/")
+ if "file" in path_list:
+ index = path_list.index("file") + 2
+ resource_id = path_list[index].split("?")[0]
+ resource_type = GoogleDriveSource.ResourceId.ResourceType.RESOURCE_TYPE_FILE
+ elif "folders" in path_list:
+ index = path_list.index("folders") + 1
+ resource_id = path_list[index].split("?")[0]
+ resource_type = (
+ GoogleDriveSource.ResourceId.ResourceType.RESOURCE_TYPE_FOLDER
+ )
+ else:
+ raise ValueError("path %s is not a valid Google Drive url.", path)
+
+ return GoogleDriveSource.ResourceId(
+ resource_id=resource_id,
+ resource_type=resource_type,
+ )
+ else:
+ raise ValueError(
+ "path must be a Google Cloud Storage uri or a Google Drive url."
+ )
+
+
+def convert_source_for_rag_import(
+ source: Union[SlackChannelsSource, JiraSource, SharePointSources],
+) -> Union[GapicSlackSource, GapicJiraSource]:
+ """Converts a SlackChannelsSource or JiraSource to a GapicSlackSource or GapicJiraSource."""
+ if isinstance(source, SlackChannelsSource):
+ result_source_channels = []
+ for channel in source.channels:
+ api_key = channel.api_key
+ cid = channel.channel_id
+ start_time = channel.start_time
+ end_time = channel.end_time
+ result_channels = GapicSlackSource.SlackChannels(
+ channels=[
+ GapicSlackSource.SlackChannels.SlackChannel(
+ channel_id=cid,
+ start_time=start_time,
+ end_time=end_time,
+ )
+ ],
+ api_key_config=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=api_key
+ ),
+ )
+ result_source_channels.append(result_channels)
+ return GapicSlackSource(
+ channels=result_source_channels,
+ )
+ elif isinstance(source, JiraSource):
+ result_source_queries = []
+ for query in source.queries:
+ api_key = query.api_key
+ custom_queries = query.custom_queries
+ projects = query.jira_projects
+ email = query.email
+ server_uri = query.server_uri
+ result_query = GapicJiraSource.JiraQueries(
+ custom_queries=custom_queries,
+ projects=projects,
+ email=email,
+ server_uri=server_uri,
+ api_key_config=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=api_key
+ ),
+ )
+ result_source_queries.append(result_query)
+ return GapicJiraSource(
+ jira_queries=result_source_queries,
+ )
+ elif isinstance(source, SharePointSources):
+ result_source_share_point_sources = []
+ for share_point_source in source.share_point_sources:
+ sharepoint_folder_path = share_point_source.sharepoint_folder_path
+ sharepoint_folder_id = share_point_source.sharepoint_folder_id
+ drive_name = share_point_source.drive_name
+ drive_id = share_point_source.drive_id
+ client_id = share_point_source.client_id
+ client_secret = share_point_source.client_secret
+ tenant_id = share_point_source.tenant_id
+ sharepoint_site_name = share_point_source.sharepoint_site_name
+ result_share_point_source = GapicSharePointSources.SharePointSource(
+ client_id=client_id,
+ client_secret=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=client_secret
+ ),
+ tenant_id=tenant_id,
+ sharepoint_site_name=sharepoint_site_name,
+ )
+ if sharepoint_folder_path is not None and sharepoint_folder_id is not None:
+ raise ValueError(
+ "sharepoint_folder_path and sharepoint_folder_id cannot both be set."
+ )
+ elif sharepoint_folder_path is not None:
+ result_share_point_source.sharepoint_folder_path = (
+ sharepoint_folder_path
+ )
+ elif sharepoint_folder_id is not None:
+ result_share_point_source.sharepoint_folder_id = sharepoint_folder_id
+ if drive_name is not None and drive_id is not None:
+ raise ValueError("drive_name and drive_id cannot both be set.")
+ elif drive_name is not None:
+ result_share_point_source.drive_name = drive_name
+ elif drive_id is not None:
+ result_share_point_source.drive_id = drive_id
+ else:
+ raise ValueError("Either drive_name and drive_id must be set.")
+ result_source_share_point_sources.append(result_share_point_source)
+ return GapicSharePointSources(
+ share_point_sources=result_source_share_point_sources,
+ )
+ else:
+ raise TypeError(
+ "source must be a SlackChannelsSource or JiraSource or SharePointSources."
+ )
+
+
+def prepare_import_files_request(
+ corpus_name: str,
+ paths: Optional[Sequence[str]] = None,
+ source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
+ chunk_size: int = 1024,
+ chunk_overlap: int = 200,
+ transformation_config: Optional[TransformationConfig] = None,
+ max_embedding_requests_per_min: int = 1000,
+ global_max_embedding_requests_per_min: Optional[int] = None,
+ use_advanced_pdf_parsing: bool = False,
+ partial_failures_sink: Optional[str] = None,
+ layout_parser: Optional[LayoutParserConfig] = None,
+ llm_parser: Optional[LlmParserConfig] = None,
+ rebuild_ann_index: bool = False,
+) -> ImportRagFilesRequest:
+ if len(corpus_name.split("/")) != 6:
+ raise ValueError(
+ "corpus_name must be of the format `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`"
+ )
+
+ rag_file_parsing_config = RagFileParsingConfig(
+ advanced_parser=RagFileParsingConfig.AdvancedParser(
+ use_advanced_pdf_parsing=use_advanced_pdf_parsing,
+ ),
+ )
+ if layout_parser is not None:
+ if (
+ re.fullmatch(
+ _VALID_DOCUMENT_AI_PROCESSOR_NAME_REGEX, layout_parser.processor_name
+ )
+ is None
+ ):
+ raise ValueError(
+ "processor_name must be of the format "
+ "`projects/{project_id}/locations/{location}/processors/{processor_id}`"
+ "or "
+ "`projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}`, "
+ f"got {layout_parser.processor_name!r}"
+ )
+ rag_file_parsing_config.layout_parser = RagFileParsingConfig.LayoutParser(
+ processor_name=layout_parser.processor_name,
+ )
+ if layout_parser.max_parsing_requests_per_min is not None:
+ rag_file_parsing_config.layout_parser.max_parsing_requests_per_min = (
+ layout_parser.max_parsing_requests_per_min
+ )
+ if layout_parser.global_max_parsing_requests_per_min is not None:
+ rag_file_parsing_config.layout_parser.global_max_parsing_requests_per_min = (
+ layout_parser.global_max_parsing_requests_per_min
+ )
+ if llm_parser is not None:
+ rag_file_parsing_config.llm_parser = RagFileParsingConfig.LlmParser(
+ model_name=llm_parser.model_name
+ )
+ if llm_parser.max_parsing_requests_per_min is not None:
+ rag_file_parsing_config.llm_parser.max_parsing_requests_per_min = (
+ llm_parser.max_parsing_requests_per_min
+ )
+ if llm_parser.global_max_parsing_requests_per_min is not None:
+ rag_file_parsing_config.llm_parser.global_max_parsing_requests_per_min = (
+ llm_parser.global_max_parsing_requests_per_min
+ )
+ if llm_parser.custom_parsing_prompt is not None:
+ rag_file_parsing_config.llm_parser.custom_parsing_prompt = (
+ llm_parser.custom_parsing_prompt
+ )
+
+ local_chunk_size = chunk_size
+ local_chunk_overlap = chunk_overlap
+ if transformation_config and transformation_config.chunking_config:
+ local_chunk_size = transformation_config.chunking_config.chunk_size
+ local_chunk_overlap = transformation_config.chunking_config.chunk_overlap
+
+ rag_file_transformation_config = RagFileTransformationConfig(
+ rag_file_chunking_config=RagFileChunkingConfig(
+ fixed_length_chunking=RagFileChunkingConfig.FixedLengthChunking(
+ chunk_size=local_chunk_size,
+ chunk_overlap=local_chunk_overlap,
+ ),
+ ),
+ )
+ import_rag_files_config = ImportRagFilesConfig(
+ rag_file_transformation_config=rag_file_transformation_config,
+ max_embedding_requests_per_min=max_embedding_requests_per_min,
+ rag_file_parsing_config=rag_file_parsing_config,
+ rebuild_ann_index=rebuild_ann_index,
+ )
+
+ if global_max_embedding_requests_per_min is not None:
+ import_rag_files_config.global_max_embedding_requests_per_min = (
+ global_max_embedding_requests_per_min
+ )
+ if source is not None:
+ gapic_source = convert_source_for_rag_import(source)
+ if isinstance(gapic_source, GapicSlackSource):
+ import_rag_files_config.slack_source = gapic_source
+ if isinstance(gapic_source, GapicJiraSource):
+ import_rag_files_config.jira_source = gapic_source
+ if isinstance(gapic_source, GapicSharePointSources):
+ import_rag_files_config.share_point_sources = gapic_source
+ else:
+ uris = []
+ resource_ids = []
+ for p in paths:
+ output = convert_path_to_resource_id(p)
+ if isinstance(output, str):
+ uris.append(p)
+ else:
+ resource_ids.append(output)
+ if uris:
+ import_rag_files_config.gcs_source.uris = uris
+ if resource_ids:
+ google_drive_source = GoogleDriveSource(
+ resource_ids=resource_ids,
+ )
+ import_rag_files_config.google_drive_source = google_drive_source
+
+ if partial_failures_sink is not None:
+ if partial_failures_sink.startswith("gs://"):
+ import_rag_files_config.partial_failure_gcs_sink.output_uri_prefix = (
+ partial_failures_sink
+ )
+ elif partial_failures_sink.startswith(
+ "bq://"
+ ) or partial_failures_sink.startswith("bigquery://"):
+ import_rag_files_config.partial_failure_bigquery_sink.output_uri = (
+ partial_failures_sink
+ )
+ else:
+ raise ValueError(
+ "if provided, partial_failures_sink must be a GCS path or a BigQuery table."
+ )
+
+ request = ImportRagFilesRequest(
+ parent=corpus_name, import_rag_files_config=import_rag_files_config
+ )
+ return request
+
+
+def get_corpus_name(
+ name: str,
+) -> str:
+ if name:
+ client = create_rag_data_service_client()
+ if client.parse_rag_corpus_path(name):
+ return name
+ elif re.match("^{}$".format(_VALID_RESOURCE_NAME_REGEX), name):
+ return client.rag_corpus_path(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ rag_corpus=name,
+ )
+ else:
+ raise ValueError(
+ "name must be of the format `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` or `{rag_corpus}`"
+ )
+ return name
+
+
+def get_file_name(
+ name: str,
+ corpus_name: str,
+) -> str:
+ client = create_rag_data_service_client()
+ if client.parse_rag_file_path(name):
+ return name
+ elif re.match("^{}$".format(_VALID_RESOURCE_NAME_REGEX), name):
+ if not corpus_name:
+ raise ValueError(
+ "corpus_name must be provided if name is a `{rag_file}`, not a "
+ "full resource name"
+ " (`projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}`). "
+ )
+ return client.rag_file_path(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ rag_corpus=get_corpus_name(corpus_name),
+ rag_file=name,
+ )
+ else:
+ raise ValueError(
+ "name must be of the format"
+ " `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}`"
+ " or `{rag_file}`"
+ )
+
+
+def get_data_schema_name(
+ name: str,
+ corpus_name: str,
+) -> str:
+ """Get the full resource name for a RagDataSchema."""
+ if name:
+ if len(name.split("/")) == 8:
+ return name
+ elif re.match("^{}$".format(_VALID_RESOURCE_NAME_REGEX), name):
+ if not corpus_name:
+ raise ValueError(
+ "corpus_name must be provided if name is a `{rag_data_schema}`,"
+ " not a "
+ "full resource name"
+ " (`projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragDataSchemas/{rag_data_schema}`). "
+ )
+ return "projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragDataSchemas/{rag_data_schema}".format(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ rag_corpus=get_corpus_name(corpus_name).split("/")[-1],
+ rag_data_schema=name,
+ )
+ else:
+ raise ValueError(
+ "name must be of the format"
+ " `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragDataSchemas/{rag_data_schema}`"
+ " or `{rag_data_schema}`"
+ )
+ return name
+
+
+def get_metadata_name(
+ name: str,
+ corpus_name: str,
+ file_name: str,
+) -> str:
+ """Get the full resource name for a RagMetadata."""
+ if name:
+ if len(name.split("/")) == 10:
+ return name
+ elif re.match("^{}$".format(_VALID_RESOURCE_NAME_REGEX), name):
+ if not corpus_name or not file_name:
+ raise ValueError(
+ "corpus_name and file_name must be provided if name is a"
+ " `{rag_metadata}`, not a "
+ "full resource name"
+ " (`projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}/ragMetadata/{rag_metadata}`). "
+ )
+ return "projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}/ragMetadata/{rag_metadata}".format(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ rag_corpus=get_corpus_name(corpus_name).split("/")[-1],
+ rag_file=get_file_name(file_name, corpus_name).split("/")[-1],
+ rag_metadata=name,
+ )
+ else:
+ raise ValueError(
+ "name must be of the format"
+ " `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}/ragMetadata/{rag_metadata}`"
+ " or `{rag_metadata}`"
+ )
+ return name
+
+
+def set_corpus_type_config(
+ corpus_type_config: RagCorpusTypeConfig,
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ """Set corpus type config in GapicRagCorpus."""
+ if isinstance(corpus_type_config.corpus_type_config, DocumentCorpus):
+ rag_corpus.corpus_type_config = GapicRagCorpus.CorpusTypeConfig(
+ document_corpus=GapicRagCorpus.CorpusTypeConfig.DocumentCorpus()
+ )
+ elif isinstance(corpus_type_config.corpus_type_config, MemoryCorpus):
+ memory_corpus = GapicRagCorpus.CorpusTypeConfig.MemoryCorpus()
+ if corpus_type_config.corpus_type_config.llm_parser is not None:
+ memory_corpus.llm_parser = RagFileParsingConfig.LlmParser(
+ model_name=corpus_type_config.corpus_type_config.llm_parser.model_name
+ )
+ if (
+ corpus_type_config.corpus_type_config.llm_parser.max_parsing_requests_per_min
+ is not None
+ ):
+ memory_corpus.llm_parser.max_parsing_requests_per_min = (
+ corpus_type_config.corpus_type_config.llm_parser.max_parsing_requests_per_min
+ )
+ if (
+ corpus_type_config.corpus_type_config.llm_parser.global_max_parsing_requests_per_min
+ is not None
+ ):
+ memory_corpus.llm_parser.global_max_parsing_requests_per_min = (
+ corpus_type_config.corpus_type_config.llm_parser.global_max_parsing_requests_per_min
+ )
+ if (
+ corpus_type_config.corpus_type_config.llm_parser.custom_parsing_prompt
+ is not None
+ ):
+ memory_corpus.llm_parser.custom_parsing_prompt = (
+ corpus_type_config.corpus_type_config.llm_parser.custom_parsing_prompt
+ )
+ rag_corpus.corpus_type_config = GapicRagCorpus.CorpusTypeConfig(
+ memory_corpus=memory_corpus
+ )
+ else:
+ raise TypeError
+
+
+def set_embedding_model_config(
+ embedding_model_config: EmbeddingModelConfig,
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ """Sets the embedding model config for the rag corpus."""
+ if embedding_model_config.publisher_model and embedding_model_config.endpoint:
+ raise ValueError("publisher_model and endpoint cannot be set at the same time.")
+ if (
+ not embedding_model_config.publisher_model
+ and not embedding_model_config.endpoint
+ ):
+ raise ValueError("At least one of publisher_model and endpoint must be set.")
+ parent = initializer.global_config.common_location_path(project=None, location=None)
+
+ if embedding_model_config.publisher_model:
+ publisher_model = embedding_model_config.publisher_model
+ full_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/publishers/google/models/(?P.+?)$",
+ publisher_model,
+ )
+ resource_name = re.match(
+ r"^publishers/google/models/(?P.+?)$",
+ publisher_model,
+ )
+ if full_resource_name:
+ rag_corpus.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ publisher_model
+ )
+ elif resource_name:
+ rag_corpus.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ parent + "/" + publisher_model
+ )
+ else:
+ raise ValueError(
+ "publisher_model must be of the format `projects/{project}/locations/{location}/publishers/google/models/{model_id}` or `publishers/google/models/{model_id}`"
+ )
+
+ if embedding_model_config.endpoint:
+ endpoint = embedding_model_config.endpoint
+ full_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/endpoints/(?P.+?)$",
+ endpoint,
+ )
+ resource_name = re.match(
+ r"^endpoints/(?P.+?)$",
+ endpoint,
+ )
+ if full_resource_name:
+ rag_corpus.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ endpoint
+ )
+ elif resource_name:
+ rag_corpus.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ parent + "/" + endpoint
+ )
+ else:
+ raise ValueError(
+ "endpoint must be of the format `projects/{project}/locations/{location}/endpoints/{endpoint}` or `endpoints/{endpoint}`"
+ )
+
+
+def set_encryption_spec(
+ encryption_spec: EncryptionSpec,
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ """Sets the encryption spec for the rag corpus."""
+ # Raises value error if encryption_spec.kms_key_name is None or empty,
+ if encryption_spec.kms_key_name is None or not encryption_spec.kms_key_name:
+ raise ValueError("kms_key_name must be set if encryption_spec is set.")
+
+ # Raises value error if encryption_spec.kms_key_name is not a valid KMS key name.
+ if not re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$",
+ encryption_spec.kms_key_name,
+ ):
+ raise ValueError(
+ "kms_key_name must be of the format "
+ "`projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`"
+ )
+
+ rag_corpus.encryption_spec = encryption_spec
+
+
+def set_vector_db(
+ vector_db: Union[
+ Weaviate, VertexFeatureStore, VertexVectorSearch, Pinecone, RagManagedDb, None
+ ],
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ """Sets the vector db configuration for the rag corpus."""
+ if vector_db is None:
+ rag_corpus.rag_vector_db_config = GapicRagVectorDbConfig()
+ elif isinstance(vector_db, RagManagedDb):
+ rag_corpus.rag_vector_db_config = GapicRagVectorDbConfig(
+ rag_managed_db=_convert_rag_managed_db_to_gapic(vector_db)
+ )
+ elif isinstance(vector_db, Weaviate):
+ http_endpoint = vector_db.weaviate_http_endpoint
+ collection_name = vector_db.collection_name
+ api_key = vector_db.api_key
+
+ rag_corpus.rag_vector_db_config = GapicRagVectorDbConfig(
+ weaviate=GapicRagVectorDbConfig.Weaviate(
+ http_endpoint=http_endpoint,
+ collection_name=collection_name,
+ ),
+ api_auth=api_auth.ApiAuth(
+ api_key_config=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=api_key
+ ),
+ ),
+ )
+ elif isinstance(vector_db, VertexFeatureStore):
+ resource_name = vector_db.resource_name
+
+ rag_corpus.rag_vector_db_config = GapicRagVectorDbConfig(
+ vertex_feature_store=GapicRagVectorDbConfig.VertexFeatureStore(
+ feature_view_resource_name=resource_name,
+ ),
+ )
+ elif isinstance(vector_db, VertexVectorSearch):
+ index_endpoint = vector_db.index_endpoint
+ index = vector_db.index
+
+ rag_corpus.rag_vector_db_config = GapicRagVectorDbConfig(
+ vertex_vector_search=GapicRagVectorDbConfig.VertexVectorSearch(
+ index_endpoint=index_endpoint,
+ index=index,
+ ),
+ )
+ elif isinstance(vector_db, Pinecone):
+ index_name = vector_db.index_name
+ api_key = vector_db.api_key
+
+ rag_corpus.rag_vector_db_config = GapicRagVectorDbConfig(
+ pinecone=GapicRagVectorDbConfig.Pinecone(
+ index_name=index_name,
+ ),
+ api_auth=api_auth.ApiAuth(
+ api_key_config=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=api_key
+ ),
+ ),
+ )
+ elif isinstance(vector_db, RagManagedVertexVectorSearch):
+ rag_corpus.rag_vector_db_config = GapicRagVectorDbConfig(
+ rag_managed_vertex_vector_search=GapicRagVectorDbConfig.RagManagedVertexVectorSearch(),
+ )
+
+ else:
+ raise TypeError(
+ "vector_db must be a Weaviate, VertexFeatureStore, VertexVectorSearch, RagManagedDb, Pinecone, or RagManagedVertexVectorSearch."
+ )
+
+
+def set_vertex_ai_search_config(
+ vertex_ai_search_config: VertexAiSearchConfig,
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ if not vertex_ai_search_config.serving_config:
+ raise ValueError("serving_config must be set.")
+ engine_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)/servingConfigs/(?P.+?)$",
+ vertex_ai_search_config.serving_config,
+ )
+ data_store_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$",
+ vertex_ai_search_config.serving_config,
+ )
+ if engine_resource_name or data_store_resource_name:
+ rag_corpus.vertex_ai_search_config = GapicVertexAiSearchConfig(
+ serving_config=vertex_ai_search_config.serving_config,
+ )
+ else:
+ raise ValueError(
+ "serving_config must be of the format `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config}` or `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/servingConfigs/{serving_config}`"
+ )
+
+
+def set_backend_config(
+ backend_config: Optional[
+ Union[
+ RagVectorDbConfig,
+ None,
+ ]
+ ],
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ """Sets the vector db configuration for the rag corpus."""
+ if backend_config is None:
+ return
+
+ if backend_config.vector_db is not None:
+ vector_config = backend_config.vector_db
+ if vector_config is None:
+ rag_corpus.vector_db_config.rag_managed_db.CopyFrom(
+ GapicRagVectorDbConfig.RagManagedDb()
+ )
+ elif isinstance(vector_config, RagManagedDb):
+ rag_corpus.vector_db_config.rag_managed_db = (
+ _convert_rag_managed_db_to_gapic(vector_config)
+ )
+ elif isinstance(vector_config, VertexVectorSearch):
+ index_endpoint = vector_config.index_endpoint
+ index = vector_config.index
+
+ rag_corpus.vector_db_config.vertex_vector_search.index_endpoint = (
+ index_endpoint
+ )
+ rag_corpus.vector_db_config.vertex_vector_search.index = index
+ elif isinstance(vector_config, Pinecone):
+ index_name = vector_config.index_name
+ api_key = vector_config.api_key
+
+ rag_corpus.vector_db_config.pinecone.index_name = index_name
+ rag_corpus.vector_db_config.api_auth.api_key_config.api_key_secret_version = (
+ api_key
+ )
+ elif isinstance(vector_config, RagManagedVertexVectorSearch):
+ rag_corpus.vector_db_config.rag_managed_vertex_vector_search = (
+ GapicRagVectorDbConfig.RagManagedVertexVectorSearch()
+ )
+ else:
+ raise TypeError(
+ "backend_config must be a VertexFeatureStore,"
+ "RagManagedDb, Pinecone, or RagManagedVertexVectorSearch."
+ )
+ if backend_config.rag_embedding_model_config:
+ set_embedding_model_config(
+ backend_config.rag_embedding_model_config, rag_corpus
+ )
+
+
+def _convert_gapic_to_spanner(
+ gapic_spanner: GapicRagManagedDbConfig.Spanner,
+) -> Spanner:
+ """Converts a GapicRagManagedDbConfig.Spanner to a Spanner."""
+ spanner = Spanner()
+ if gapic_spanner.__contains__("scaled"):
+ spanner.tier = Scaled()
+ elif gapic_spanner.__contains__("basic"):
+ spanner.tier = Basic()
+ elif gapic_spanner.__contains__("unprovisioned"):
+ spanner.tier = Unprovisioned()
+ else:
+ raise ValueError("At least one of scaled, basic, or unprovisioned must be set.")
+ return spanner
+
+
+def convert_gapic_to_rag_engine_config(
+ response: GapicRagEngineConfig,
+) -> RagEngineConfig:
+ """Converts a GapicRagEngineConfig to a RagEngineConfig."""
+ rag_managed_db_config = RagManagedDbConfig()
+ if response.rag_managed_db_config.__contains__("spanner"):
+ rag_managed_db_config.mode = _convert_gapic_to_spanner(
+ response.rag_managed_db_config.spanner
+ )
+ elif response.rag_managed_db_config.__contains__("serverless"):
+ rag_managed_db_config.mode = Serverless()
+ elif response.rag_managed_db_config.__contains__("basic"):
+ rag_managed_db_config.mode = Spanner(tier=Basic())
+ elif response.rag_managed_db_config.__contains__("unprovisioned"):
+ rag_managed_db_config.mode = Spanner(tier=Unprovisioned())
+ elif response.rag_managed_db_config.__contains__("scaled"):
+ rag_managed_db_config.mode = Spanner(tier=Scaled())
+ else:
+ raise ValueError("At least one of rag_managed_db_config mode must be set.")
+ return RagEngineConfig(
+ name=response.name,
+ rag_managed_db_config=rag_managed_db_config,
+ )
+
+
+def _convert_spanner_to_gapic(
+ spanner: Spanner,
+) -> GapicRagManagedDbConfig.Spanner:
+ """Converts a Spanner to a GapicRagManagedDbConfig.Spanner."""
+ gapic_spanner = GapicRagManagedDbConfig.Spanner()
+ if isinstance(spanner.tier, Scaled):
+ gapic_spanner.scaled = GapicRagManagedDbConfig.Scaled()
+ elif isinstance(spanner.tier, Basic):
+ gapic_spanner.basic = GapicRagManagedDbConfig.Basic()
+ elif isinstance(spanner.tier, Unprovisioned):
+ gapic_spanner.unprovisioned = GapicRagManagedDbConfig.Unprovisioned()
+ return gapic_spanner
+
+
+def convert_rag_engine_config_to_gapic(
+ rag_engine_config: RagEngineConfig,
+) -> GapicRagEngineConfig:
+ """Converts a RagEngineConfig to a GapicRagEngineConfig."""
+ rag_managed_db_config = GapicRagManagedDbConfig()
+
+ if rag_engine_config.rag_managed_db_config is None or (
+ rag_engine_config.rag_managed_db_config.mode is None
+ ):
+ rag_managed_db_config = GapicRagManagedDbConfig(
+ spanner=GapicRagManagedDbConfig.Spanner(
+ basic=GapicRagManagedDbConfig.Basic()
+ )
+ )
+ else:
+ if isinstance(rag_engine_config.rag_managed_db_config.mode, Serverless):
+ rag_managed_db_config.serverless = GapicRagManagedDbConfig.Serverless()
+ elif isinstance(rag_engine_config.rag_managed_db_config.mode, Spanner):
+ rag_managed_db_config.spanner = _convert_spanner_to_gapic(
+ rag_engine_config.rag_managed_db_config.mode
+ )
+ return GapicRagEngineConfig(
+ name=rag_engine_config.name,
+ rag_managed_db_config=rag_managed_db_config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/resources.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/resources.py
new file mode 100644
index 0000000000000000000000000000000000000000..254d28852e9913bdd47516c2143d99fa0d312c11
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/preview/rag/utils/resources.py
@@ -0,0 +1,817 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import dataclasses
+from typing import List, Optional, Sequence, Union
+
+from google.cloud.aiplatform_v1beta1.types import EncryptionSpec
+
+from google.protobuf import timestamp_pb2
+
+DEPRECATION_DATE = "June 2025"
+
+
+#
+@dataclasses.dataclass
+class RagFile:
+ """RAG file (output only).
+
+ Attributes:
+ name: Generated resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file}``
+ display_name: Display name that was configured at client side.
+ description: The description of the RagFile.
+ """
+
+ name: Optional[str] = None
+ display_name: Optional[str] = None
+ description: Optional[str] = None
+
+
+@dataclasses.dataclass
+class EmbeddingModelConfig:
+ """EmbeddingModelConfig.
+
+ The representation of the embedding model config. Users input a 1P embedding
+ model as a Publisher model resource, or a 1P fine tuned embedding model
+ as an Endpoint resource.
+
+ Attributes:
+ publisher_model: 1P publisher model resource name. Format:
+ ``publishers/google/models/{model}`` or
+ ``projects/{project}/locations/{location}/publishers/google/models/{model}``
+ endpoint: 1P fine tuned embedding model resource name. Format:
+ ``endpoints/{endpoint}`` or
+ ``projects/{project}/locations/{location}/endpoints/{endpoint}``.
+ model:
+ Output only. The resource name of the model that is deployed
+ on the endpoint. Present only when the endpoint is not a
+ publisher model. Pattern:
+ ``projects/{project}/locations/{location}/models/{model}``
+ model_version_id:
+ Output only. Version ID of the model that is
+ deployed on the endpoint. Present only when the
+ endpoint is not a publisher model.
+ """
+
+ publisher_model: Optional[str] = None
+ endpoint: Optional[str] = None
+ model: Optional[str] = None
+ model_version_id: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexPredictionEndpoint:
+ """VertexPredictionEndpoint.
+
+ Attributes:
+ publisher_model: 1P publisher model resource name. Format:
+ ``publishers/google/models/{model}`` or
+ ``projects/{project}/locations/{location}/publishers/google/models/{model}``
+ endpoint: 1P fine tuned embedding model resource name. Format:
+ ``endpoints/{endpoint}`` or
+ ``projects/{project}/locations/{location}/endpoints/{endpoint}``.
+ model:
+ Output only. The resource name of the model that is deployed
+ on the endpoint. Present only when the endpoint is not a
+ publisher model. Pattern:
+ ``projects/{project}/locations/{location}/models/{model}``
+ model_version_id:
+ Output only. Version ID of the model that is
+ deployed on the endpoint. Present only when the
+ endpoint is not a publisher model.
+ """
+
+ endpoint: Optional[str] = None
+ publisher_model: Optional[str] = None
+ model: Optional[str] = None
+ model_version_id: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RagEmbeddingModelConfig:
+ """RagEmbeddingModelConfig.
+
+ Attributes:
+ vertex_prediction_endpoint: The Vertex AI Prediction Endpoint resource
+ name. Format:
+ ``projects/{project}/locations/{location}/endpoints/{endpoint}``
+ """
+
+ vertex_prediction_endpoint: Optional[VertexPredictionEndpoint] = None
+
+
+@dataclasses.dataclass
+class Weaviate:
+ """Weaviate.
+
+ Attributes:
+ weaviate_http_endpoint: The Weaviate DB instance HTTP endpoint
+ collection_name: The corresponding Weaviate collection this corpus maps to
+ api_key: The SecretManager resource name for the Weaviate DB API token. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ """
+
+ weaviate_http_endpoint: Optional[str] = None
+ collection_name: Optional[str] = None
+ api_key: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexFeatureStore:
+ """VertexFeatureStore.
+
+ Attributes:
+ resource_name: The resource name of the FeatureView. Format:
+ ``projects/{project}/locations/{location}/featureOnlineStores/
+ {feature_online_store}/featureViews/{feature_view}``
+ """
+
+ resource_name: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexVectorSearch:
+ """VertexVectorSearch.
+
+ Attributes:
+ index_endpoint (str):
+ The resource name of the Index Endpoint. Format:
+ ``projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}``
+ index (str):
+ The resource name of the Index. Format:
+ ``projects/{project}/locations/{location}/indexes/{index}``
+ """
+
+ index_endpoint: Optional[str] = None
+ index: Optional[str] = None
+
+
+@dataclasses.dataclass
+class KNN:
+ """Config for KNN search."""
+
+
+@dataclasses.dataclass
+class ANN:
+ """Config for ANN search.
+
+ RagManagedDb uses a tree-based structure to partition data and
+ facilitate faster searches. As a tradeoff, it requires longer
+ indexing time and manual triggering of index rebuild via the
+ ImportRagFiles and UpdateRagCorpus API.
+
+ Attributes:
+ tree_depth (int):
+ The depth of the tree-based structure. Only
+ depth values of 2 and 3 are supported.
+
+ Recommended value is 2 if you have if you have
+ O(10K) files in the RagCorpus and set this to 3
+ if more than that.
+
+ Default value is 2.
+ leaf_count (int):
+ Number of leaf nodes in the tree-based structure. Each leaf
+ node contains groups of closely related vectors along with
+ their corresponding centroid.
+
+ Recommended value is 10 * sqrt(num of RagFiles in your
+ RagCorpus).
+
+ Default value is 500.
+ """
+
+ tree_depth: Optional[int] = None
+ leaf_count: Optional[int] = None
+
+
+@dataclasses.dataclass
+class RagManagedDb:
+ """RagManagedDb.
+
+ Attributes:
+ retrieval_strategy: Performs a KNN or ANN search on RagCorpus.
+ Default choice is KNN if not specified.
+ """
+
+ retrieval_strategy: Optional[Union[KNN, ANN]] = None
+
+
+@dataclasses.dataclass
+class Pinecone:
+ """Pinecone.
+
+ Attributes:
+ index_name: The Pinecone index name.
+ api_key: The SecretManager resource name for the Pinecone DB API token. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ """
+
+ index_name: Optional[str] = None
+ api_key: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RagManagedVertexVectorSearch:
+ """RagManagedVertexVectorSearch.
+
+ Attributes:
+ collection_name: The resource name of the Vector Search 2.0 Collection that
+ RAG Created for the corpus. Only populated after the corpus is successfully
+ created. Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}``
+ """
+
+ collection_name: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexAiSearchConfig:
+ """VertexAiSearchConfig.
+
+ Attributes:
+ serving_config: The resource name of the Vertex AI Search serving config.
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config}``
+ or
+ ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/servingConfigs/{serving_config}``
+ """
+
+ serving_config: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RagVectorDbConfig:
+ """RagVectorDbConfig.
+
+ Attributes:
+ vector_db: Can be one of the following: Weaviate, VertexFeatureStore,
+ VertexVectorSearch, Pinecone, RagManagedDb, RagManagedVertexVectorSearch.
+ rag_embedding_model_config: The embedding model config of the Vector DB.
+ """
+
+ vector_db: Optional[
+ Union[
+ Weaviate,
+ VertexFeatureStore,
+ VertexVectorSearch,
+ Pinecone,
+ RagManagedDb,
+ RagManagedVertexVectorSearch,
+ ]
+ ] = None
+ rag_embedding_model_config: Optional[RagEmbeddingModelConfig] = None
+
+
+@dataclasses.dataclass
+class RagResource:
+ """RagResource.
+
+ The representation of the rag source. It can be used to specify corpus only
+ or ragfiles. Currently only support one corpus or multiple files from one
+ corpus. In the future we may open up multiple corpora support.
+
+ Attributes:
+ rag_corpus: A Rag corpus resource name or corpus id. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}``
+ or ``{rag_corpus_id}``.
+ rag_files_id: List of Rag file resource name or file ids in the same corpus. Format:
+ ``{rag_file}``.
+ """
+
+ rag_corpus: Optional[str] = None
+ rag_file_ids: Optional[List[str]] = None
+
+
+@dataclasses.dataclass
+class SlackChannel:
+ """SlackChannel.
+
+ Attributes:
+ channel_id: The Slack channel ID.
+ api_key: The SecretManager resource name for the Slack API token. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ See: https://api.slack.com/tutorials/tracks/getting-a-token.
+ start_time: The starting timestamp for messages to import.
+ end_time: The ending timestamp for messages to import.
+ """
+
+ channel_id: str
+ api_key: str
+ start_time: Optional[timestamp_pb2.Timestamp] = None
+ end_time: Optional[timestamp_pb2.Timestamp] = None
+
+
+@dataclasses.dataclass
+class SlackChannelsSource:
+ """SlackChannelsSource.
+
+ Attributes:
+ channels: The Slack channels.
+ """
+
+ channels: Sequence[SlackChannel]
+
+
+@dataclasses.dataclass
+class JiraQuery:
+ """JiraQuery.
+
+ Attributes:
+ email: The Jira email address.
+ jira_projects: A list of Jira projects to import in their entirety.
+ custom_queries: A list of custom JQL Jira queries to import.
+ api_key: The SecretManager version resource name for Jira API access. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ See: https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/
+ server_uri: The Jira server URI. Format:
+ ``{server}.atlassian.net``
+ """
+
+ email: str
+ jira_projects: Sequence[str]
+ custom_queries: Sequence[str]
+ api_key: str
+ server_uri: str
+
+
+@dataclasses.dataclass
+class JiraSource:
+ """JiraSource.
+
+ Attributes:
+ queries: The Jira queries.
+ """
+
+ queries: Sequence[JiraQuery]
+
+
+@dataclasses.dataclass
+class SharePointSource:
+ """SharePointSource.
+
+ Attributes:
+ sharepoint_folder_path: The path of the SharePoint folder to download
+ from.
+ sharepoint_folder_id: The ID of the SharePoint folder to download
+ from.
+ drive_name: The name of the drive to download from.
+ drive_id: The ID of the drive to download from.
+ client_id: The Application ID for the app registered in
+ Microsoft Azure Portal. The application must
+ also be configured with MS Graph permissions
+ "Files.ReadAll", "Sites.ReadAll" and
+ BrowserSiteLists.Read.All.
+ client_secret: The application secret for the app registered
+ in Azure.
+ tenant_id: Unique identifier of the Azure Active
+ Directory Instance.
+ sharepoint_site_name: The name of the SharePoint site to download
+ from. This can be the site name or the site id.
+ """
+
+ sharepoint_folder_path: Optional[str] = None
+ sharepoint_folder_id: Optional[str] = None
+ drive_name: Optional[str] = None
+ drive_id: Optional[str] = None
+ client_id: str = None
+ client_secret: str = None
+ tenant_id: str = None
+ sharepoint_site_name: str = None
+
+
+@dataclasses.dataclass
+class SharePointSources:
+ """SharePointSources.
+
+ Attributes:
+ share_point_sources: The SharePoint sources.
+ """
+
+ share_point_sources: Sequence[SharePointSource]
+
+
+@dataclasses.dataclass
+class Filter:
+ """Filter.
+
+ Attributes:
+ vector_distance_threshold: Only returns contexts with vector
+ distance smaller than the threshold.
+ vector_similarity_threshold: Only returns contexts with vector
+ similarity larger than the threshold.
+ metadata_filter: String for metadata filtering.
+ """
+
+ vector_distance_threshold: Optional[float] = None
+ vector_similarity_threshold: Optional[float] = None
+ metadata_filter: Optional[str] = None
+
+
+@dataclasses.dataclass
+class HybridSearch:
+ """HybridSearch.
+
+ Attributes:
+ alpha: Alpha value controls the weight between dense and
+ sparse vector search results. The range is [0, 1], while 0
+ means sparse vector search only and 1 means dense vector
+ search only. The default value is 0.5 which balances sparse
+ and dense vector search equally.
+ """
+
+ alpha: Optional[float] = None
+
+
+@dataclasses.dataclass
+class LlmRanker:
+ """LlmRanker.
+
+ Attributes:
+ model_name: The model name used for ranking. Only Gemini models are
+ supported for now.
+ """
+
+ model_name: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RankService:
+ """RankService.
+
+ Attributes:
+ model_name: The model name of the rank service. Format:
+ ``semantic-ranker-512@latest``
+ """
+
+ model_name: Optional[str] = None
+
+
+@dataclasses.dataclass
+class Ranking:
+ """Ranking.
+
+ Attributes:
+ rank_service: (google.cloud.aiplatform_v1beta1.types.RagRetrievalConfig.Ranking.RankService)
+ Config for Rank Service.
+ llm_ranker (google.cloud.aiplatform_v1beta1.types.RagRetrievalConfig.Ranking.LlmRanker):
+ Config for LlmRanker.
+ """
+
+ rank_service: Optional[RankService] = None
+ llm_ranker: Optional[LlmRanker] = None
+
+
+@dataclasses.dataclass
+class RagRetrievalConfig:
+ """RagRetrievalConfig.
+
+ Attributes:
+ top_k: The number of contexts to retrieve.
+ filter: Config for filters.
+ hybrid_search (google.cloud.aiplatform_v1beta1.types.RagRetrievalConfig.HybridSearch):
+ Config for Hybrid Search.
+ ranking (google.cloud.aiplatform_v1beta1.types.RagRetrievalConfig.Ranking):
+ Config for ranking and reranking.
+ """
+
+ top_k: Optional[int] = None
+ filter: Optional[Filter] = None
+ hybrid_search: Optional[HybridSearch] = None
+ ranking: Optional[Ranking] = None
+
+
+@dataclasses.dataclass
+class ChunkingConfig:
+ """ChunkingConfig.
+
+ Attributes:
+ chunk_size: The size of each chunk.
+ chunk_overlap: The size of the overlap between chunks.
+ """
+
+ chunk_size: int
+ chunk_overlap: int
+
+
+@dataclasses.dataclass
+class TransformationConfig:
+ """TransformationConfig.
+
+ Attributes:
+ chunking_config: The chunking config.
+ """
+
+ chunking_config: Optional[ChunkingConfig] = None
+
+
+@dataclasses.dataclass
+class LayoutParserConfig:
+ """Configuration for the Document AI Layout Parser Processor.
+
+ Attributes:
+ processor_name (str):
+ The full resource name of a Document AI processor or processor
+ version. The processor must have type `LAYOUT_PARSER_PROCESSOR`.
+ Format:
+ - `projects/{project_id}/locations/{location}/processors/{processor_id}`
+ - `projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}`
+ max_parsing_requests_per_min (int):
+ The maximum number of requests the job is allowed to make to the
+ Document AI processor per minute. Consult
+ https://cloud.google.com/document-ai/quotas and the Quota page for
+ your project to set an appropriate value here. If unspecified, a
+ default value of 120 QPM will be used.
+ global_max_parsing_requests_per_min (int):
+ The maximum number of requests the job is allowed to make to
+ the Document AI processor per minute in this project.
+ Consult https://cloud.google.com/document-ai/quotas and the
+ Quota page for your project to set an appropriate value
+ here. If this value is not specified,
+ max_parsing_requests_per_min will be used by indexing
+ pipeline as the global limit.
+ """
+
+ processor_name: str
+ max_parsing_requests_per_min: Optional[int] = None
+ global_max_parsing_requests_per_min: Optional[int] = None
+
+
+@dataclasses.dataclass
+class LlmParserConfig:
+ """Configuration for the LLM Parser Processor.
+
+ Attributes:
+ model_name (str):
+ The full resource name of a Vertex AI model. Format:
+ - `projects/{project_id}/locations/{location}/publishers/google/models/{model_id}`
+ - `projects/{project_id}/locations/{location}/models/{model_id}`
+ max_parsing_requests_per_min (int):
+ The maximum number of requests the job is allowed to make to the
+ Vertex AI model per minute. Consult
+ https://cloud.google.com/vertex-ai/generative-ai/docs/quotas and
+ the Quota page for your project to set an appropriate value here.
+ If unspecified, a default value of 5000 QPM will be used.
+ global_max_parsing_requests_per_min (int):
+ The maximum number of requests the job is allowed to make to
+ the LLM model per minute in this project. Consult
+ https://cloud.google.com/vertex-ai/generative-ai/docs/quotas
+ and your document size to set an appropriate value here. If
+ this value is not specified, max_parsing_requests_per_min
+ will be used by indexing pipeline job as the global limit.
+ custom_parsing_prompt (str):
+ A custom prompt to use for parsing.
+ """
+
+ model_name: str
+ max_parsing_requests_per_min: Optional[int] = None
+ global_max_parsing_requests_per_min: Optional[int] = None
+ custom_parsing_prompt: Optional[str] = None
+
+
+@dataclasses.dataclass
+class Scaled:
+ """Scaled tier offers production grade performance along with
+
+ autoscaling functionality. It is suitable for customers with large
+ amounts of data or performance sensitive workloads.
+ """
+
+
+@dataclasses.dataclass
+class Basic:
+ """Basic tier is a cost-effective and low compute tier suitable for the following cases:
+
+ * Experimenting with RagManagedDb.
+ * Small data size.
+ * Latency insensitive workload.
+ * Only using RAG Engine with external vector DBs.
+
+ NOTE: This is the default tier if not explicitly chosen.
+ """
+
+
+@dataclasses.dataclass
+class Unprovisioned:
+ """Disables the RAG Engine service and deletes all your data held within
+ this service. This will halt the billing of the service.
+
+ NOTE: Once deleted the data cannot be recovered. To start using
+ RAG Engine again, you will need to update the tier by calling the
+ UpdateRagEngineConfig API.
+ """
+
+
+@dataclasses.dataclass
+class Spanner:
+ """Switches RAG Engine to use Spanner/RagManagedDb as the backend.
+
+ Attributes:
+ tier: The tier of the RagManagedDb. The default tier is Basic.
+
+ NOTE: This is the default mode if not explicitly chosen.
+ """
+
+ tier: Optional[Union[Basic, Scaled, Unprovisioned]] = None
+
+
+@dataclasses.dataclass
+class Serverless:
+ """Switches RAG Engine to use serverless mode as the backend."""
+
+
+@dataclasses.dataclass
+class RagManagedDbConfig:
+ """RagManagedDbConfig.
+
+ The config of the RagManagedDb used by RagEngine.
+
+ Attributes:
+ mode: The choice of backend for your RAG Engine. The default mode is
+ Spanner with Basic tier.
+ """
+
+ mode: Optional[Union[Spanner, Serverless]] = None
+
+
+@dataclasses.dataclass
+class RagEngineConfig:
+ """RagEngineConfig.
+
+ Attributes:
+ name: Generated resource name for singleton resource. Format:
+ ``projects/{project}/locations/{location}/ragEngineConfig``
+ rag_managed_db_config: The config of the RagManagedDb used by RagEngine.
+ The default tier is Basic.
+ """
+
+ name: str
+ rag_managed_db_config: Optional[RagManagedDbConfig] = None
+
+
+@dataclasses.dataclass
+class DocumentCorpus:
+ """DocumentCorpus."""
+
+
+@dataclasses.dataclass
+class MemoryCorpus:
+ """MemoryCorpus.
+
+ Attributes:
+ llm_parser: The LLM parser to use for the memory corpus.
+ """
+
+ llm_parser: Optional[LlmParserConfig] = None
+
+
+@dataclasses.dataclass
+class RagCorpusTypeConfig:
+ """CorpusTypeConfig.
+
+ Attributes:
+ corpus_type_config: Can be one of the following: DocumentCorpus,
+ MemoryCorpus.
+ """
+
+ corpus_type_config: Optional[Union[DocumentCorpus, MemoryCorpus]] = None
+
+
+@dataclasses.dataclass
+class RagCorpus:
+ """RAG corpus(output only).
+
+ Attributes:
+ name: Generated resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}``
+ display_name: Display name that was configured at client side.
+ description: The description of the RagCorpus.
+ corpus_type_config: The corpus type config of the RagCorpus.
+ vertex_ai_search_config: The Vertex AI Search config of the RagCorpus.
+ backend_config: The backend config of the RagCorpus. It can specify a
+ Vector DB and/or the embedding model config.
+ encryption_spec: The encryption spec of the RagCorpus. Immutable.
+ """
+
+ name: Optional[str] = None
+ display_name: Optional[str] = None
+ description: Optional[str] = None
+ corpus_type_config: Optional[RagCorpusTypeConfig] = None
+ vertex_ai_search_config: Optional[VertexAiSearchConfig] = None
+ backend_config: Optional[RagVectorDbConfig] = None
+ encryption_spec: Optional[EncryptionSpec] = None
+
+
+@dataclasses.dataclass
+class RagMetadataSchemaDetails:
+ """Data schema details indicates the data type and the data
+
+ struct corresponding to the key of user specified metadata.
+
+ Attributes:
+ type (str): Type of the metadata.
+ list_config (RagMetadataSchemaDetails.ListConfig): Config for List data
+ type.
+ granularity (str): The granularity associated with this RagMetadataSchema.
+ search_strategy (RagMetadataSchemaDetails.SearchStrategy): The search
+ strategy for the metadata value of the key.
+ """
+
+ @dataclasses.dataclass
+ class ListConfig:
+ """Config for List data type.
+
+ Attributes:
+ value_schema (RagMetadataSchemaDetails): The value's data type in the
+ list.
+ """
+
+ value_schema: Optional["RagMetadataSchemaDetails"] = None
+
+ @dataclasses.dataclass
+ class SearchStrategy:
+ """The search strategy for the metadata value of the key.
+
+ Attributes:
+ search_strategy_type (str): The search strategy type to be applied on
+ the metadata key.
+ """
+
+ search_strategy_type: Optional[str] = None
+
+ type: Optional[str] = None
+ list_config: Optional[ListConfig] = None
+ granularity: Optional[str] = None
+ search_strategy: Optional[SearchStrategy] = None
+
+
+@dataclasses.dataclass
+class RagDataSchema:
+ """The schema of the user specified metadata.
+
+ Attributes:
+ name (str): Identifier. Resource name of the data schema.
+ key (str): Required. The key of this data schema.
+ schema_details (RagMetadataSchemaDetails): The schema details mapping to
+ the key.
+ """
+
+ name: Optional[str] = None
+ key: Optional[str] = None
+ schema_details: Optional[RagMetadataSchemaDetails] = None
+
+
+@dataclasses.dataclass
+class MetadataValue:
+ """The value of metadata.
+
+ Attributes:
+ string_value (str): The string value.
+ int_value (int): The int value.
+ float_value (float): The float value.
+ bool_value (bool): The bool value.
+ """
+
+ string_value: Optional[str] = None
+ int_value: Optional[int] = None
+ float_value: Optional[float] = None
+ bool_value: Optional[bool] = None
+
+
+@dataclasses.dataclass
+class RagMetadata:
+ """Metadata for RagFile provided by users.
+
+ Attributes:
+ name (str): Identifier. Resource name of the RagMetadata.
+ user_specified_metadata (UserSpecifiedMetadata): User provided metadata.
+ """
+
+ name: Optional[str] = None
+ user_specified_metadata: Optional["UserSpecifiedMetadata"] = None
+
+
+@dataclasses.dataclass
+class UserSpecifiedMetadata:
+ """Metadata provided by users.
+
+ Attributes:
+ values (Dict[str, MetadataValue]): Required. The values of the metadata.
+ """
+
+ values: dict[str, MetadataValue]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3224c90991c9f8478a79c9eb75085344cbd3c83
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__init__.py
@@ -0,0 +1,127 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from agentplatform.rag.rag_data import (
+ add_inline_citations_and_references,
+ create_corpus,
+ delete_corpus,
+ delete_file,
+ get_corpus,
+ get_file,
+ get_rag_engine_config,
+ import_files,
+ import_files_async,
+ list_corpora,
+ list_files,
+ update_corpus,
+ update_rag_engine_config,
+ upload_file,
+)
+from agentplatform.rag.rag_retrieval import (
+ ask_contexts,
+ async_retrieve_contexts,
+ retrieval_query,
+)
+from agentplatform.rag.rag_store import (
+ Retrieval,
+ VertexRagStore,
+)
+from agentplatform.rag.utils.resources import (
+ Basic,
+ ChunkingConfig,
+ Filter,
+ JiraQuery,
+ JiraSource,
+ LayoutParserConfig,
+ LlmParserConfig,
+ LlmRanker,
+ Pinecone,
+ RagCitedGenerationResponse,
+ RagCorpus,
+ RagEmbeddingModelConfig,
+ RagEngineConfig,
+ RagFile,
+ RagManagedDb,
+ RagManagedDbConfig,
+ RagResource,
+ RagRetrievalConfig,
+ RagVectorDbConfig,
+ RankService,
+ Ranking,
+ Scaled,
+ SharePointSource,
+ SharePointSources,
+ SlackChannel,
+ SlackChannelsSource,
+ TransformationConfig,
+ Unprovisioned,
+ VertexAiSearchConfig,
+ VertexPredictionEndpoint,
+ VertexVectorSearch,
+)
+
+
+__all__ = (
+ "Basic",
+ "ChunkingConfig",
+ "Filter",
+ "JiraQuery",
+ "JiraSource",
+ "LayoutParserConfig",
+ "LlmParserConfig",
+ "LlmRanker",
+ "Pinecone",
+ "RagCorpus",
+ "RagEmbeddingModelConfig",
+ "RagEngineConfig",
+ "RagFile",
+ "RagCitedGenerationResponse",
+ "RagManagedDb",
+ "RagManagedDbConfig",
+ "RagResource",
+ "RagRetrievalConfig",
+ "RagVectorDbConfig",
+ "Ranking",
+ "RankService",
+ "Retrieval",
+ "Scaled",
+ "SharePointSource",
+ "SharePointSources",
+ "SlackChannel",
+ "SlackChannelsSource",
+ "TransformationConfig",
+ "Unprovisioned",
+ "VertexAiSearchConfig",
+ "VertexRagStore",
+ "VertexPredictionEndpoint",
+ "VertexVectorSearch",
+ "ask_contexts",
+ "create_corpus",
+ "delete_corpus",
+ "delete_file",
+ "get_corpus",
+ "get_rag_engine_config",
+ "get_file",
+ "import_files",
+ "import_files_async",
+ "list_corpora",
+ "list_files",
+ "retrieval_query",
+ "async_retrieve_contexts",
+ "upload_file",
+ "update_corpus",
+ "update_rag_engine_config",
+ "add_inline_citations_and_references",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..493373efd6e72fdf6005364d35adb8fedbdafa3a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_data.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_data.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37e390a14c3ac3143d8ff6905bd580f8f8e70f5a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_data.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_inline_citations.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_inline_citations.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d80ee2fb7741a2c07490d420c024281d3a7661c1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_inline_citations.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_retrieval.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_retrieval.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45d57b7974beaeebb6990c77bf68157faf175f44
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_retrieval.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa2f0d896c82e06c0aa033f73cb3ae7114248564
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/__pycache__/rag_store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_data.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..39e6661a5db7460b49fa4611322bbf06d8786b46
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_data.py
@@ -0,0 +1,1152 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""RAG data management SDK."""
+
+from typing import Optional, Sequence, Union
+from google import auth
+from google.api_core import operation_async
+from google.auth.transport import requests as google_auth_requests
+from google.cloud import aiplatform
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform import utils
+from google.cloud.aiplatform_v1 import (
+ CreateRagCorpusRequest,
+ DeleteRagCorpusRequest,
+ DeleteRagFileRequest,
+ GetRagCorpusRequest,
+ GetRagEngineConfigRequest,
+ GetRagFileRequest,
+ ImportRagFilesResponse,
+ ListRagCorporaRequest,
+ ListRagFilesRequest,
+ RagCorpus as GapicRagCorpus,
+ UpdateRagCorpusRequest,
+ UpdateRagEngineConfigRequest,
+)
+from google.cloud.aiplatform_v1.services.vertex_rag_data_service.pagers import (
+ ListRagCorporaPager,
+ ListRagFilesPager,
+)
+from agentplatform.rag.rag_inline_citations import (
+ format_bibliography,
+ populate_cited_chunk_references,
+)
+from agentplatform.rag.utils import (
+ _gapic_utils,
+)
+from google.cloud.aiplatform_v1.types import EncryptionSpec
+from agentplatform.rag.utils.resources import (
+ JiraSource,
+ LayoutParserConfig,
+ LlmParserConfig,
+ RagCitedGenerationResponse,
+ RagCorpus,
+ RagEngineConfig,
+ RagFile,
+ RagVectorDbConfig,
+ SharePointSources,
+ SlackChannelsSource,
+ VertexAiSearchConfig,
+ TransformationConfig,
+)
+
+
+def create_corpus(
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ vertex_ai_search_config: Optional[VertexAiSearchConfig] = None,
+ backend_config: Optional[
+ Union[
+ RagVectorDbConfig,
+ None,
+ ]
+ ] = None,
+ encryption_spec: Optional[EncryptionSpec] = None,
+ timeout: int = 600,
+) -> RagCorpus:
+ """Creates a new RagCorpus resource.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform import rag
+
+ agentplatform.init(project="my-project")
+
+ rag_corpus = rag.create_corpus(
+ display_name="my-corpus-1",
+ )
+ ```
+
+ Args:
+ display_name: If not provided, SDK will create one. The display name of
+ the RagCorpus. The name can be up to 128 characters long and can consist
+ of any UTF-8 characters.
+ description: The description of the RagCorpus.
+ vertex_ai_search_config: The Vertex AI Search config of the RagCorpus.
+ Note: backend_config cannot be set if vertex_ai_search_config is
+ specified.
+ backend_config: The backend config of the RagCorpus, specifying a data
+ store and/or embedding model.
+ encryption_spec: The encryption spec of the RagCorpus.
+ timeout: Default is 600 seconds.
+
+ Returns:
+ RagCorpus.
+ Raises:
+ RuntimeError: Failed in RagCorpus creation due to exception.
+ RuntimeError: Failed in RagCorpus creation due to operation error.
+ """
+ if vertex_ai_search_config and backend_config:
+ raise ValueError(
+ "Only one of vertex_ai_search_config or backend_config can be set."
+ )
+
+ if not display_name:
+ display_name = "vertex-" + utils.timestamped_unique_name()
+ parent = initializer.global_config.common_location_path(project=None, location=None)
+
+ rag_corpus = GapicRagCorpus(display_name=display_name, description=description)
+
+ if backend_config:
+ _gapic_utils.set_backend_config(
+ backend_config=backend_config,
+ rag_corpus=rag_corpus,
+ )
+ elif vertex_ai_search_config:
+ _gapic_utils.set_vertex_ai_search_config(
+ vertex_ai_search_config=vertex_ai_search_config,
+ rag_corpus=rag_corpus,
+ )
+
+ if encryption_spec:
+ _gapic_utils.set_encryption_spec(
+ encryption_spec=encryption_spec,
+ rag_corpus=rag_corpus,
+ )
+
+ request = CreateRagCorpusRequest(
+ parent=parent,
+ rag_corpus=rag_corpus,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+
+ try:
+ response = client.create_rag_corpus(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagCorpus creation due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_corpus(response.result(timeout=timeout))
+
+
+def update_corpus(
+ corpus_name: str,
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ vertex_ai_search_config: Optional[VertexAiSearchConfig] = None,
+ backend_config: Optional[
+ Union[
+ RagVectorDbConfig,
+ None,
+ ]
+ ] = None,
+ timeout: int = 600,
+) -> RagCorpus:
+ """Updates a RagCorpus resource.
+
+ It is intended to update 3rd party vector DBs (Vector Search, Vertex AI
+ Feature Store, Weaviate, Pinecone) but not Vertex RagManagedDb.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform import rag
+
+ agentplatform.init(project="my-project")
+
+ rag_corpus = rag.update_corpus(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ display_name="my-corpus-1",
+ )
+ ```
+
+ Args:
+ corpus_name: The name of the RagCorpus resource to update. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`` or
+ ``{rag_corpus}``.
+ display_name: If not provided, the display name will not be updated. The
+ display name of the RagCorpus. The name can be up to 128 characters long
+ and can consist of any UTF-8 characters.
+ description: The description of the RagCorpus. If not provided, the
+ description will not be updated.
+ vertex_ai_search_config: The Vertex AI Search config of the RagCorpus. If
+ not provided, the Vertex AI Search config will not be updated.
+ Note: backend_config cannot be set if vertex_ai_search_config is
+ specified.
+ backend_config: The backend config of the RagCorpus, specifying a data
+ store and/or embedding model.
+ timeout: Default is 600 seconds.
+
+ Returns:
+ RagCorpus.
+ Raises:
+ RuntimeError: Failed in RagCorpus update due to exception.
+ RuntimeError: Failed in RagCorpus update due to operation error.
+ """
+ if vertex_ai_search_config and backend_config:
+ raise ValueError(
+ "Only one of vertex_ai_search_config or backend_config can be set."
+ )
+
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ if display_name and description:
+ rag_corpus = GapicRagCorpus(
+ name=corpus_name, display_name=display_name, description=description
+ )
+ elif display_name:
+ rag_corpus = GapicRagCorpus(name=corpus_name, display_name=display_name)
+ elif description:
+ rag_corpus = GapicRagCorpus(name=corpus_name, description=description)
+ else:
+ rag_corpus = GapicRagCorpus(name=corpus_name)
+
+ if backend_config:
+ _gapic_utils.set_backend_config(
+ backend_config=backend_config,
+ rag_corpus=rag_corpus,
+ )
+
+ if vertex_ai_search_config:
+ _gapic_utils.set_vertex_ai_search_config(
+ vertex_ai_search_config=vertex_ai_search_config,
+ rag_corpus=rag_corpus,
+ )
+
+ request = UpdateRagCorpusRequest(
+ rag_corpus=rag_corpus,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+
+ try:
+ response = client.update_rag_corpus(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagCorpus update due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_corpus_no_embedding_model_config(
+ response.result(timeout=timeout)
+ )
+
+
+def get_corpus(name: str) -> RagCorpus:
+ """
+ Get an existing RagCorpus.
+
+ Args:
+ name: An existing RagCorpus resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ Returns:
+ RagCorpus.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(name)
+ request = GetRagCorpusRequest(name=corpus_name)
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.get_rag_corpus(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in getting the RagCorpus due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_corpus(response)
+
+
+def list_corpora(
+ page_size: Optional[int] = None, page_token: Optional[str] = None
+) -> ListRagCorporaPager:
+ """
+ List all RagCorpora in the same project and location.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform import rag
+
+ agentplatform.init(project="my-project")
+
+ # List all corpora.
+ rag_corpora = list(rag.list_corpora())
+
+ # Alternatively, return a ListRagCorporaPager.
+ pager_1 = rag.list_corpora(page_size=10)
+ # Then get the next page, use the generated next_page_token from the last pager.
+ pager_2 = rag.list_corpora(page_size=10, page_token=pager_1.next_page_token)
+
+ ```
+ Args:
+ page_size: The standard list page size. Leaving out the page_size
+ causes all of the results to be returned.
+ page_token: The standard list page token.
+
+ Returns:
+ ListRagCorporaPager.
+ """
+ parent = initializer.global_config.common_location_path(project=None, location=None)
+ request = ListRagCorporaRequest(
+ parent=parent,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ pager = client.list_rag_corpora(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in listing the RagCorpora due to: ", e) from e
+
+ return pager
+
+
+def delete_corpus(name: str) -> None:
+ """
+ Delete an existing RagCorpus.
+
+ Args:
+ name: An existing RagCorpus resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(name)
+ request = DeleteRagCorpusRequest(name=corpus_name)
+
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ client.delete_rag_corpus(request=request)
+ print("Successfully deleted the RagCorpus.")
+ except Exception as e:
+ raise RuntimeError("Failed in RagCorpus deletion due to: ", e) from e
+ return None
+
+
+def upload_file(
+ corpus_name: str,
+ path: Union[str, Sequence[str]],
+ display_name: Optional[str] = None,
+ description: Optional[str] = None,
+ transformation_config: Optional[TransformationConfig] = None,
+ timeout: int = 600,
+) -> RagFile:
+ """
+ Synchronous file upload to an existing RagCorpus.
+
+ Example usage:
+
+ ```
+ import agentplatform
+ from agentplatform import rag
+
+ agentplatform.init(project="my-project")
+
+ // Optional.
+ transformation_config = TransformationConfig(
+ chunking_config=ChunkingConfig(
+ chunk_size=1024,
+ chunk_overlap=200,
+ ),
+ )
+
+ rag_file = rag.upload_file(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ display_name="my_file.txt",
+ path="usr/home/my_file.txt",
+ transformation_config=transformation_config,
+ )
+ ```
+
+ Args:
+ corpus_name: The name of the RagCorpus resource into which to upload the file.
+ Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ path: A local file path. For example,
+ "usr/home/my_file.txt".
+ display_name: The display name of the data file.
+ description: The description of the RagFile.
+ transformation_config: The config for transforming the RagFile, like chunking.
+ timeout: Default is 600 seconds.
+
+ Returns:
+ RagFile.
+ Raises:
+ RuntimeError: Failed in RagFile upload.
+ ValueError: RagCorpus is not found.
+ RuntimeError: Failed in indexing the RagFile.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ location = initializer.global_config.location
+ # GAPIC doesn't expose a path (scotty). Use requests API instead
+ if display_name is None:
+ display_name = "vertex-" + utils.timestamped_unique_name()
+ headers = {"X-Goog-Upload-Protocol": "multipart"}
+ if not initializer.global_config.api_endpoint:
+ request_endpoint = "{}-{}".format(
+ location, aiplatform.constants.base.API_BASE_PATH
+ )
+ else:
+ request_endpoint = initializer.global_config.api_endpoint
+ upload_request_uri = "https://{}/upload/v1/{}/ragFiles:upload".format(
+ request_endpoint,
+ corpus_name,
+ )
+ js_rag_file = {"rag_file": {"display_name": display_name}}
+
+ if description:
+ js_rag_file["rag_file"]["description"] = description
+
+ if transformation_config and transformation_config.chunking_config:
+ chunk_size = transformation_config.chunking_config.chunk_size
+ chunk_overlap = transformation_config.chunking_config.chunk_overlap
+ js_rag_file["upload_rag_file_config"] = {
+ "rag_file_transformation_config": {
+ "rag_file_chunking_config": {
+ "fixed_length_chunking": {
+ "chunk_size": chunk_size,
+ "chunk_overlap": chunk_overlap,
+ }
+ }
+ }
+ }
+
+ files = {
+ "metadata": (None, str(js_rag_file)),
+ "file": open(path, "rb"),
+ }
+ credentials = initializer.global_config.credentials
+ if not credentials:
+ credentials, _ = auth.default()
+ authorized_session = google_auth_requests.AuthorizedSession(credentials=credentials)
+ try:
+ response = authorized_session.post(
+ url=upload_request_uri,
+ files=files,
+ headers=headers,
+ timeout=timeout,
+ )
+ except Exception as e:
+ raise RuntimeError("Failed in uploading the RagFile due to: ", e) from e
+
+ if response.status_code == 404:
+ raise ValueError(
+ "RagCorpus '%s' is not found: %s", corpus_name, upload_request_uri
+ )
+ if response.json().get("error"):
+ raise RuntimeError(
+ "Failed in indexing the RagFile due to: ", response.json().get("error")
+ )
+ return _gapic_utils.convert_json_to_rag_file(response.json())
+
+
+def import_files(
+ corpus_name: str,
+ paths: Optional[Sequence[str]] = None,
+ source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
+ transformation_config: Optional[TransformationConfig] = None,
+ timeout: int = 600,
+ max_embedding_requests_per_min: int = 1000,
+ import_result_sink: Optional[str] = None,
+ layout_parser: Optional[LayoutParserConfig] = None,
+ llm_parser: Optional[LlmParserConfig] = None,
+) -> ImportRagFilesResponse:
+ """
+ Import files to an existing RagCorpus, wait until completion.
+
+ Example usage:
+
+ ```
+ import agentplatform
+ from agentplatform import rag
+ from google.protobuf import timestamp_pb2
+
+ agentplatform.init(project="my-project")
+ # Google Drive example
+ paths = [
+ "https://drive.google.com/file/d/123",
+ "https://drive.google.com/drive/folders/456"
+ ]
+ # Google Cloud Storage example
+ paths = ["gs://my_bucket/my_files_dir", ...]
+
+ transformation_config = TransformationConfig(
+ chunking_config=ChunkingConfig(
+ chunk_size=1024,
+ chunk_overlap=200,
+ ),
+ )
+
+ response = rag.import_files(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ paths=paths,
+ transformation_config=transformation_config,
+ )
+
+ # Slack example
+ start_time = timestamp_pb2.Timestamp()
+ start_time.FromJsonString('2020-12-31T21:33:44Z')
+ end_time = timestamp_pb2.Timestamp()
+ end_time.GetCurrentTime()
+ source = rag.SlackChannelsSource(
+ channels = [
+ SlackChannel("channel1", "api_key1"),
+ SlackChannel("channel2", "api_key2", start_time, end_time)
+ ],
+ )
+ # Jira Example
+ jira_query = rag.JiraQuery(
+ email="xxx@yyy.com",
+ jira_projects=["project1", "project2"],
+ custom_queries=["query1", "query2"],
+ api_key="api_key",
+ server_uri="server.atlassian.net"
+ )
+ source = rag.JiraSource(
+ queries=[jira_query],
+ )
+
+ response = rag.import_files(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ source=source,
+ transformation_config=transformation_config,
+ )
+
+ # SharePoint Example.
+ sharepoint_query = rag.SharePointSource(
+ sharepoint_folder_path="https://my-sharepoint-site.com/my-folder",
+ sharepoint_site_name="my-sharepoint-site.com",
+ client_id="my-client-id",
+ client_secret="my-client-secret",
+ tenant_id="my-tenant-id",
+ drive_id="my-drive-id",
+ )
+ source = rag.SharePointSources(
+ share_point_sources=[sharepoint_query],
+ )
+
+ # Return the number of imported RagFiles after completion.
+ print(response.imported_rag_files_count)
+
+ # Document AI Layout Parser example.
+ parser = LayoutParserConfig(
+ processor_name="projects/my-project/locations/us-central1/processors/my-processor-id",
+ max_parsing_requests_per_min=120,
+ )
+ response = rag.import_files(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ paths=paths,
+ parser=parser,
+ )
+
+ ```
+ Args:
+ corpus_name: The name of the RagCorpus resource into which to import files.
+ Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ paths: A list of uris. Eligible uris will be Google Cloud Storage
+ directory ("gs://my-bucket/my_dir") or a Google Drive url for file
+ (https://drive.google.com/file/... or folder
+ "https://drive.google.com/corp/drive/folders/...").
+ source: The source of the Slack or Jira import.
+ Must be either a SlackChannelsSource or JiraSource.
+ transformation_config: The config for transforming the imported
+ RagFiles.
+ max_embedding_requests_per_min:
+ Optional. The max number of queries per
+ minute that this job is allowed to make to the
+ embedding model specified on the corpus. This
+ value is specific to this job and not shared
+ across other import jobs. Consult the Quotas
+ page on the project to set an appropriate value
+ here. If unspecified, a default value of 1,000
+ QPM would be used.
+ timeout: Default is 600 seconds.
+ import_result_sink: Either a GCS path to store import results or a
+ BigQuery table to store import results. The format is
+ "gs://my-bucket/my/object.ndjson" for GCS or
+ "bq://my-project.my-dataset.my-table" for BigQuery. An existing GCS
+ object cannot be used. However, the BigQuery table may or may not
+ exist - if it does not exist, it will be created. If it does exist,
+ the schema will be checked and the import results will be appended
+ to the table.
+ parser: Document parser to use. Should be either None (default parser),
+ or a LayoutParserConfig (to parse documents using a Document AI
+ Layout Parser processor).
+ Returns:
+ ImportRagFilesResponse.
+ """
+ if source is not None and paths is not None:
+ raise ValueError("Only one of source or paths must be passed in at a time")
+ if source is None and paths is None:
+ raise ValueError("One of source or paths must be passed in")
+ if layout_parser is not None and llm_parser is not None:
+ raise ValueError(
+ "Only one of layout_parser or llm_parser may be passed in at a time"
+ )
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ request = _gapic_utils.prepare_import_files_request(
+ corpus_name=corpus_name,
+ paths=paths,
+ source=source,
+ transformation_config=transformation_config,
+ max_embedding_requests_per_min=max_embedding_requests_per_min,
+ import_result_sink=import_result_sink,
+ layout_parser=layout_parser,
+ llm_parser=llm_parser,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.import_rag_files(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in importing the RagFiles due to: ", e) from e
+
+ return response.result(timeout=timeout)
+
+
+async def import_files_async(
+ corpus_name: str,
+ paths: Optional[Sequence[str]] = None,
+ source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
+ transformation_config: Optional[TransformationConfig] = None,
+ max_embedding_requests_per_min: int = 1000,
+ import_result_sink: Optional[str] = None,
+ layout_parser: Optional[LayoutParserConfig] = None,
+ llm_parser: Optional[LlmParserConfig] = None,
+) -> operation_async.AsyncOperation:
+ """
+ Import files to an existing RagCorpus asynchronously.
+
+ Example usage:
+
+ ```
+ import agentplatform
+ from agentplatform import rag
+ from google.protobuf import timestamp_pb2
+
+ agentplatform.init(project="my-project")
+
+ # Google Drive example
+ paths = [
+ "https://drive.google.com/file/d/123",
+ "https://drive.google.com/drive/folders/456"
+ ]
+ # Google Cloud Storage example
+ paths = ["gs://my_bucket/my_files_dir", ...]
+
+ transformation_config = TransformationConfig(
+ chunking_config=ChunkingConfig(
+ chunk_size=1024,
+ chunk_overlap=200,
+ ),
+ )
+
+ response = await rag.import_files_async(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ paths=paths,
+ transformation_config=transformation_config,
+ )
+
+ # Slack example
+ start_time = timestamp_pb2.Timestamp()
+ start_time.FromJsonString('2020-12-31T21:33:44Z')
+ end_time = timestamp_pb2.Timestamp()
+ end_time.GetCurrentTime()
+ source = rag.SlackChannelsSource(
+ channels = [
+ SlackChannel("channel1", "api_key1"),
+ SlackChannel("channel2", "api_key2", start_time, end_time)
+ ],
+ )
+ # Jira Example
+ jira_query = rag.JiraQuery(
+ email="xxx@yyy.com",
+ jira_projects=["project1", "project2"],
+ custom_queries=["query1", "query2"],
+ api_key="api_key",
+ server_uri="server.atlassian.net"
+ )
+ source = rag.JiraSource(
+ queries=[jira_query],
+ )
+
+ response = await rag.import_files_async(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ source=source,
+ transformation_config=transformation_config,
+ )
+
+ # SharePoint Example.
+ sharepoint_query = rag.SharePointSource(
+ sharepoint_folder_path="https://my-sharepoint-site.com/my-folder",
+ sharepoint_site_name="my-sharepoint-site.com",
+ client_id="my-client-id",
+ client_secret="my-client-secret",
+ tenant_id="my-tenant-id",
+ drive_id="my-drive-id",
+ )
+ source = rag.SharePointSources(
+ share_point_sources=[sharepoint_query],
+ )
+
+ # Document AI Layout Parser example.
+ parser = LayoutParserConfig(
+ processor_name="projects/my-project/locations/us-central1/processors/my-processor-id",
+ max_parsing_requests_per_min=120,
+ )
+ response = rag.import_files_async(
+ corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
+ paths=paths,
+ parser=parser,
+ )
+
+ # Get the result.
+ await response.result()
+
+ ```
+ Args:
+ corpus_name: The name of the RagCorpus resource into which to import files.
+ Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ paths: A list of uris. Eligible uris will be Google Cloud Storage
+ directory ("gs://my-bucket/my_dir") or a Google Drive url for file
+ (https://drive.google.com/file/... or folder
+ "https://drive.google.com/corp/drive/folders/...").
+ source: The source of the Slack or Jira import.
+ Must be either a SlackChannelsSource or JiraSource.
+ transformation_config: The config for transforming the imported
+ RagFiles.
+ max_embedding_requests_per_min:
+ Optional. The max number of queries per
+ minute that this job is allowed to make to the
+ embedding model specified on the corpus. This
+ value is specific to this job and not shared
+ across other import jobs. Consult the Quotas
+ page on the project to set an appropriate value
+ here. If unspecified, a default value of 1,000
+ QPM would be used.
+ import_result_sink: Either a GCS path to store import results or a
+ BigQuery table to store import results. The format is
+ "gs://my-bucket/my/object.ndjson" for GCS or
+ "bq://my-project.my-dataset.my-table" for BigQuery. An existing GCS
+ object cannot be used. However, the BigQuery table may or may not
+ exist - if it does not exist, it will be created. If it does exist,
+ the schema will be checked and the import results will be appended
+ to the table.
+ parser: Document parser to use. Should be either None (default parser),
+ or a LayoutParserConfig (to parse documents using a Document AI
+ Layout Parser processor).
+ Returns:
+ operation_async.AsyncOperation.
+ """
+ if source is not None and paths is not None:
+ raise ValueError("Only one of source or paths must be passed in at a time")
+ if source is None and paths is None:
+ raise ValueError("One of source or paths must be passed in")
+ if layout_parser is not None and llm_parser is not None:
+ raise ValueError(
+ "Only one of layout_parser or llm_parser may be passed in at a time"
+ )
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ request = _gapic_utils.prepare_import_files_request(
+ corpus_name=corpus_name,
+ paths=paths,
+ source=source,
+ transformation_config=transformation_config,
+ max_embedding_requests_per_min=max_embedding_requests_per_min,
+ import_result_sink=import_result_sink,
+ layout_parser=layout_parser,
+ llm_parser=llm_parser,
+ )
+ async_client = _gapic_utils.create_rag_data_service_async_client()
+ try:
+ response = await async_client.import_rag_files(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in importing the RagFiles due to: ", e) from e
+ return response
+
+
+def get_file(name: str, corpus_name: Optional[str] = None) -> RagFile:
+ """
+ Get an existing RagFile.
+
+ Args:
+ name: Either a full RagFile resource name must be provided, or a RagCorpus
+ name and a RagFile name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}``
+ or ``{rag_file}``.
+ corpus_name: If `name` is not a full resource name, an existing RagCorpus
+ name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ Returns:
+ RagFile.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ name = _gapic_utils.get_file_name(name, corpus_name)
+ request = GetRagFileRequest(name=name)
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.get_rag_file(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in getting the RagFile due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_file(response)
+
+
+def list_files(
+ corpus_name: str, page_size: Optional[int] = None, page_token: Optional[str] = None
+) -> ListRagFilesPager:
+ """
+ List all RagFiles in an existing RagCorpus.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+ # List all corpora.
+ rag_corpora = list(rag.list_corpora())
+
+ # List all files of the first corpus.
+ rag_files = list(rag.list_files(corpus_name=rag_corpora[0].name))
+
+ # Alternatively, return a ListRagFilesPager.
+ pager_1 = rag.list_files(
+ corpus_name=rag_corpora[0].name,
+ page_size=10
+ )
+ # Then get the next page, use the generated next_page_token from the last pager.
+ pager_2 = rag.list_files(
+ corpus_name=rag_corpora[0].name,
+ page_size=10,
+ page_token=pager_1.next_page_token
+ )
+
+ ```
+
+ Args:
+ corpus_name: An existing RagCorpus name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ page_size: The standard list page size. Leaving out the page_size
+ causes all of the results to be returned.
+ page_token: The standard list page token.
+ Returns:
+ ListRagFilesPager.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ request = ListRagFilesRequest(
+ parent=corpus_name,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ pager = client.list_rag_files(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in listing the RagFiles due to: ", e) from e
+
+ return pager
+
+
+def delete_file(name: str, corpus_name: Optional[str] = None) -> None:
+ """
+ Delete RagFile from an existing RagCorpus.
+
+ Args:
+ name: Either a full RagFile resource name must be provided, or a RagCorpus
+ name and a RagFile name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}``
+ or ``{rag_file}``.
+ corpus_name: If `name` is not a full resource name, an existing RagCorpus
+ name must be provided. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
+ or ``{rag_corpus}``.
+ """
+ corpus_name = _gapic_utils.get_corpus_name(corpus_name)
+ name = _gapic_utils.get_file_name(name, corpus_name)
+ request = DeleteRagFileRequest(name=name)
+
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ client.delete_rag_file(request=request)
+ print("Successfully deleted the RagFile.")
+ except Exception as e:
+ raise RuntimeError("Failed in RagFile deletion due to: ", e) from e
+ return None
+
+
+def update_rag_engine_config(
+ rag_engine_config: RagEngineConfig,
+ timeout: int = 600,
+) -> RagEngineConfig:
+ """Update RagEngineConfig.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform import rag
+ agentplatform.init(project="my-project")
+ rag_engine_config = rag.RagEngineConfig(
+ rag_managed_db_config=rag.RagManagedDbConfig(
+ rag_managed_db=rag.RagManagedDb(
+ db_basic_tier=rag.Basic(),
+ ),
+ )
+ ),
+ )
+ rag.update_rag_engine_config(rag_engine_config=rag_engine_config)
+ ```
+
+ Args:
+ rag_engine_config: The RagEngineConfig to update.
+ timeout: Default is 600 seconds.
+
+ Raises:
+ RuntimeError: Failed in RagEngineConfig update due to exception.
+ """
+ gapic_rag_engine_config = _gapic_utils.convert_rag_engine_config_to_gapic(
+ rag_engine_config
+ )
+ request = UpdateRagEngineConfigRequest(
+ rag_engine_config=gapic_rag_engine_config,
+ )
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.update_rag_engine_config(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in RagEngineConfig update due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_engine_config(
+ response.result(timeout=timeout)
+ )
+
+
+def get_rag_engine_config(name: str) -> RagEngineConfig:
+ """Get an existing RagEngineConfig.
+
+ Example usage:
+ ```
+ import agentplatform
+ from agentplatform import rag
+ agentplatform.init(project="my-project")
+ rag_engine_config = rag.get_rag_engine_config(
+ name="projects/my-project/locations/us-central1/ragEngineConfig"
+ )
+ ```
+ Args:
+ name: The RagEngineConfig resource name pattern of the singleton resource.
+
+ Returns:
+ RagEngineConfig.
+ Raises:
+ RuntimeError: Failed in getting the RagEngineConfig.
+ """
+ request = GetRagEngineConfigRequest(name=name)
+ client = _gapic_utils.create_rag_data_service_client()
+ try:
+ response = client.get_rag_engine_config(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in getting the RagEngineConfig due to: ", e) from e
+ return _gapic_utils.convert_gapic_to_rag_engine_config(response)
+
+
+def add_inline_citations_and_references(
+ original_text_str, grounding_supports, grounding_chunks
+) -> RagCitedGenerationResponse:
+ """Adds inline citations to a text string based on grounding_supports and grounding_chunks.
+
+ Args:
+ original_text_str (str): The text (as a Unicode string) to which citations
+ will be added.
+ grounding_supports (list): A list of objects, where each object represents
+ a grounding support and has attributes: - segment: An object with
+ 'end_index' (byte offset relative to UTF-8). - grounding_chunk_indices:
+ A list of integers.
+ grounding_chunks (list): A list of objects, where each object is a source
+ chunk wrapper. To get URI: obj.retrieved_context.uri. To get page
+ span: obj.retrieved_context.rag_chunk.page_span.
+
+ Returns:
+ RagCitedGenerationResponse: An object containing the text with inline
+ citations and a formatted bibliography string.
+
+ Raises:
+ TypeError: If original_text_str is not a string, or if grounding_supports,
+ grounding_chunks, or internally generated reference dictionaries
+ are of an unexpected type (raised by this function or helpers).
+ ValueError: If original_text_str has encoding/decoding issues,
+ if segment data in grounding_supports is invalid,
+ if calculated insertion indices are out of bounds,
+ or if essential data within grounding_chunks (like the chunks
+ themselves, retrieved_context, or URI) is None when a value
+ is expected (raised by this function or helpers).
+ IndexError: If chunk indices used for citation or bibliography generation
+ are out of bounds for the provided grounding_chunks (raised by helpers).
+ AttributeError: If expected attributes (e.g., 'retrieved_context', 'uri')
+ are missing from the data structures within grounding_chunks
+ (raised by helpers).
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ rag_retrieval_tool = Tool.from_retrieval(
+ retrieval=rag.Retrieval(
+ source=rag.VertexRagStore(
+ rag_resources=[
+ rag.RagResource(
+ rag_corpus=corpus_name,
+ # Optional: supply IDs from `rag.list_files()`.
+ # rag_file_ids=["rag-file-1", "rag-file-2", ...],
+ )
+ ],
+ rag_retrieval_config=rag.RagRetrievalConfig(
+ top_k=10,
+ filter=rag.utils.resources.Filter(vector_distance_threshold=0.5),
+ ),
+ ),
+ )
+ )
+
+ rag_model = GenerativeModel(
+ model_name="gemini-2.5-pro-preview-05-06", tools=[rag_retrieval_tool]
+ )
+ response = rag_model.generate_content("Why is the sky blue?")
+
+ rag_cited_generation_response = rag.add_inline_citations_and_references(
+ original_text_str=response.candidates[0].content.parts[0].text,
+ grounding_supports=list(response.candidates[0].grounding_metadata.grounding_supports),
+ grounding_chunks=list(response.candidates[0].grounding_metadata.grounding_chunks),
+ )
+ print(rag_cited_generation_response.cited_text)
+ print(rag_cited_generation_response.final_bibliography)
+
+ """
+ if not isinstance(original_text_str, str):
+ raise TypeError("original_text_str must be a string.")
+ if not isinstance(grounding_supports, list):
+ raise TypeError("grounding_supports must be a list.")
+ if not isinstance(grounding_chunks, list):
+ raise TypeError("grounding_chunks must be a list.")
+
+ cited_chunk_references = {}
+
+ populate_cited_chunk_references(
+ grounding_supports, grounding_chunks, cited_chunk_references
+ )
+
+ # If there are no grounding supports, return original text and empty bibliography.
+ if not grounding_supports:
+ return _gapic_utils.convert_tuple_to_rag_cited_generation_response(
+ original_text_str, ""
+ )
+
+ try:
+ original_text_bytes_equivalent = original_text_str.encode("utf-8")
+ except UnicodeEncodeError as e:
+ raise ValueError(
+ "Could not encode original_text_str to UTF-8 for index"
+ f" conversion: {e}. Cannot process citations."
+ ) from e
+
+ insertions = []
+
+ for support_idx, support in enumerate(grounding_supports):
+ current_support_chunk_indices = []
+ if (
+ hasattr(support, "grounding_chunk_indices")
+ and support.grounding_chunk_indices is not None
+ ):
+ # Ensure indices are integers and unique for the citation string
+ valid_indices = [
+ idx for idx in support.grounding_chunk_indices if isinstance(idx, int)
+ ]
+ current_support_chunk_indices = sorted(list(set(valid_indices)))
+
+ # Validate segment and end_index
+ if not (
+ hasattr(support, "segment")
+ and support.segment
+ and hasattr(support.segment, "end_index")
+ and isinstance(support.segment.end_index, int)
+ and support.segment.end_index >= 0 # Ensure end_index is not negative
+ ):
+ raise ValueError(f"Invalid segment data for support at index {support_idx}")
+
+ byte_end_idx = support.segment.end_index
+
+ if byte_end_idx > len(original_text_bytes_equivalent):
+ byte_end_idx = len(original_text_bytes_equivalent)
+
+ char_end_idx = -1 # Initialize before try block
+ try:
+ # Slice the byte string up to the (potentially clamped) byte_end_idx
+ prefix_bytes = original_text_bytes_equivalent[:byte_end_idx]
+ # Decode this prefix to find the corresponding character length
+ char_end_idx = len(prefix_bytes.decode("utf-8"))
+ except UnicodeDecodeError as e:
+ # If decoding the prefix fails, we cannot reliably determine char_end_idx.
+ raise ValueError(
+ "Could not decode prefix of original_text_str (up to byte"
+ f" {byte_end_idx}) from UTF-8 for support at index {support_idx}:"
+ f" {e}. Cannot accurately place citation."
+ ) from e
+ except IndexError as e: # Should be less common with slice clamping
+ raise ValueError(
+ "Index error during byte-to-char conversion for support at index"
+ f" {support_idx}: {e}. This might indicate an issue with byte_end_idx"
+ " calculation."
+ ) from e
+
+ if char_end_idx > len(original_text_str):
+ char_end_idx = len(original_text_str)
+
+ citation_str = "".join([f"[{idx}]" for idx in current_support_chunk_indices])
+
+ if citation_str:
+ insertions.append(
+ {
+ "char_index": char_end_idx,
+ "citation": citation_str,
+ "original_byte_idx": byte_end_idx,
+ }
+ )
+
+ # Sort insertions by character index in reverse order to insert from end to start,
+ # preserving earlier indices.
+ insertions.sort(
+ key=lambda x: (x["char_index"], x["original_byte_idx"]), reverse=True
+ )
+
+ modified_text_list = list(original_text_str)
+ for insertion_info in insertions:
+ idx = insertion_info["char_index"]
+ citation = insertion_info["citation"]
+ if 0 <= idx <= len(modified_text_list):
+ modified_text_list.insert(idx, citation)
+ else:
+ raise ValueError(
+ f"Calculated insertion index {idx} is out of bounds for"
+ f" modified_text_list (length {len(modified_text_list)}). Citation:"
+ f" '{citation}'"
+ )
+
+ cited_text_output = "".join(modified_text_list)
+ references_output_string = format_bibliography(
+ cited_chunk_references, grounding_chunks
+ )
+ return _gapic_utils.convert_tuple_to_rag_cited_generation_response(
+ cited_text_output, references_output_string
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_inline_citations.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_inline_citations.py
new file mode 100644
index 0000000000000000000000000000000000000000..66bc92853178e98c5fe0a612490b0b430da4f016
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_inline_citations.py
@@ -0,0 +1,176 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Helper functions for processing and formatting citations from RAG generation outputs."""
+
+
+def populate_cited_chunk_references(
+ grounding_supports,
+ grounding_chunks,
+ cited_refs_dict,
+) -> None:
+ """Populates cited_refs_dict with URI information for all unique chunk indices found in grounding_supports.
+
+ Args:
+ grounding_supports: A list of support items, where each item might contain
+ grounding chunk indices.
+ grounding_chunks: A list of all available chunk items from which to retrieve
+ context and URI.
+ cited_refs_dict: A dictionary to populate with chunk_idx as key and URI
+ as value.
+
+ Raises:
+ TypeError: If grounding_chunks is not a list, or cited_refs_dict is not a
+ dictionary.
+ ValueError: If grounding_chunks or cited_refs_dict is None.
+ If a chunk_item at a valid index is None.
+ If 'retrieved_context' or 'uri' attribute of a chunk is None.
+ IndexError: If a chunk_idx is out of bounds for grounding_chunks.
+ AttributeError: If 'retrieved_context' or 'uri' attribute is missing from
+ a chunk or its context.
+ """
+ if grounding_chunks is None or not grounding_chunks:
+ raise ValueError("grounding_chunks cannot be None or empty.")
+ if grounding_supports is None or not grounding_supports:
+ raise ValueError("grounding_supports cannot be None or empty.")
+ if not isinstance(grounding_chunks, list):
+ raise TypeError("grounding_chunks must be a list.")
+ if not isinstance(grounding_supports, list):
+ raise TypeError("grounding_supports must be a list.")
+ if cited_refs_dict is None:
+ raise ValueError("cited_refs_dict cannot be None.")
+ if not isinstance(cited_refs_dict, dict):
+ raise TypeError("cited_refs_dict must be a dictionary.")
+
+ for support in grounding_supports:
+ current_support_chunk_indices = []
+ if (
+ hasattr(support, "grounding_chunk_indices")
+ and support.grounding_chunk_indices is not None
+ ):
+ valid_indices = [
+ idx for idx in support.grounding_chunk_indices if isinstance(idx, int)
+ ]
+ current_support_chunk_indices = sorted(list(set(valid_indices)))
+
+ for chunk_idx in current_support_chunk_indices:
+ if chunk_idx not in cited_refs_dict:
+ if not (0 <= chunk_idx < len(grounding_chunks)):
+ raise IndexError(
+ f"Chunk index {chunk_idx} is out of bounds for grounding_chunks of size {len(grounding_chunks)}."
+ )
+ chunk_item = grounding_chunks[chunk_idx]
+ if chunk_item is None:
+ raise ValueError(f"Chunk item at index {chunk_idx} is None.")
+ if not hasattr(chunk_item, "retrieved_context"):
+ raise AttributeError(
+ f"Chunk item at index {chunk_idx} is missing 'retrieved_context' attribute."
+ )
+ retrieved_context_obj = chunk_item.retrieved_context
+ if retrieved_context_obj is None:
+ raise ValueError(
+ f"Attribute 'retrieved_context' for chunk {chunk_idx} is None."
+ )
+ if not hasattr(retrieved_context_obj, "uri"):
+ raise AttributeError(
+ f"retrieved_context for chunk {chunk_idx} is missing 'uri' attribute."
+ )
+ uri = retrieved_context_obj.uri
+ if uri is None:
+ raise ValueError(f"Attribute 'uri' for chunk {chunk_idx} is None.")
+ cited_refs_dict[chunk_idx] = uri
+
+
+def format_bibliography(cited_refs_dict, grounding_chunks) -> str:
+ """Formats the bibliography string from the populated cited_refs_dict.
+
+ Omits page information if page numbers are not valid (e.g., not >= 1).
+
+ Args:
+ cited_refs_dict: A dictionary with chunk_idx as key and URI as value.
+ It's expected that populate_cited_chunk_references has successfully
+ populated this dict.
+ grounding_chunks: A list of all available chunk items, used to retrieve page
+ span information.
+
+ Returns:
+ A string representing the formatted bibliography, with each reference
+ on a new line.
+
+ Raises:
+ TypeError: If cited_refs_dict is not a dictionary or grounding_chunks is not a list.
+ ValueError: If cited_refs_dict or grounding_chunks is None.
+ If a chunk_item in grounding_chunks referenced by cited_refs_dict is None.
+ IndexError: If a chunk_idx from cited_refs_dict is out of bounds for
+ grounding_chunks.
+ """
+ if cited_refs_dict is None:
+ raise ValueError("cited_refs_dict cannot be None.")
+ if not isinstance(cited_refs_dict, dict):
+ raise TypeError("cited_refs_dict must be a dictionary.")
+ if grounding_chunks is None:
+ raise ValueError("grounding_chunks cannot be None.")
+ if not isinstance(grounding_chunks, list):
+ raise TypeError("grounding_chunks must be a list.")
+
+ reference_lines = []
+ for chunk_idx_ref in sorted(list(cited_refs_dict.keys())):
+ uri = cited_refs_dict[chunk_idx_ref]
+ page_info_str = ""
+ if not (
+ isinstance(chunk_idx_ref, int)
+ and 0 <= chunk_idx_ref < len(grounding_chunks)
+ ):
+ raise IndexError(
+ f"Chunk index {chunk_idx_ref} from cited_refs_dict is invalid or out of bounds "
+ f"for grounding_chunks of size {len(grounding_chunks)}."
+ )
+ chunk_item = grounding_chunks[chunk_idx_ref]
+ if chunk_item is None:
+ raise ValueError(
+ f"Chunk item at index {chunk_idx_ref} in grounding_chunks is None, "
+ "but was referenced in cited_refs_dict."
+ )
+ page_span_data = None
+ if (
+ hasattr(chunk_item, "retrieved_context")
+ and chunk_item.retrieved_context
+ and hasattr(chunk_item.retrieved_context, "rag_chunk")
+ and chunk_item.retrieved_context.rag_chunk
+ and hasattr(chunk_item.retrieved_context.rag_chunk, "page_span")
+ and chunk_item.retrieved_context.rag_chunk.page_span
+ ):
+ page_span_data = chunk_item.retrieved_context.rag_chunk.page_span
+ if (
+ page_span_data
+ and hasattr(page_span_data, "first_page")
+ and hasattr(page_span_data, "last_page")
+ ):
+ first_page_val = page_span_data.first_page
+ last_page_val = page_span_data.last_page
+ is_first_page_valid_num = (
+ isinstance(first_page_val, int) and first_page_val >= 1
+ )
+ is_last_page_valid_num = (
+ isinstance(last_page_val, int) and last_page_val >= 1
+ )
+ if is_first_page_valid_num and is_last_page_valid_num:
+ if last_page_val >= first_page_val:
+ page_info_str = (
+ f", p.{first_page_val}-{last_page_val}"
+ if first_page_val != last_page_val
+ else f", p.{first_page_val}"
+ )
+ reference_lines.append(f"[{chunk_idx_ref}] {uri}{page_info_str}")
+ return "\n".join(reference_lines)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_retrieval.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_retrieval.py
new file mode 100644
index 0000000000000000000000000000000000000000..70ead25de48f56abf1c8cebd25f917491b21d8c8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_retrieval.py
@@ -0,0 +1,505 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Retrieval query to get relevant contexts."""
+
+import re
+from typing import List, Optional
+
+from google.cloud import aiplatform_v1
+from google.cloud.aiplatform import initializer
+from agentplatform.rag.utils import _gapic_utils
+from agentplatform.rag.utils import resources
+
+from google.protobuf import any_pb2
+
+
+def retrieval_query(
+ text: str,
+ parent_override: Optional[str] = None,
+ api_path_override: Optional[str] = None,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+) -> aiplatform_v1.RetrieveContextsResponse:
+ """Retrieve top k relevant docs/chunks.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ config = agentplatform.rag.RagRetrievalConfig(
+ top_k=2,
+ filter=agentplatform.rag.Filter(
+ vector_distance_threshold=0.5
+ ),
+ ranking=agentplatform.rag.Ranking(
+ llm_ranker=rag.LlmRanker(
+ model_name="gemini-2.5-flash"
+ )
+ )
+ )
+
+ results = agentplatform.rag.retrieval_query(
+ text="Why is the sky blue?",
+ rag_resources=[agentplatform.rag.RagResource(
+ rag_corpus="projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1",
+ rag_file_ids=["rag-file-1", "rag-file-2", ...],
+ )],
+ rag_retrieval_config=config,
+ )
+ ```
+
+ Args:
+ text: The query in text format to get relevant contexts.
+ parent_override: Optional. The resource path of the parent.
+ api_path_override: Optional. The base API endpoint to use for the request.
+ rag_resources: A list of RagResource. It can be used to specify corpus
+ only or ragfiles. Currently only support one corpus or multiple files
+ from one corpus. In the future we may open up multiple corpora support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including similarity_top_k and vector_distance_threshold
+
+ Returns:
+ RetrieveContextsResonse.
+ """
+ parent = initializer.global_config.common_location_path()
+ if parent_override:
+ parent = parent_override
+
+ client = _gapic_utils.create_rag_service_client(api_path_override)
+
+ if rag_resources:
+ if len(rag_resources) > 1:
+ raise ValueError("Currently only support 1 RagResource.")
+ name = rag_resources[0].rag_corpus
+ else:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client(api_path_override)
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match("^{}$".format(_gapic_utils._VALID_RESOURCE_NAME_REGEX), name):
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should be:"
+ " projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}"
+ )
+
+ if rag_resources:
+ gapic_rag_resource = (
+ aiplatform_v1.RetrieveContextsRequest.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resources[0].rag_file_ids,
+ )
+ )
+ vertex_rag_store = aiplatform_v1.RetrieveContextsRequest.VertexRagStore(
+ rag_resources=[gapic_rag_resource],
+ )
+ else:
+ vertex_rag_store = aiplatform_v1.RetrieveContextsRequest.VertexRagStore(
+ rag_corpora=[rag_corpus_name],
+ )
+
+ # If rag_retrieval_config is not specified, set it to default values.
+ if not rag_retrieval_config:
+ api_retrieval_config = aiplatform_v1.RagRetrievalConfig()
+ else:
+ # If rag_retrieval_config is specified, check for missing parameters.
+ api_retrieval_config = aiplatform_v1.RagRetrievalConfig()
+ api_retrieval_config.top_k = rag_retrieval_config.top_k
+ # Set vector_distance_threshold to config value if specified
+ if rag_retrieval_config.filter:
+ # Check if both vector_distance_threshold and vector_similarity_threshold
+ # are specified.
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+ api_retrieval_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+ api_retrieval_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.llm_ranker
+ ):
+ raise ValueError("Only one of rank_service and llm_ranker can be set.")
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.rank_service:
+ api_retrieval_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ elif rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrieval_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+
+ query = aiplatform_v1.RagQuery(
+ text=text,
+ rag_retrieval_config=api_retrieval_config,
+ )
+ request = aiplatform_v1.RetrieveContextsRequest(
+ vertex_rag_store=vertex_rag_store,
+ parent=parent,
+ query=query,
+ )
+ try:
+ response = client.retrieve_contexts(request=request)
+ except Exception as e:
+ raise RuntimeError("Failed in retrieving contexts due to: ", e) from e
+
+ return response
+
+
+async def async_retrieve_contexts(
+ text: str,
+ parent_override: Optional[str] = None,
+ api_path_override: Optional[str] = None,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+ timeout: int = 600,
+) -> aiplatform_v1.RetrieveContextsResponse:
+ """Retrieve top k relevant docs/chunks asynchronously.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ config = agentplatform.rag.RagRetrievalConfig(
+ top_k=2,
+ )
+
+ results = await agentplatform.rag.async_retrieve_contexts(
+ text="Why is the sky blue?",
+ rag_resources=[agentplatform.rag.RagResource(
+ rag_corpus="projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1",
+ rag_file_ids=["rag-file-1", "rag-file-2", ...],
+ )],
+ rag_retrieval_config=config,
+ )
+ ```
+
+ Args:
+ text: Required. The query in text format to get relevant contexts.
+ parent_override: Optional. The parent resource name to use for the API
+ request. If not specified, the parent is determined from the global
+ configuration.
+ api_path_override: Optional. The API path override to use for the API
+ request. If not specified, the path is determined from the global
+ configuration.
+ rag_resources: Optional. A list of RagResource. It can be used to specify
+ corpus only or ragfiles. Currently only support one corpus or multiple
+ files from one corpus. In the future we may open up multiple corpora
+ support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including top_k.
+ timeout: Optional. The timeout in seconds for the request.
+
+ Returns:
+ RetrieveContextsResponse.
+ """
+ if parent_override:
+ parent = parent_override
+ else:
+ parent = initializer.global_config.common_location_path()
+
+ client = _gapic_utils.create_rag_service_async_client(
+ api_path_override=api_path_override
+ )
+
+ if not rag_resources:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client(
+ api_path_override=api_path_override
+ )
+
+ gapic_rag_resources = []
+ for rag_resource in rag_resources:
+ name = rag_resource.rag_corpus
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match("^{}$".format(_gapic_utils._VALID_RESOURCE_NAME_REGEX), name):
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should be:"
+ " projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}"
+ )
+ gapic_rag_resources.append(
+ aiplatform_v1.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resource.rag_file_ids,
+ )
+ )
+
+ vertex_rag_store = aiplatform_v1.VertexRagStore(
+ rag_resources=gapic_rag_resources,
+ )
+
+ # If rag_retrieval_config is not specified, set it to default values.
+ if not rag_retrieval_config:
+ api_retrieval_config = aiplatform_v1.RagRetrievalConfig()
+ else:
+ # If rag_retrieval_config is specified, check for missing parameters.
+ api_retrieval_config = aiplatform_v1.RagRetrievalConfig()
+ api_retrieval_config.top_k = rag_retrieval_config.top_k
+ # Set vector_distance_threshold to config value if specified
+ if rag_retrieval_config.filter:
+ # Check if both vector_distance_threshold and vector_similarity_threshold
+ # are specified.
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+ api_retrieval_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+ api_retrieval_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.llm_ranker
+ ):
+ raise ValueError("Only one of rank_service and llm_ranker can be set.")
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.rank_service:
+ api_retrieval_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ elif rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrieval_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+
+ query = aiplatform_v1.RagQuery(
+ text=text,
+ rag_retrieval_config=api_retrieval_config,
+ )
+
+ vertex_rag_store.rag_retrieval_config = api_retrieval_config
+
+ tool = aiplatform_v1.Tool(
+ retrieval=aiplatform_v1.Retrieval(
+ vertex_rag_store=vertex_rag_store,
+ )
+ )
+
+ request = aiplatform_v1.AsyncRetrieveContextsRequest(
+ parent=parent,
+ query=query,
+ tools=[tool],
+ )
+ try:
+ response_lro = await client.async_retrieve_contexts(
+ request=request, timeout=timeout
+ )
+ try:
+ response = await response_lro.result(timeout=timeout)
+ except Exception as e:
+ if response_lro.done():
+ raw_op = response_lro.operation
+ if raw_op.WhichOneof("result") == "response":
+ any_response = raw_op.response
+ inner_any = any_pb2.Any()
+ if any_response.Unpack(inner_any):
+ inner_any.type_url = (
+ "type.googleapis.com/google.cloud.aiplatform.v1.RagContexts"
+ )
+ rag_contexts = aiplatform_v1.RagContexts()
+ if inner_any.Unpack(rag_contexts._pb):
+ return aiplatform_v1.AsyncRetrieveContextsResponse(
+ contexts=rag_contexts
+ )
+ raise e
+ except Exception as e:
+ raise RuntimeError(
+ "Failed in retrieving contexts asynchronously due to: ", e
+ ) from e
+
+ return response
+
+
+def ask_contexts(
+ text: str,
+ parent_override: Optional[str] = None,
+ api_path_override: Optional[str] = None,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+ timeout: int = 600,
+) -> aiplatform_v1.AskContextsResponse:
+ """Ask questions on top k relevant docs/chunks.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ config = agentplatform.rag.RagRetrievalConfig(
+ top_k=2,
+ )
+
+ results = agentplatform.rag.ask_contexts(
+ text="Why is the sky blue?",
+ rag_resources=[agentplatform.rag.RagResource(
+ rag_corpus="projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1",
+ rag_file_ids=["rag-file-1", "rag-file-2", ...],
+ )],
+ rag_retrieval_config=config,
+ )
+ ```
+
+ Args:
+ text: Required. The query in text format to get relevant contexts.
+ parent_override: Optional. The parent resource name to use for the API
+ request. If not specified, the parent is determined from the global
+ configuration.
+ api_path_override: Optional. The API path override to use for the API
+ request. If not specified, the path is determined from the global
+ configuration.
+ rag_resources: Optional. A list of RagResource. It can be used to specify
+ corpus only or ragfiles. Currently only support one corpus or multiple
+ files from one corpus. In the future we may open up multiple corpora
+ support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including top_k.
+ timeout: Optional. The timeout in seconds for the request.
+
+ Returns:
+ AskContextsResponse.
+ """
+ if parent_override:
+ parent = parent_override
+ else:
+ parent = initializer.global_config.common_location_path()
+
+ client = _gapic_utils.create_rag_service_client(api_path_override=api_path_override)
+
+ if not rag_resources:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client(
+ api_path_override=api_path_override
+ )
+
+ gapic_rag_resources = []
+ for rag_resource in rag_resources:
+ name = rag_resource.rag_corpus
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match("^{}$".format(_gapic_utils._VALID_RESOURCE_NAME_REGEX), name):
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should be:"
+ " projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}"
+ )
+ gapic_rag_resources.append(
+ aiplatform_v1.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resource.rag_file_ids,
+ )
+ )
+
+ vertex_rag_store = aiplatform_v1.VertexRagStore(
+ rag_resources=gapic_rag_resources,
+ )
+
+ # If rag_retrieval_config is not specified, set it to default values.
+ if not rag_retrieval_config:
+ api_retrieval_config = aiplatform_v1.RagRetrievalConfig()
+ else:
+ # If rag_retrieval_config is specified, check for missing parameters.
+ api_retrieval_config = aiplatform_v1.RagRetrievalConfig()
+ api_retrieval_config.top_k = rag_retrieval_config.top_k
+ # Set vector_distance_threshold to config value if specified
+ if rag_retrieval_config.filter:
+ # Check if both vector_distance_threshold and vector_similarity_threshold
+ # are specified.
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+ api_retrieval_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+ api_retrieval_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.llm_ranker
+ ):
+ raise ValueError("Only one of rank_service and llm_ranker can be set.")
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.rank_service:
+ api_retrieval_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ elif rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrieval_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+
+ query = aiplatform_v1.RagQuery(
+ text=text,
+ rag_retrieval_config=api_retrieval_config,
+ )
+
+ vertex_rag_store.rag_retrieval_config = api_retrieval_config
+
+ tool = aiplatform_v1.Tool(
+ retrieval=aiplatform_v1.Retrieval(
+ vertex_rag_store=vertex_rag_store,
+ )
+ )
+
+ request = aiplatform_v1.AskContextsRequest(
+ parent=parent,
+ query=query,
+ tools=[tool],
+ )
+ try:
+ response = client.ask_contexts(request=request, timeout=timeout)
+ except Exception as e:
+ raise RuntimeError("Failed in asking contexts due to: ", e) from e
+
+ return response
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8f0b93f49439eae0c4a6e771f7162040a31868b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/rag_store.py
@@ -0,0 +1,165 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""RAG retrieval tool for content generation."""
+
+import re
+from typing import List, Optional, Union
+
+from google.cloud import aiplatform_v1beta1
+from agentplatform.rag.utils import _gapic_utils
+from agentplatform.rag.utils import resources
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform_v1beta1.types import tool as gapic_tool_types
+
+
+class Retrieval:
+ """Defines a retrieval tool that a model can call to access external knowledge."""
+
+ def __init__(
+ self,
+ source: Union["VertexRagStore"],
+ disable_attribution: Optional[bool] = False,
+ ):
+ self._raw_retrieval = gapic_tool_types.Retrieval(
+ vertex_rag_store=source._raw_vertex_rag_store,
+ disable_attribution=disable_attribution,
+ )
+
+
+class VertexRagStore:
+ """Retrieve from Vertex RAG Store."""
+
+ def __init__(
+ self,
+ rag_resources: Optional[List[resources.RagResource]] = None,
+ rag_retrieval_config: Optional[resources.RagRetrievalConfig] = None,
+ ):
+ """Initializes a Vertex RAG store tool.
+
+ Example usage:
+ ```
+ import agentplatform
+
+ agentplatform.init(project="my-project")
+
+ config = agentplatform.rag.RagRetrievalConfig(
+ top_k=2,
+ filter=agentplatform.rag.RagRetrievalConfig.Filter(
+ vector_distance_threshold=0.5
+ ),
+ ranking=vertex.rag.Ranking(
+ llm_ranker=agentplatform.rag.LlmRanker(
+ model_name="gemini-1.5-flash-002"
+ )
+ )
+ )
+
+ tool = Tool.from_retrieval(
+ retrieval=agentplatform.rag.Retrieval(
+ source=agentplatform.rag.VertexRagStore(
+ rag_corpora=["projects/my-project/locations/us-central1/ragCorpora/rag-corpus-1"],
+ rag_retrieval_config=config,
+ ),
+ )
+ )
+ ```
+
+ Args:
+ rag_resources: List of RagResource to retrieve from. It can be used
+ to specify corpus only or ragfiles. Currently only support one
+ corpus or multiple files from one corpus. In the future we
+ may open up multiple corpora support.
+ rag_retrieval_config: Optional. The config containing the retrieval
+ parameters, including similarity_top_k and vector_distance_threshold.
+ """
+
+ if rag_resources:
+ if len(rag_resources) > 1:
+ raise ValueError("Currently only support 1 RagResource.")
+ name = rag_resources[0].rag_corpus
+ else:
+ raise ValueError("rag_resources must be specified.")
+
+ data_client = _gapic_utils.create_rag_data_service_client()
+ if data_client.parse_rag_corpus_path(name):
+ rag_corpus_name = name
+ elif re.match("^{}$".format(_gapic_utils._VALID_RESOURCE_NAME_REGEX), name):
+ parent = initializer.global_config.common_location_path()
+ rag_corpus_name = parent + "/ragCorpora/" + name
+ else:
+ raise ValueError(
+ f"Invalid RagCorpus name: {name}. Proper format should be:"
+ " projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}"
+ )
+
+ # If rag_retrieval_config is not specified, set it to default values.
+ api_retrieval_config = aiplatform_v1beta1.RagRetrievalConfig()
+ # If rag_retrieval_config is specified, populate the default config.
+ if rag_retrieval_config:
+ api_retrieval_config.top_k = rag_retrieval_config.top_k
+ # Set vector_distance_threshold to config value if specified
+ if rag_retrieval_config.filter:
+ # Check if both vector_distance_threshold and
+ # vector_similarity_threshold are specified.
+ if (
+ rag_retrieval_config.filter
+ and rag_retrieval_config.filter.vector_distance_threshold
+ and rag_retrieval_config.filter.vector_similarity_threshold
+ ):
+ raise ValueError(
+ "Only one of vector_distance_threshold or"
+ " vector_similarity_threshold can be specified at a time"
+ " in rag_retrieval_config."
+ )
+ api_retrieval_config.filter.vector_distance_threshold = (
+ rag_retrieval_config.filter.vector_distance_threshold
+ )
+ api_retrieval_config.filter.vector_similarity_threshold = (
+ rag_retrieval_config.filter.vector_similarity_threshold
+ )
+ # Check if both rank_service and llm_ranker are specified.
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ and rag_retrieval_config.ranking.rank_service.model_name
+ and rag_retrieval_config.ranking.llm_ranker
+ and rag_retrieval_config.ranking.llm_ranker.model_name
+ ):
+ raise ValueError(
+ "Only one of rank_service or llm_ranker can be specified"
+ " at a time in rag_retrieval_config."
+ )
+ # Set rank_service to config value if specified
+ if (
+ rag_retrieval_config.ranking
+ and rag_retrieval_config.ranking.rank_service
+ ):
+ api_retrieval_config.ranking.rank_service.model_name = (
+ rag_retrieval_config.ranking.rank_service.model_name
+ )
+ # Set llm_ranker to config value if specified
+ if rag_retrieval_config.ranking and rag_retrieval_config.ranking.llm_ranker:
+ api_retrieval_config.ranking.llm_ranker.model_name = (
+ rag_retrieval_config.ranking.llm_ranker.model_name
+ )
+
+ gapic_rag_resource = gapic_tool_types.VertexRagStore.RagResource(
+ rag_corpus=rag_corpus_name,
+ rag_file_ids=rag_resources[0].rag_file_ids,
+ )
+ self._raw_vertex_rag_store = gapic_tool_types.VertexRagStore(
+ rag_resources=[gapic_rag_resource],
+ rag_retrieval_config=api_retrieval_config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/__pycache__/_gapic_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/__pycache__/_gapic_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..613a2f94cf3c29268abc0fa7837e442d375862a0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/__pycache__/_gapic_utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/__pycache__/resources.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/__pycache__/resources.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..813d26ab9f4f0efd25c9f70f038a25e5891fb0eb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/__pycache__/resources.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/_gapic_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/_gapic_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1077f475929c89cf20c78725c84315e7f7535021
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/_gapic_utils.py
@@ -0,0 +1,824 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import re
+from typing import Any, Dict, Optional, Sequence, Union
+from google.cloud.aiplatform import initializer
+from google.cloud.aiplatform.utils import (
+ VertexRagAsyncClientWithOverride,
+ VertexRagClientWithOverride,
+ VertexRagDataAsyncClientWithOverride,
+ VertexRagDataClientWithOverride,
+)
+from google.cloud.aiplatform_v1 import (
+ GoogleDriveSource,
+ ImportRagFilesConfig,
+ ImportRagFilesRequest,
+ JiraSource as GapicJiraSource,
+ RagCorpus as GapicRagCorpus,
+ RagEmbeddingModelConfig as GapicRagEmbeddingModelConfig,
+ RagEngineConfig as GapicRagEngineConfig,
+ RagFileChunkingConfig,
+ RagFileParsingConfig,
+ RagFileTransformationConfig,
+ RagFile as GapicRagFile,
+ RagManagedDbConfig as GapicRagManagedDbConfig,
+ RagVectorDbConfig as GapicRagVectorDbConfig,
+ SharePointSources as GapicSharePointSources,
+ SlackSource as GapicSlackSource,
+ VertexAiSearchConfig as GapicVertexAiSearchConfig,
+)
+from google.cloud.aiplatform_v1.types import api_auth
+from google.cloud.aiplatform_v1.types import EncryptionSpec
+from agentplatform.rag.utils.resources import (
+ Basic,
+ JiraSource,
+ LayoutParserConfig,
+ LlmParserConfig,
+ Pinecone,
+ RagCitedGenerationResponse,
+ RagCorpus,
+ RagEmbeddingModelConfig,
+ RagEngineConfig,
+ RagFile,
+ RagManagedDb,
+ RagManagedDbConfig,
+ RagVectorDbConfig,
+ Scaled,
+ SharePointSources,
+ SlackChannelsSource,
+ TransformationConfig,
+ Unprovisioned,
+ VertexAiSearchConfig,
+ VertexPredictionEndpoint,
+ VertexVectorSearch,
+)
+
+
+_VALID_RESOURCE_NAME_REGEX = "[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}"
+_VALID_DOCUMENT_AI_PROCESSOR_NAME_REGEX = (
+ r"projects/[^/]+/locations/[^/]+/processors/[^/]+(?:/processorVersions/[^/]+)?"
+)
+
+
+def create_rag_data_service_client(
+ api_path_override: Optional[str] = None,
+):
+ return initializer.global_config.create_client(
+ client_class=VertexRagDataClientWithOverride,
+ api_path_override=api_path_override,
+ ).select_version("v1")
+
+
+def create_rag_data_service_async_client(
+ api_path_override: Optional[str] = None,
+):
+ return initializer.global_config.create_client(
+ client_class=VertexRagDataAsyncClientWithOverride,
+ api_path_override=api_path_override,
+ ).select_version("v1")
+
+
+def create_rag_service_client(
+ api_path_override: Optional[str] = None,
+):
+ return initializer.global_config.create_client(
+ client_class=VertexRagClientWithOverride,
+ api_path_override=api_path_override,
+ ).select_version("v1")
+
+
+def create_rag_service_async_client(
+ api_path_override: Optional[str] = None,
+):
+ return initializer.global_config.create_client(
+ client_class=VertexRagAsyncClientWithOverride,
+ api_path_override=api_path_override,
+ ).select_version("v1")
+
+
+def convert_gapic_to_rag_embedding_model_config(
+ gapic_embedding_model_config: GapicRagEmbeddingModelConfig,
+) -> RagEmbeddingModelConfig:
+ """Convert GapicRagEmbeddingModelConfig to RagEmbeddingModelConfig."""
+ embedding_model_config = RagEmbeddingModelConfig()
+ path = gapic_embedding_model_config.vertex_prediction_endpoint.endpoint
+ publisher_model = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/publishers/google/models/(?P.+?)$",
+ path,
+ )
+ endpoint = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/endpoints/(?P.+?)$",
+ path,
+ )
+ if publisher_model:
+ embedding_model_config.vertex_prediction_endpoint = VertexPredictionEndpoint(
+ publisher_model=path
+ )
+ if endpoint:
+ embedding_model_config.vertex_prediction_endpoint = VertexPredictionEndpoint(
+ endpoint=path,
+ model=gapic_embedding_model_config.vertex_prediction_endpoint.model,
+ model_version_id=gapic_embedding_model_config.vertex_prediction_endpoint.model_version_id,
+ )
+ return embedding_model_config
+
+
+def _check_weaviate(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("weaviate")
+ except AttributeError:
+ if "weaviate" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("weaviate")
+ return False
+
+
+def _check_rag_managed_db(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("rag_managed_db")
+ except AttributeError:
+ if "rag_managed_db" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("rag_managed_db")
+ return False
+
+
+def _check_vertex_feature_store(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("vertex_feature_store")
+ except AttributeError:
+ if "vertex_feature_store" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("vertex_feature_store")
+ return False
+
+
+def _check_pinecone(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("pinecone")
+ except AttributeError:
+ if "pinecone" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("pinecone")
+ return False
+
+
+def _check_vertex_vector_search(gapic_vector_db: GapicRagVectorDbConfig) -> bool:
+ try:
+ return gapic_vector_db.__contains__("vertex_vector_search")
+ except AttributeError:
+ if "vertex_vector_search" in gapic_vector_db._pb.DESCRIPTOR.fields_by_name:
+ return gapic_vector_db._pb.HasField("vertex_vector_search")
+ return False
+
+
+def _check_rag_embedding_model_config(
+ gapic_vector_db: GapicRagVectorDbConfig,
+) -> bool:
+ try:
+ return gapic_vector_db.__contains__("rag_embedding_model_config")
+ except AttributeError:
+ if (
+ "rag_embedding_model_config"
+ in gapic_vector_db._pb.DESCRIPTOR.fields_by_name
+ ):
+ return gapic_vector_db._pb.HasField("rag_embedding_model_config")
+ return False
+
+
+def convert_gapic_to_backend_config(
+ gapic_vector_db: GapicRagVectorDbConfig,
+) -> RagVectorDbConfig:
+ """Convert Gapic RagVectorDbConfig to VertexVectorSearch, Pinecone, or RagManagedDb."""
+ if not gapic_vector_db:
+ return None
+ vector_config = RagVectorDbConfig()
+ if _check_pinecone(gapic_vector_db):
+ vector_config.vector_db = Pinecone(
+ index_name=gapic_vector_db.pinecone.index_name,
+ api_key=gapic_vector_db.api_auth.api_key_config.api_key_secret_version,
+ )
+ elif _check_vertex_vector_search(gapic_vector_db):
+ vector_config.vector_db = VertexVectorSearch(
+ index_endpoint=gapic_vector_db.vertex_vector_search.index_endpoint,
+ index=gapic_vector_db.vertex_vector_search.index,
+ )
+ elif _check_rag_managed_db(gapic_vector_db):
+ vector_config.vector_db = RagManagedDb()
+ if _check_rag_embedding_model_config(gapic_vector_db):
+ vector_config.rag_embedding_model_config = (
+ convert_gapic_to_rag_embedding_model_config(
+ gapic_vector_db.rag_embedding_model_config
+ )
+ )
+ return vector_config
+
+
+def convert_gapic_to_vertex_ai_search_config(
+ gapic_vertex_ai_search_config: GapicVertexAiSearchConfig,
+) -> Optional[VertexAiSearchConfig]:
+ """Convert Gapic VertexAiSearchConfig to VertexAiSearchConfig."""
+ print(f"DEBUG: gapic_vertex_ai_search_config={gapic_vertex_ai_search_config!r}")
+ print(f"DEBUG: serving_config={gapic_vertex_ai_search_config.serving_config!r}")
+ if gapic_vertex_ai_search_config.serving_config:
+ return VertexAiSearchConfig(
+ serving_config=gapic_vertex_ai_search_config.serving_config,
+ )
+ return None
+
+
+def convert_gapic_to_rag_corpus(gapic_rag_corpus: GapicRagCorpus) -> RagCorpus:
+ """Convert GapicRagCorpus to RagCorpus."""
+ rag_corpus = RagCorpus(
+ name=gapic_rag_corpus.name,
+ display_name=gapic_rag_corpus.display_name,
+ description=gapic_rag_corpus.description,
+ vertex_ai_search_config=convert_gapic_to_vertex_ai_search_config(
+ gapic_rag_corpus.vertex_ai_search_config
+ ),
+ backend_config=convert_gapic_to_backend_config(
+ gapic_rag_corpus.vector_db_config
+ ),
+ encryption_spec=gapic_rag_corpus.encryption_spec,
+ )
+ return rag_corpus
+
+
+def convert_gapic_to_rag_corpus_no_embedding_model_config(
+ gapic_rag_corpus: GapicRagCorpus,
+) -> RagCorpus:
+ """Convert GapicRagCorpus without embedding model config (for UpdateRagCorpus) to RagCorpus."""
+ vertex_ai_search_config = convert_gapic_to_vertex_ai_search_config(
+ gapic_rag_corpus.vertex_ai_search_config
+ )
+ old_config = gapic_rag_corpus.vector_db_config
+ rag_vector_db_config_no_embedding_model_config = old_config.__class__()
+ if _check_rag_managed_db(old_config):
+ rag_vector_db_config_no_embedding_model_config.rag_managed_db = (
+ old_config.rag_managed_db
+ )
+ elif _check_pinecone(old_config):
+ rag_vector_db_config_no_embedding_model_config.pinecone = old_config.pinecone
+ elif _check_vertex_vector_search(old_config):
+ rag_vector_db_config_no_embedding_model_config.vertex_vector_search = (
+ old_config.vertex_vector_search
+ )
+ elif _check_weaviate(old_config):
+ rag_vector_db_config_no_embedding_model_config.weaviate = old_config.weaviate
+ elif _check_vertex_feature_store(old_config):
+ rag_vector_db_config_no_embedding_model_config.vertex_feature_store = (
+ old_config.vertex_feature_store
+ )
+ try:
+ if old_config.__contains__("api_auth"):
+ rag_vector_db_config_no_embedding_model_config.api_auth = (
+ old_config.api_auth
+ )
+ except AttributeError:
+ pass
+ rag_corpus = RagCorpus(
+ name=gapic_rag_corpus.name,
+ display_name=gapic_rag_corpus.display_name,
+ description=gapic_rag_corpus.description,
+ vertex_ai_search_config=vertex_ai_search_config,
+ backend_config=convert_gapic_to_backend_config(
+ rag_vector_db_config_no_embedding_model_config
+ ),
+ encryption_spec=gapic_rag_corpus.encryption_spec,
+ )
+ return rag_corpus
+
+
+def convert_gapic_to_rag_file(gapic_rag_file: GapicRagFile) -> RagFile:
+ """Convert GapicRagFile to RagFile."""
+ rag_file = RagFile(
+ name=gapic_rag_file.name,
+ display_name=gapic_rag_file.display_name,
+ description=gapic_rag_file.description,
+ )
+ return rag_file
+
+
+def convert_json_to_rag_file(upload_rag_file_response: Dict[str, Any]) -> RagFile:
+ """Converts a JSON response to a RagFile."""
+ rag_file = RagFile(
+ name=upload_rag_file_response.get("ragFile").get("name"),
+ display_name=upload_rag_file_response.get("ragFile").get("displayName"),
+ description=upload_rag_file_response.get("ragFile").get("description"),
+ )
+ return rag_file
+
+
+def convert_tuple_to_rag_cited_generation_response(
+ cited_text: str, final_bibliography: str
+) -> RagCitedGenerationResponse:
+ """Converts a tuple to a RagCitedGenerationResponse."""
+ rag_cited_generation_response = RagCitedGenerationResponse(
+ cited_text=cited_text,
+ final_bibliography=final_bibliography,
+ )
+ return rag_cited_generation_response
+
+
+def convert_path_to_resource_id(
+ path: str,
+) -> Union[str, GoogleDriveSource.ResourceId]:
+ """Converts a path to a Google Cloud storage uri or GoogleDriveSource.ResourceId."""
+ if path.startswith("gs://"):
+ # Google Cloud Storage source
+ return path
+ elif path.startswith("https://drive.google.com/"):
+ # Google Drive source
+ path_list = path.split("/")
+ if "file" in path_list:
+ index = path_list.index("file") + 2
+ resource_id = path_list[index].split("?")[0]
+ resource_type = GoogleDriveSource.ResourceId.ResourceType.RESOURCE_TYPE_FILE
+ elif "folders" in path_list:
+ index = path_list.index("folders") + 1
+ resource_id = path_list[index].split("?")[0]
+ resource_type = (
+ GoogleDriveSource.ResourceId.ResourceType.RESOURCE_TYPE_FOLDER
+ )
+ else:
+ raise ValueError("path %s is not a valid Google Drive url.", path)
+
+ return GoogleDriveSource.ResourceId(
+ resource_id=resource_id,
+ resource_type=resource_type,
+ )
+ else:
+ raise ValueError(
+ "path must be a Google Cloud Storage uri or a Google Drive url."
+ )
+
+
+def convert_source_for_rag_import(
+ source: Union[SlackChannelsSource, JiraSource, SharePointSources],
+) -> Union[GapicSlackSource, GapicJiraSource]:
+ """Converts a SlackChannelsSource or JiraSource to a GapicSlackSource or GapicJiraSource."""
+ if isinstance(source, SlackChannelsSource):
+ result_source_channels = []
+ for channel in source.channels:
+ api_key = channel.api_key
+ cid = channel.channel_id
+ start_time = channel.start_time
+ end_time = channel.end_time
+ result_channels = GapicSlackSource.SlackChannels(
+ channels=[
+ GapicSlackSource.SlackChannels.SlackChannel(
+ channel_id=cid,
+ start_time=start_time,
+ end_time=end_time,
+ )
+ ],
+ api_key_config=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=api_key
+ ),
+ )
+ result_source_channels.append(result_channels)
+ return GapicSlackSource(
+ channels=result_source_channels,
+ )
+ elif isinstance(source, JiraSource):
+ result_source_queries = []
+ for query in source.queries:
+ api_key = query.api_key
+ custom_queries = query.custom_queries
+ projects = query.jira_projects
+ email = query.email
+ server_uri = query.server_uri
+ result_query = GapicJiraSource.JiraQueries(
+ custom_queries=custom_queries,
+ projects=projects,
+ email=email,
+ server_uri=server_uri,
+ api_key_config=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=api_key
+ ),
+ )
+ result_source_queries.append(result_query)
+ return GapicJiraSource(
+ jira_queries=result_source_queries,
+ )
+ elif isinstance(source, SharePointSources):
+ result_source_share_point_sources = []
+ for share_point_source in source.share_point_sources:
+ sharepoint_folder_path = share_point_source.sharepoint_folder_path
+ sharepoint_folder_id = share_point_source.sharepoint_folder_id
+ drive_name = share_point_source.drive_name
+ drive_id = share_point_source.drive_id
+ client_id = share_point_source.client_id
+ client_secret = share_point_source.client_secret
+ tenant_id = share_point_source.tenant_id
+ sharepoint_site_name = share_point_source.sharepoint_site_name
+ result_share_point_source = GapicSharePointSources.SharePointSource(
+ client_id=client_id,
+ client_secret=api_auth.ApiAuth.ApiKeyConfig(
+ api_key_secret_version=client_secret
+ ),
+ tenant_id=tenant_id,
+ sharepoint_site_name=sharepoint_site_name,
+ )
+ if sharepoint_folder_path is not None and sharepoint_folder_id is not None:
+ raise ValueError(
+ "sharepoint_folder_path and sharepoint_folder_id cannot both be set."
+ )
+ elif sharepoint_folder_path is not None:
+ result_share_point_source.sharepoint_folder_path = (
+ sharepoint_folder_path
+ )
+ elif sharepoint_folder_id is not None:
+ result_share_point_source.sharepoint_folder_id = sharepoint_folder_id
+ if drive_name is not None and drive_id is not None:
+ raise ValueError("drive_name and drive_id cannot both be set.")
+ elif drive_name is not None:
+ result_share_point_source.drive_name = drive_name
+ elif drive_id is not None:
+ result_share_point_source.drive_id = drive_id
+ else:
+ raise ValueError("Either drive_name and drive_id must be set.")
+ result_source_share_point_sources.append(result_share_point_source)
+ return GapicSharePointSources(
+ share_point_sources=result_source_share_point_sources,
+ )
+ else:
+ raise TypeError(
+ "source must be a SlackChannelsSource or JiraSource or SharePointSources."
+ )
+
+
+def prepare_import_files_request(
+ corpus_name: str,
+ paths: Optional[Sequence[str]] = None,
+ source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
+ transformation_config: Optional[TransformationConfig] = None,
+ max_embedding_requests_per_min: int = 1000,
+ import_result_sink: Optional[str] = None,
+ partial_failures_sink: Optional[str] = None,
+ layout_parser: Optional[LayoutParserConfig] = None,
+ llm_parser: Optional[LlmParserConfig] = None,
+) -> ImportRagFilesRequest:
+ if len(corpus_name.split("/")) != 6:
+ raise ValueError(
+ "corpus_name must be of the format `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`"
+ )
+
+ rag_file_parsing_config = RagFileParsingConfig()
+ if layout_parser is not None:
+ if (
+ re.fullmatch(
+ _VALID_DOCUMENT_AI_PROCESSOR_NAME_REGEX,
+ layout_parser.processor_name,
+ )
+ is None
+ ):
+ raise ValueError(
+ "processor_name must be of the format"
+ " `projects/{project_id}/locations/{location}/processors/{processor_id}`or"
+ " `projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}`,"
+ f" got {layout_parser.processor_name!r}"
+ )
+ rag_file_parsing_config.layout_parser = RagFileParsingConfig.LayoutParser(
+ processor_name=layout_parser.processor_name,
+ max_parsing_requests_per_min=layout_parser.max_parsing_requests_per_min,
+ )
+ if llm_parser is not None:
+ rag_file_parsing_config.llm_parser = RagFileParsingConfig.LlmParser(
+ model_name=llm_parser.model_name
+ )
+ if llm_parser.max_parsing_requests_per_min is not None:
+ rag_file_parsing_config.llm_parser.max_parsing_requests_per_min = (
+ llm_parser.max_parsing_requests_per_min
+ )
+ if llm_parser.custom_parsing_prompt is not None:
+ rag_file_parsing_config.llm_parser.custom_parsing_prompt = (
+ llm_parser.custom_parsing_prompt
+ )
+
+ chunk_size = 1024
+ chunk_overlap = 200
+ if transformation_config and transformation_config.chunking_config:
+ chunk_size = transformation_config.chunking_config.chunk_size
+ chunk_overlap = transformation_config.chunking_config.chunk_overlap
+
+ rag_file_transformation_config = RagFileTransformationConfig(
+ rag_file_chunking_config=RagFileChunkingConfig(
+ fixed_length_chunking=RagFileChunkingConfig.FixedLengthChunking(
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ ),
+ ),
+ )
+
+ import_rag_files_config = ImportRagFilesConfig(
+ rag_file_transformation_config=rag_file_transformation_config,
+ rag_file_parsing_config=rag_file_parsing_config,
+ max_embedding_requests_per_min=max_embedding_requests_per_min,
+ )
+
+ import_result_sink = import_result_sink or partial_failures_sink
+
+ if import_result_sink is not None:
+ if import_result_sink.startswith("gs://"):
+ import_rag_files_config.partial_failure_gcs_sink.output_uri_prefix = (
+ import_result_sink
+ )
+ elif import_result_sink.startswith("bq://"):
+ import_rag_files_config.partial_failure_bigquery_sink.output_uri = (
+ import_result_sink
+ )
+ else:
+ raise ValueError(
+ "import_result_sink must be a GCS path or a BigQuery table."
+ )
+
+ if source is not None:
+ gapic_source = convert_source_for_rag_import(source)
+ if isinstance(gapic_source, GapicSlackSource):
+ import_rag_files_config.slack_source = gapic_source
+ if isinstance(gapic_source, GapicJiraSource):
+ import_rag_files_config.jira_source = gapic_source
+ if isinstance(gapic_source, GapicSharePointSources):
+ import_rag_files_config.share_point_sources = gapic_source
+ else:
+ uris = []
+ resource_ids = []
+ for p in paths:
+ output = convert_path_to_resource_id(p)
+ if isinstance(output, str):
+ uris.append(p)
+ else:
+ resource_ids.append(output)
+ if uris:
+ import_rag_files_config.gcs_source.uris = uris
+ if resource_ids:
+ google_drive_source = GoogleDriveSource(
+ resource_ids=resource_ids,
+ )
+ import_rag_files_config.google_drive_source = google_drive_source
+
+ request = ImportRagFilesRequest(
+ parent=corpus_name, import_rag_files_config=import_rag_files_config
+ )
+ return request
+
+
+def get_corpus_name(
+ name: str,
+) -> str:
+ if name:
+ client = create_rag_data_service_client()
+ if client.parse_rag_corpus_path(name):
+ return name
+ elif re.match("^{}$".format(_VALID_RESOURCE_NAME_REGEX), name):
+ return client.rag_corpus_path(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ rag_corpus=name,
+ )
+ else:
+ raise ValueError(
+ "name must be of the format `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` or `{rag_corpus}`"
+ )
+ return name
+
+
+def get_file_name(
+ name: str,
+ corpus_name: str,
+) -> str:
+ client = create_rag_data_service_client()
+ if client.parse_rag_file_path(name):
+ return name
+ elif re.match("^{}$".format(_VALID_RESOURCE_NAME_REGEX), name):
+ if not corpus_name:
+ raise ValueError(
+ "corpus_name must be provided if name is a `{rag_file}`, not a "
+ "full resource name (`projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}`). "
+ )
+ return client.rag_file_path(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ rag_corpus=get_corpus_name(corpus_name),
+ rag_file=name,
+ )
+ else:
+ raise ValueError(
+ "name must be of the format `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}` or `{rag_file}`"
+ )
+
+
+def set_embedding_model_config(
+ embedding_model_config: RagEmbeddingModelConfig,
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ if embedding_model_config.vertex_prediction_endpoint is None:
+ return
+ if (
+ embedding_model_config.vertex_prediction_endpoint.publisher_model
+ and embedding_model_config.vertex_prediction_endpoint.endpoint
+ ):
+ raise ValueError("publisher_model and endpoint cannot be set at the same time.")
+ if (
+ not embedding_model_config.vertex_prediction_endpoint.publisher_model
+ and not embedding_model_config.vertex_prediction_endpoint.endpoint
+ ):
+ raise ValueError("At least one of publisher_model and endpoint must be set.")
+ parent = initializer.global_config.common_location_path(project=None, location=None)
+
+ if embedding_model_config.vertex_prediction_endpoint.publisher_model:
+ publisher_model = (
+ embedding_model_config.vertex_prediction_endpoint.publisher_model
+ )
+ full_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/publishers/google/models/(?P.+?)$",
+ publisher_model,
+ )
+ resource_name = re.match(
+ r"^publishers/google/models/(?P.+?)$",
+ publisher_model,
+ )
+ if full_resource_name:
+ rag_corpus.vector_db_config.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ publisher_model
+ )
+ elif resource_name:
+ rag_corpus.vector_db_config.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ parent + "/" + publisher_model
+ )
+ else:
+ raise ValueError(
+ "publisher_model must be of the format `projects/{project}/locations/{location}/publishers/google/models/{model_id}` or `publishers/google/models/{model_id}`"
+ )
+
+ if embedding_model_config.vertex_prediction_endpoint.endpoint:
+ endpoint = embedding_model_config.vertex_prediction_endpoint.endpoint
+ full_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/endpoints/(?P.+?)$",
+ endpoint,
+ )
+ resource_name = re.match(
+ r"^endpoints/(?P.+?)$",
+ endpoint,
+ )
+ if full_resource_name:
+ rag_corpus.vector_db_config.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ endpoint
+ )
+ elif resource_name:
+ rag_corpus.vector_db_config.rag_embedding_model_config.vertex_prediction_endpoint.endpoint = (
+ parent + "/" + endpoint
+ )
+ else:
+ raise ValueError(
+ "endpoint must be of the format `projects/{project}/locations/{location}/endpoints/{endpoint}` or `endpoints/{endpoint}`"
+ )
+
+
+def set_backend_config(
+ backend_config: Optional[
+ Union[
+ RagVectorDbConfig,
+ None,
+ ]
+ ],
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ """Sets the vector db configuration for the rag corpus."""
+ if backend_config is None:
+ return
+
+ if backend_config.vector_db is not None:
+ vector_config = backend_config.vector_db
+ if isinstance(vector_config, RagManagedDb):
+ rag_corpus.vector_db_config.rag_managed_db.CopyFrom(
+ GapicRagVectorDbConfig.RagManagedDb()
+ )
+ elif isinstance(vector_config, VertexVectorSearch):
+ index_endpoint = vector_config.index_endpoint
+ index = vector_config.index
+
+ rag_corpus.vector_db_config.vertex_vector_search.index_endpoint = (
+ index_endpoint
+ )
+ rag_corpus.vector_db_config.vertex_vector_search.index = index
+ elif isinstance(vector_config, Pinecone):
+ index_name = vector_config.index_name
+ api_key = vector_config.api_key
+
+ rag_corpus.vector_db_config.pinecone.index_name = index_name
+ rag_corpus.vector_db_config.api_auth.api_key_config.api_key_secret_version = (
+ api_key
+ )
+ elif vector_config is not None:
+ raise TypeError(
+ "backend_config must be a VertexFeatureStore,"
+ "RagManagedDb, or Pinecone."
+ )
+ if backend_config.rag_embedding_model_config:
+ set_embedding_model_config(
+ backend_config.rag_embedding_model_config, rag_corpus
+ )
+
+
+def set_encryption_spec(
+ encryption_spec: EncryptionSpec,
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ """Sets the encryption spec for the rag corpus."""
+ # Raises value error if encryption_spec.kms_key_name is None or empty,
+ if encryption_spec.kms_key_name is None or not encryption_spec.kms_key_name:
+ raise ValueError("kms_key_name must be set if encryption_spec is set.")
+
+ # Raises value error if encryption_spec.kms_key_name is not a valid KMS key name.
+ if not re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$",
+ encryption_spec.kms_key_name,
+ ):
+ raise ValueError(
+ "kms_key_name must be of the format "
+ "`projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`"
+ )
+
+ rag_corpus.encryption_spec = encryption_spec
+
+
+def set_vertex_ai_search_config(
+ vertex_ai_search_config: VertexAiSearchConfig,
+ rag_corpus: GapicRagCorpus,
+) -> None:
+ if not vertex_ai_search_config.serving_config:
+ raise ValueError("serving_config must be set.")
+ engine_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)/servingConfigs/(?P.+?)$",
+ vertex_ai_search_config.serving_config,
+ )
+ data_store_resource_name = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$",
+ vertex_ai_search_config.serving_config,
+ )
+ if engine_resource_name or data_store_resource_name:
+ rag_corpus.vertex_ai_search_config = GapicVertexAiSearchConfig(
+ serving_config=vertex_ai_search_config.serving_config,
+ )
+ else:
+ raise ValueError(
+ "serving_config must be of the format `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config}` or `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/servingConfigs/{serving_config}`"
+ )
+
+
+def convert_gapic_to_rag_engine_config(
+ response: GapicRagEngineConfig,
+) -> RagEngineConfig:
+ """Converts a GapicRagEngineConfig to a RagEngineConfig."""
+ rag_managed_db_config = RagManagedDbConfig()
+ # If future fields are added with similar names, beware that __contains__
+ # may match them.
+ if response.rag_managed_db_config.__contains__("basic"):
+ rag_managed_db_config.tier = Basic()
+ elif response.rag_managed_db_config.__contains__("unprovisioned"):
+ rag_managed_db_config.tier = Unprovisioned()
+ elif response.rag_managed_db_config.__contains__("scaled"):
+ rag_managed_db_config.tier = Scaled()
+ else:
+ raise ValueError("At least one of rag_managed_db_config must be set.")
+ return RagEngineConfig(
+ name=response.name,
+ rag_managed_db_config=rag_managed_db_config,
+ )
+
+
+def convert_rag_engine_config_to_gapic(
+ rag_engine_config: RagEngineConfig,
+) -> GapicRagEngineConfig:
+ """Converts a RagEngineConfig to a GapicRagEngineConfig."""
+ rag_managed_db_config = GapicRagManagedDbConfig()
+ if (
+ rag_engine_config.rag_managed_db_config is None
+ or rag_engine_config.rag_managed_db_config.tier is None
+ ):
+ rag_managed_db_config = GapicRagManagedDbConfig(
+ basic=GapicRagManagedDbConfig.Basic()
+ )
+ else:
+ if isinstance(rag_engine_config.rag_managed_db_config.tier, Basic):
+ rag_managed_db_config.basic = GapicRagManagedDbConfig.Basic()
+ elif isinstance(rag_engine_config.rag_managed_db_config.tier, Unprovisioned):
+ rag_managed_db_config.unprovisioned = (
+ GapicRagManagedDbConfig.Unprovisioned()
+ )
+ elif isinstance(rag_engine_config.rag_managed_db_config.tier, Scaled):
+ rag_managed_db_config.scaled = GapicRagManagedDbConfig.Scaled()
+ return GapicRagEngineConfig(
+ name=rag_engine_config.name,
+ rag_managed_db_config=rag_managed_db_config,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/resources.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/resources.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f50516280d4d83f916248f881821bc19b6337d3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/rag/utils/resources.py
@@ -0,0 +1,545 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import dataclasses
+from typing import List, Optional, Sequence, Union
+
+from google.protobuf import timestamp_pb2
+from google.cloud.aiplatform_v1.types import EncryptionSpec
+
+
+@dataclasses.dataclass
+class RagFile:
+ """RAG file (output only).
+
+ Attributes:
+ name: Generated resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file}``
+ display_name: Display name that was configured at client side.
+ description: The description of the RagFile.
+ """
+
+ name: Optional[str] = None
+ display_name: Optional[str] = None
+ description: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexPredictionEndpoint:
+ """VertexPredictionEndpoint.
+
+ Attributes:
+ publisher_model: 1P publisher model resource name. Format:
+ ``publishers/google/models/{model}`` or
+ ``projects/{project}/locations/{location}/publishers/google/models/{model}``
+ endpoint: 1P fine tuned embedding model resource name. Format:
+ ``endpoints/{endpoint}`` or
+ ``projects/{project}/locations/{location}/endpoints/{endpoint}``.
+ model:
+ Output only. The resource name of the model that is deployed
+ on the endpoint. Present only when the endpoint is not a
+ publisher model. Pattern:
+ ``projects/{project}/locations/{location}/models/{model}``
+ model_version_id:
+ Output only. Version ID of the model that is
+ deployed on the endpoint. Present only when the
+ endpoint is not a publisher model.
+ """
+
+ endpoint: Optional[str] = None
+ publisher_model: Optional[str] = None
+ model: Optional[str] = None
+ model_version_id: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RagEmbeddingModelConfig:
+ """RagEmbeddingModelConfig.
+
+ Attributes:
+ vertex_prediction_endpoint: The Vertex AI Prediction Endpoint config.
+ """
+
+ vertex_prediction_endpoint: Optional[VertexPredictionEndpoint] = None
+
+
+@dataclasses.dataclass
+class Weaviate:
+ """Weaviate.
+
+ Attributes:
+ weaviate_http_endpoint: The Weaviate DB instance HTTP endpoint
+ collection_name: The corresponding Weaviate collection this corpus maps to
+ api_key: The SecretManager resource name for the Weaviate DB API token. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ """
+
+ weaviate_http_endpoint: Optional[str] = None
+ collection_name: Optional[str] = None
+ api_key: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexFeatureStore:
+ """VertexFeatureStore.
+
+ Attributes:
+ resource_name: The resource name of the FeatureView. Format:
+ ``projects/{project}/locations/{location}/featureOnlineStores/
+ {feature_online_store}/featureViews/{feature_view}``
+ """
+
+ resource_name: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexVectorSearch:
+ """VertexVectorSearch.
+
+ Attributes:
+ index_endpoint (str):
+ The resource name of the Index Endpoint. Format:
+ ``projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}``
+ index (str):
+ The resource name of the Index. Format:
+ ``projects/{project}/locations/{location}/indexes/{index}``
+ """
+
+ index_endpoint: Optional[str] = None
+ index: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RagManagedDb:
+ """RagManagedDb."""
+
+
+@dataclasses.dataclass
+class Pinecone:
+ """Pinecone.
+
+ Attributes:
+ index_name: The Pinecone index name.
+ api_key: The SecretManager resource name for the Pinecone DB API token. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ """
+
+ index_name: Optional[str] = None
+ api_key: Optional[str] = None
+
+
+@dataclasses.dataclass
+class VertexAiSearchConfig:
+ """VertexAiSearchConfig.
+
+ Attributes:
+ serving_config: The resource name of the Vertex AI Search serving config.
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config}``
+ or
+ ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/servingConfigs/{serving_config}``
+ """
+
+ serving_config: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RagVectorDbConfig:
+ """RagVectorDbConfig.
+
+ Attributes:
+ vector_db: Can be one of the following: RagManagedDb, Pinecone,
+ VertexVectorSearch.
+ rag_embedding_model_config: The embedding model config of the Vector DB.
+ """
+
+ vector_db: Optional[
+ Union[
+ VertexVectorSearch,
+ Pinecone,
+ RagManagedDb,
+ ]
+ ] = None
+ rag_embedding_model_config: Optional[RagEmbeddingModelConfig] = None
+
+
+@dataclasses.dataclass
+class RagCorpus:
+ """RAG corpus(output only).
+
+ Attributes:
+ name: Generated resource name. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}``
+ display_name: Display name that was configured at client side.
+ description: The description of the RagCorpus.
+ vertex_ai_search_config: The Vertex AI Search config of the RagCorpus.
+ backend_config: The backend config of the RagCorpus. It can be a data
+ store and/or retrieval engine.
+ encryption_spec: The encryption spec of the RagCorpus. Immutable.
+ """
+
+ name: Optional[str] = None
+ display_name: Optional[str] = None
+ description: Optional[str] = None
+ vertex_ai_search_config: Optional[VertexAiSearchConfig] = None
+ backend_config: Optional[
+ Union[
+ RagVectorDbConfig,
+ None,
+ ]
+ ] = None
+ encryption_spec: Optional[EncryptionSpec] = None
+
+
+@dataclasses.dataclass
+class RagResource:
+ """RagResource.
+
+ The representation of the rag source. It can be used to specify corpus only
+ or ragfiles. Currently only support one corpus or multiple files from one
+ corpus. In the future we may open up multiple corpora support.
+
+ Attributes:
+ rag_corpus: A Rag corpus resource name or corpus id. Format:
+ ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}``
+ or ``{rag_corpus_id}``.
+ rag_files_id: List of Rag file resource name or file ids in the same corpus. Format:
+ ``{rag_file}``.
+ """
+
+ rag_corpus: Optional[str] = None
+ rag_file_ids: Optional[List[str]] = None
+
+
+@dataclasses.dataclass
+class SlackChannel:
+ """SlackChannel.
+
+ Attributes:
+ channel_id: The Slack channel ID.
+ api_key: The SecretManager resource name for the Slack API token. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ See: https://api.slack.com/tutorials/tracks/getting-a-token.
+ start_time: The starting timestamp for messages to import.
+ end_time: The ending timestamp for messages to import.
+ """
+
+ channel_id: str
+ api_key: str
+ start_time: Optional[timestamp_pb2.Timestamp] = None
+ end_time: Optional[timestamp_pb2.Timestamp] = None
+
+
+@dataclasses.dataclass
+class SlackChannelsSource:
+ """SlackChannelsSource.
+
+ Attributes:
+ channels: The Slack channels.
+ """
+
+ channels: Sequence[SlackChannel]
+
+
+@dataclasses.dataclass
+class JiraQuery:
+ """JiraQuery.
+
+ Attributes:
+ email: The Jira email address.
+ jira_projects: A list of Jira projects to import in their entirety.
+ custom_queries: A list of custom JQL Jira queries to import.
+ api_key: The SecretManager version resource name for Jira API access. Format:
+ ``projects/{project}/secrets/{secret}/versions/{version}``
+ See: https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/
+ server_uri: The Jira server URI. Format:
+ ``{server}.atlassian.net``
+ """
+
+ email: str
+ jira_projects: Sequence[str]
+ custom_queries: Sequence[str]
+ api_key: str
+ server_uri: str
+
+
+@dataclasses.dataclass
+class JiraSource:
+ """JiraSource.
+
+ Attributes:
+ queries: The Jira queries.
+ """
+
+ queries: Sequence[JiraQuery]
+
+
+@dataclasses.dataclass
+class SharePointSource:
+ """SharePointSource.
+
+ Attributes:
+ sharepoint_folder_path: The path of the SharePoint folder to download
+ from.
+ sharepoint_folder_id: The ID of the SharePoint folder to download
+ from.
+ drive_name: The name of the drive to download from.
+ drive_id: The ID of the drive to download from.
+ client_id: The Application ID for the app registered in
+ Microsoft Azure Portal. The application must
+ also be configured with MS Graph permissions
+ "Files.ReadAll", "Sites.ReadAll" and
+ BrowserSiteLists.Read.All.
+ client_secret: The application secret for the app registered
+ in Azure.
+ tenant_id: Unique identifier of the Azure Active
+ Directory Instance.
+ sharepoint_site_name: The name of the SharePoint site to download
+ from. This can be the site name or the site id.
+ """
+
+ sharepoint_folder_path: Optional[str] = None
+ sharepoint_folder_id: Optional[str] = None
+ drive_name: Optional[str] = None
+ drive_id: Optional[str] = None
+ client_id: str = None
+ client_secret: str = None
+ tenant_id: str = None
+ sharepoint_site_name: str = None
+
+
+@dataclasses.dataclass
+class SharePointSources:
+ """SharePointSources.
+
+ Attributes:
+ share_point_sources: The SharePoint sources.
+ """
+
+ share_point_sources: Sequence[SharePointSource]
+
+
+@dataclasses.dataclass
+class Filter:
+ """Filter.
+
+ Attributes:
+ vector_distance_threshold: Only returns contexts with vector
+ distance smaller than the threshold.
+ vector_similarity_threshold: Only returns contexts with vector
+ similarity larger than the threshold.
+ metadata_filter: String for metadata filtering.
+ """
+
+ vector_distance_threshold: Optional[float] = None
+ vector_similarity_threshold: Optional[float] = None
+ metadata_filter: Optional[str] = None
+
+
+@dataclasses.dataclass
+class LlmRanker:
+ """LlmRanker.
+
+ Attributes:
+ model_name: The model name used for ranking. Only Gemini models are
+ supported for now.
+ """
+
+ model_name: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RankService:
+ """RankService.
+
+ Attributes:
+ model_name: The model name of the rank service. Format:
+ ``semantic-ranker-512@latest``
+ """
+
+ model_name: Optional[str] = None
+
+
+@dataclasses.dataclass
+class Ranking:
+ """Ranking.
+
+ Attributes:
+ rank_service: Config for Rank Service.
+ llm_ranker: Config for LlmRanker.
+ """
+
+ rank_service: Optional[RankService] = None
+ llm_ranker: Optional[LlmRanker] = None
+
+
+@dataclasses.dataclass
+class RagRetrievalConfig:
+ """RagRetrievalConfig.
+
+ Attributes:
+ top_k: The number of contexts to retrieve.
+ filter: Config for filters.
+ ranking: Config for ranking.
+ """
+
+ top_k: Optional[int] = None
+ filter: Optional[Filter] = None
+ ranking: Optional[Ranking] = None
+
+
+@dataclasses.dataclass
+class ChunkingConfig:
+ """ChunkingConfig.
+
+ Attributes:
+ chunk_size: The size of each chunk.
+ chunk_overlap: The size of the overlap between chunks.
+ """
+
+ chunk_size: int
+ chunk_overlap: int
+
+
+@dataclasses.dataclass
+class TransformationConfig:
+ """TransformationConfig.
+
+ Attributes:
+ chunking_config: The chunking config.
+ """
+
+ chunking_config: Optional[ChunkingConfig] = None
+
+
+@dataclasses.dataclass
+class LayoutParserConfig:
+ """Configuration for the Document AI Layout Parser Processor.
+
+ Attributes:
+ processor_name: The full resource name of a Document AI processor or
+ processor version. The processor must have type
+ `LAYOUT_PARSER_PROCESSOR`.
+ Format must be one of the following:
+ - `projects/{project_id}/locations/{location}/processors/{processor_id}`
+ - `projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}`
+ max_parsing_requests_per_min: The maximum number of requests the job is
+ allowed to make to the Document AI processor per minute. Consult
+ https://cloud.google.com/document-ai/quotas and the Quota page for
+ your project to set an appropriate value here. If unspecified, a
+ default value of 120 QPM will be used.
+ """
+
+ processor_name: str
+ max_parsing_requests_per_min: Optional[int] = None
+
+
+@dataclasses.dataclass
+class LlmParserConfig:
+ """Configuration for the Document AI Layout Parser Processor.
+
+ Attributes:
+ model_name (str):
+ The full resource name of a Vertex AI model. Format:
+ - `projects/{project_id}/locations/{location}/publishers/google/models/{model_id}`
+ - `projects/{project_id}/locations/{location}/models/{model_id}`
+ max_parsing_requests_per_min (int):
+ The maximum number of requests the job is allowed to make to the
+ Vertex AI model per minute. Consult
+ https://cloud.google.com/vertex-ai/generative-ai/docs/quotas and
+ the Quota page for your project to set an appropriate value here.
+ If unspecified, a default value of 120 QPM will be used.
+ custom_parsing_prompt (str):
+ A custom prompt to use for parsing.
+ """
+
+ model_name: str
+ max_parsing_requests_per_min: Optional[int] = None
+ custom_parsing_prompt: Optional[str] = None
+
+
+@dataclasses.dataclass
+class RagCitedGenerationResponse:
+ """RagCitedGenerationResponse.
+
+ Attributes:
+ cited_text: The text with inline citations.
+ final_bibliography: List of all unique cited chunks, their URIs, and page
+ numbers (if applicable).
+ """
+
+ cited_text: str
+ final_bibliography: str
+
+
+@dataclasses.dataclass
+class Scaled:
+ """Scaled tier offers production grade performance along with
+
+ autoscaling functionality. It is suitable for customers with large
+ amounts of data or performance sensitive workloads.
+ """
+
+
+@dataclasses.dataclass
+class Basic:
+ """Basic tier is a cost-effective and low compute tier suitable for the following cases:
+
+ * Experimenting with RagManagedDb.
+ * Small data size.
+ * Latency insensitive workload.
+ * Only using RAG Engine with external vector DBs.
+
+ NOTE: This is the default tier if not explicitly chosen.
+ """
+
+
+@dataclasses.dataclass
+class Unprovisioned:
+ """Disables the RAG Engine service and deletes all your data held within
+ this service. This will halt the billing of the service.
+
+ NOTE: Once deleted the data cannot be recovered. To start using
+ RAG Engine again, you will need to update the tier by calling the
+ UpdateRagEngineConfig API.
+ """
+
+
+@dataclasses.dataclass
+class RagManagedDbConfig:
+ """RagManagedDbConfig.
+
+ The config of the RagManagedDb used by RagEngine.
+
+ Attributes:
+ tier: The tier of the RagManagedDb. The default tier is Basic.
+ """
+
+ tier: Optional[Union[Basic, Scaled, Unprovisioned]] = None
+
+
+@dataclasses.dataclass
+class RagEngineConfig:
+ """RagEngineConfig.
+
+ Attributes:
+ name: Generated resource name for singleton resource. Format:
+ ``projects/{project}/locations/{location}/ragEngineConfig``
+ rag_managed_db_config: The config of the RagManagedDb used by RagEngine.
+ The default tier is Basic.
+ """
+
+ name: str
+ rag_managed_db_config: Optional[RagManagedDbConfig] = None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..db65f5340345f23c88b403a4c748611ab3614df3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/__init__.py
@@ -0,0 +1,180 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""The agentplatform resources module."""
+
+from google.cloud.aiplatform import initializer
+
+from google.cloud.aiplatform.datasets import (
+ ImageDataset,
+ TabularDataset,
+ TextDataset,
+ TimeSeriesDataset,
+ VideoDataset,
+)
+from google.cloud.aiplatform import explain
+from google.cloud.aiplatform import gapic
+from google.cloud.aiplatform import hyperparameter_tuning
+from google.cloud.aiplatform.featurestore import (
+ EntityType,
+ Feature,
+ Featurestore,
+)
+from google.cloud.aiplatform.matching_engine import (
+ MatchingEngineIndex,
+ MatchingEngineIndexEndpoint,
+)
+from google.cloud.aiplatform import metadata
+from google.cloud.aiplatform.tensorboard import uploader_tracker
+from google.cloud.aiplatform.models import DeploymentResourcePool
+from google.cloud.aiplatform.models import Endpoint
+from google.cloud.aiplatform.models import PrivateEndpoint
+from google.cloud.aiplatform.models import Model
+from google.cloud.aiplatform.models import ModelRegistry
+from google.cloud.aiplatform.model_evaluation import ModelEvaluation
+from google.cloud.aiplatform.jobs import (
+ BatchPredictionJob,
+ CustomJob,
+ HyperparameterTuningJob,
+ ModelDeploymentMonitoringJob,
+)
+from google.cloud.aiplatform.pipeline_jobs import PipelineJob
+from google.cloud.aiplatform.pipeline_job_schedules import (
+ PipelineJobSchedule,
+)
+from google.cloud.aiplatform.tensorboard import (
+ Tensorboard,
+ TensorboardExperiment,
+ TensorboardRun,
+ TensorboardTimeSeries,
+)
+from google.cloud.aiplatform.training_jobs import (
+ CustomTrainingJob,
+ CustomContainerTrainingJob,
+ CustomPythonPackageTrainingJob,
+ AutoMLTabularTrainingJob,
+ AutoMLForecastingTrainingJob,
+ SequenceToSequencePlusForecastingTrainingJob,
+ TemporalFusionTransformerForecastingTrainingJob,
+ TimeSeriesDenseEncoderForecastingTrainingJob,
+ AutoMLImageTrainingJob,
+ AutoMLTextTrainingJob,
+ AutoMLVideoTrainingJob,
+)
+
+from google.cloud.aiplatform import helpers
+
+"""
+Usage:
+import agentplatform
+
+agentplatform.init(project='my_project')
+"""
+init = initializer.global_config.init
+
+get_pipeline_df = metadata.metadata._LegacyExperimentService.get_pipeline_df
+
+log_params = metadata.metadata._experiment_tracker.log_params
+log_metrics = metadata.metadata._experiment_tracker.log_metrics
+log_classification_metrics = (
+ metadata.metadata._experiment_tracker.log_classification_metrics
+)
+log_model = metadata.metadata._experiment_tracker.log_model
+get_experiment_df = metadata.metadata._experiment_tracker.get_experiment_df
+start_run = metadata.metadata._experiment_tracker.start_run
+autolog = metadata.metadata._experiment_tracker.autolog
+start_execution = metadata.metadata._experiment_tracker.start_execution
+log = metadata.metadata._experiment_tracker.log
+log_time_series_metrics = metadata.metadata._experiment_tracker.log_time_series_metrics
+end_run = metadata.metadata._experiment_tracker.end_run
+
+upload_tb_log = uploader_tracker._tensorboard_tracker.upload_tb_log
+start_upload_tb_log = uploader_tracker._tensorboard_tracker.start_upload_tb_log
+end_upload_tb_log = uploader_tracker._tensorboard_tracker.end_upload_tb_log
+
+save_model = metadata._models.save_model
+get_experiment_model = metadata.schema.google.artifact_schema.ExperimentModel.get
+
+Experiment = metadata.experiment_resources.Experiment
+ExperimentRun = metadata.experiment_run_resource.ExperimentRun
+Artifact = metadata.artifact.Artifact
+Execution = metadata.execution.Execution
+Context = metadata.context.Context
+
+
+__all__ = (
+ "end_run",
+ "explain",
+ "gapic",
+ "init",
+ "helpers",
+ "hyperparameter_tuning",
+ "log",
+ "log_params",
+ "log_metrics",
+ "log_classification_metrics",
+ "log_model",
+ "log_time_series_metrics",
+ "get_experiment_df",
+ "get_pipeline_df",
+ "start_run",
+ "start_execution",
+ "save_model",
+ "get_experiment_model",
+ "autolog",
+ "upload_tb_log",
+ "start_upload_tb_log",
+ "end_upload_tb_log",
+ "Artifact",
+ "AutoMLImageTrainingJob",
+ "AutoMLTabularTrainingJob",
+ "AutoMLForecastingTrainingJob",
+ "AutoMLTextTrainingJob",
+ "AutoMLVideoTrainingJob",
+ "BatchPredictionJob",
+ "CustomJob",
+ "CustomTrainingJob",
+ "CustomContainerTrainingJob",
+ "CustomPythonPackageTrainingJob",
+ "DeploymentResourcePool",
+ "Endpoint",
+ "EntityType",
+ "Execution",
+ "Experiment",
+ "ExperimentRun",
+ "Feature",
+ "Featurestore",
+ "MatchingEngineIndex",
+ "MatchingEngineIndexEndpoint",
+ "ImageDataset",
+ "HyperparameterTuningJob",
+ "Model",
+ "ModelRegistry",
+ "ModelEvaluation",
+ "ModelDeploymentMonitoringJob",
+ "PipelineJob",
+ "PipelineJobSchedule",
+ "PrivateEndpoint",
+ "SequenceToSequencePlusForecastingTrainingJob",
+ "TabularDataset",
+ "Tensorboard",
+ "TensorboardExperiment",
+ "TensorboardRun",
+ "TensorboardTimeSeries",
+ "TextDataset",
+ "TemporalFusionTransformerForecastingTrainingJob",
+ "TimeSeriesDataset",
+ "TimeSeriesDenseEncoderForecastingTrainingJob",
+ "VideoDataset",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dba6a3586d6606b95ba8b7aa624d9c8ede862c2f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..345592a4095e3a882f2008a2e2cf1714fd750081
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/__init__.py
@@ -0,0 +1,89 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""The agentplatform resources preview module."""
+
+from google.cloud.aiplatform.preview.jobs import (
+ CustomJob,
+ HyperparameterTuningJob,
+)
+from google.cloud.aiplatform.preview.models import (
+ Prediction,
+ DeploymentResourcePool,
+ Endpoint,
+ Model,
+)
+from google.cloud.aiplatform.preview.featurestore.entity_type import (
+ EntityType,
+)
+from google.cloud.aiplatform.preview.persistent_resource import (
+ PersistentResource,
+)
+from google.cloud.aiplatform.preview.pipelinejobschedule.pipeline_job_schedules import (
+ PipelineJobSchedule,
+)
+
+from agentplatform.resources.preview.feature_store import (
+ Feature,
+ FeatureGroup,
+ FeatureGroupBigQuerySource,
+ FeatureMonitor,
+ FeatureOnlineStore,
+ FeatureOnlineStoreType,
+ FeatureView,
+ FeatureViewBigQuerySource,
+ FeatureViewReadResponse,
+ FeatureViewRegistrySource,
+ FeatureViewVertexRagSource,
+ IndexConfig,
+ TreeAhConfig,
+ BruteForceConfig,
+ DistanceMeasureType,
+ AlgorithmConfig,
+)
+
+from agentplatform.resources.preview.ml_monitoring import (
+ ModelMonitor,
+ ModelMonitoringJob,
+)
+
+__all__ = (
+ "CustomJob",
+ "HyperparameterTuningJob",
+ "Prediction",
+ "DeploymentResourcePool",
+ "Endpoint",
+ "Model",
+ "PersistentResource",
+ "EntityType",
+ "PipelineJobSchedule",
+ "Feature",
+ "FeatureGroup",
+ "FeatureGroupBigQuerySource",
+ "FeatureMonitor",
+ "FeatureOnlineStoreType",
+ "FeatureOnlineStore",
+ "FeatureView",
+ "FeatureViewBigQuerySource",
+ "FeatureViewReadResponse",
+ "FeatureViewVertexRagSource",
+ "FeatureViewRegistrySource",
+ "IndexConfig",
+ "TreeAhConfig",
+ "BruteForceConfig",
+ "DistanceMeasureType",
+ "AlgorithmConfig",
+ "ModelMonitor",
+ "ModelMonitoringJob",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b86119a1f0f852bac0e64da9d261efcbaaadaf2a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a790eff4650c3b8d61a73e7490928ea0453c7d5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__init__.py
@@ -0,0 +1,68 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""The agentplatform resources preview module."""
+
+from agentplatform.resources.preview.feature_store.feature import (
+ Feature,
+)
+
+from agentplatform.resources.preview.feature_store.feature_group import (
+ FeatureGroup,
+)
+
+from agentplatform.resources.preview.feature_store.feature_monitor import (
+ FeatureMonitor,
+)
+
+from agentplatform.resources.preview.feature_store.feature_online_store import (
+ FeatureOnlineStore,
+ FeatureOnlineStoreType,
+)
+
+from agentplatform.resources.preview.feature_store.feature_view import (
+ FeatureView,
+)
+
+from agentplatform.resources.preview.feature_store.utils import (
+ FeatureGroupBigQuerySource,
+ FeatureViewBigQuerySource,
+ FeatureViewReadResponse,
+ FeatureViewVertexRagSource,
+ FeatureViewRegistrySource,
+ IndexConfig,
+ TreeAhConfig,
+ BruteForceConfig,
+ DistanceMeasureType,
+ AlgorithmConfig,
+)
+
+__all__ = (
+ "Feature",
+ "FeatureGroup",
+ "FeatureGroupBigQuerySource",
+ "FeatureMonitor",
+ "FeatureOnlineStoreType",
+ "FeatureOnlineStore",
+ "FeatureView",
+ "FeatureViewBigQuerySource",
+ "FeatureViewReadResponse",
+ "FeatureViewVertexRagSource",
+ "FeatureViewRegistrySource",
+ "IndexConfig",
+ "TreeAhConfig",
+ "BruteForceConfig",
+ "DistanceMeasureType",
+ "AlgorithmConfig",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a940dd36208c531f9aa4d17e70b3282e39664db0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/_offline_store_impl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/_offline_store_impl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..304acc3a6fdf033e9ffa70f9f51aeab8d7f42e68
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/_offline_store_impl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de759a8e2b9c18ba36e21040cb0941a1a15179ed
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_group.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_group.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d36c53f4907b6ba7d9890a1e0642f4db3720f8f6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_group.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_monitor.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_monitor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c276f6661dadbc5083dce43f6c421620c0d9f00
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_monitor.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_online_store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_online_store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76056699a8b900435ff160ebfffc2ac0913e8a73
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_online_store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_view.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_view.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..629d1899c907d5f9a321d7c244c3071efa0ef74d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/feature_view.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/offline_store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/offline_store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e34dbc3c0402f660ae508bc8a78a8b05ba8b050
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/offline_store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..559928565220a55d044eaae7a4c9cf3f447ce9a5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/_offline_store_impl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/_offline_store_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd824b05a0949032c55d81ebfe5a54af117383c1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/_offline_store_impl.py
@@ -0,0 +1,188 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import textwrap
+from dataclasses import dataclass
+from typing import Optional, List
+
+
+@dataclass
+class DataSource:
+ """An object to represent a data source - both entity DataFrame and any feature data.
+
+ Contains helpers for use with SQL templating.
+ """
+
+ def __init__(
+ self,
+ qualifying_name: str,
+ sql: str,
+ data_columns: List[str],
+ timestamp_column: str,
+ entity_id_columns: Optional[List[str]] = None,
+ ):
+ """Initialize DataSource object.
+
+ Args:
+ qualifying_name:
+ A unique name used to qualify the data in the PITL query.
+ sql:
+ SQL query representing the data_source.
+ data_columns:
+ Columns other than entity ID column(s) and timestamp column.
+ timestamp_column:
+ The column that holds feature timestamp data.
+ entity_id_columns:
+ The column(s) that holds entity IDs. Shouldn't be populated for
+ entity_df.
+ """
+ self.qualifying_name = qualifying_name
+ self._sql = sql
+ self.data_columns = data_columns
+ self.timestamp_column = timestamp_column
+ self.entity_id_columns = entity_id_columns
+
+ def copy_with_pitl_suffix(self) -> "DataSource":
+ import copy
+
+ data_source = copy.copy(self)
+ data_source.qualifying_name += "_pitl"
+ return data_source
+
+ @property
+ def sql(self):
+ return self._sql
+
+ @property
+ def comma_separated_qualified_data_columns(self):
+ return ", ".join(
+ [self.qualifying_name + "." + col for col in self.data_columns]
+ )
+
+ @property
+ def comma_separated_name_qualified_all_non_timestamp_columns(self):
+ """Same as `comma_separated_qualified_data_columns` but including entity ID column."""
+ all_columns = self.data_columns.copy()
+ if self.entity_id_columns:
+ all_columns += self.entity_id_columns
+ return ", ".join([self.qualifying_name + "." + col for col in all_columns])
+
+ @property
+ def qualified_timestamp_column(self) -> str:
+ """Returns name qualified timestamp column e.g. `name.feature_timestamp`."""
+ return f"{self.qualifying_name}.{self.timestamp_column}"
+
+
+def _generate_eid_check(entity_data: DataSource, feature: DataSource):
+ """Generate equality check for entity columns of feature against matching columns in entity_data."""
+ e_cols = set(entity_data.data_columns)
+ f_cols = feature.entity_id_columns
+ assert f_cols
+
+ equal_statements = []
+ for col in f_cols:
+ if col not in e_cols:
+ raise ValueError(
+ f"Feature entity ID column '{col}' should be a column in the entity DataFrame."
+ )
+ equal_statements.append(
+ f"{entity_data.qualifying_name}.{col} = {feature.qualifying_name}.{col}"
+ )
+
+ statement = " AND\n".join(equal_statements)
+
+ return statement
+
+
+# Args:
+# textwrap: Module
+# generate_eid_check: function (above)
+# entity_data: DataSource
+# feature_data: List[DataSource]
+_PITL_QUERY_TEMPLATE_RAW = """WITH
+ {{ entity_data.qualifying_name }}_without_row_num AS (
+{{ textwrap.indent(entity_data.sql, ' ' * 4) }}
+ ),
+ {{ entity_data.qualifying_name }} AS (
+ SELECT *, ROW_NUMBER() OVER() AS row_num,
+ FROM entity_df_without_row_num
+ ),
+
+ # Features
+ {% for feature_data_elem in feature_data %}
+ {{ feature_data_elem.qualifying_name }} AS (
+{{ textwrap.indent(feature_data_elem.sql, ' ' * 4) }}
+ ),
+ {% endfor %}
+
+ # Features with PITL
+ {% for feature_data_elem in feature_data %}
+ {{ feature_data_elem.qualifying_name }}_pitl AS (
+ SELECT
+ {{ entity_data.qualifying_name }}.row_num,
+ {{ feature_data_elem.comma_separated_qualified_data_columns }},
+ FROM {{ entity_data.qualifying_name }}
+ LEFT JOIN {{ feature_data_elem.qualifying_name }}
+ ON (
+{{ textwrap.indent(generate_eid_check(entity_data, feature_data_elem) + ' AND', ' ' * 6) }}
+ CAST({{ feature_data_elem.qualified_timestamp_column }} AS TIMESTAMP) <= CAST({{ entity_data.qualified_timestamp_column }} AS TIMESTAMP)
+ )
+ QUALIFY ROW_NUMBER() OVER (PARTITION BY {{ entity_data.qualifying_name }}.row_num ORDER BY {{ feature_data_elem.qualified_timestamp_column }} DESC) = 1
+ ){{ ',' if not loop.last else '' }}
+ {% endfor %}
+
+
+SELECT
+ {{ entity_data.comma_separated_name_qualified_all_non_timestamp_columns }},
+ {% for feature_data_elem in feature_data %}
+ {% set feature_pitl = feature_data_elem.copy_with_pitl_suffix() %}
+ {{ feature_pitl.comma_separated_qualified_data_columns }},
+ {% endfor %}
+ {{ entity_data.qualified_timestamp_column }}
+
+FROM {{ entity_data.qualifying_name }}
+{% for feature_data_elem in feature_data %}
+JOIN {{ feature_data_elem.qualifying_name }}_pitl USING (row_num)
+{% endfor %}
+"""
+
+
+def pitl_query_template():
+ try:
+ import jinja2
+ except ImportError as exc:
+ raise ImportError(
+ "`Jinja2` is not installed but required for this functionality."
+ ) from exc
+
+ return jinja2.Environment(
+ loader=jinja2.BaseLoader, lstrip_blocks=True, trim_blocks=True
+ ).from_string(_PITL_QUERY_TEMPLATE_RAW)
+
+
+def render_pitl_query(entity_data: DataSource, feature_data: List[DataSource]):
+ """Return the PITL query jinja template.
+
+ The args for the query are as follows:
+ textwrap: The python textwrap module.
+ entity_data[DataSource]: The entity data(frame) as SQL source.
+ feature_data[List[DataSource]]:
+ """
+ return pitl_query_template().render(
+ textwrap=textwrap,
+ generate_eid_check=_generate_eid_check,
+ entity_data=entity_data,
+ feature_data=feature_data,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d74c6d568417c1f4d93fec32c81eff961931359
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature.py
@@ -0,0 +1,149 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import re
+from typing import List, Optional
+from google.auth import credentials as auth_credentials
+from google.cloud.aiplatform import base
+from google.cloud.aiplatform import utils
+from google.cloud.aiplatform.compat.types import (
+ feature as gca_feature,
+ feature_monitor_v1beta1 as gca_feature_monitor,
+ feature_v1beta1 as gca_feature_v1beta1,
+ featurestore_service_v1beta1 as gca_featurestore_service_v1beta1,
+)
+
+
+class Feature(base.VertexAiResourceNounWithFutureManager):
+ """Class for managing Feature resources."""
+
+ client_class = utils.FeatureRegistryClientWithOverride
+
+ _resource_noun = "features"
+ _getter_method = "get_feature"
+ _list_method = "list_features"
+ _delete_method = "delete_feature"
+ _parse_resource_name_method = "parse_feature_path"
+ _format_resource_name_method = "feature_path"
+ _gca_resource: gca_feature.Feature
+
+ def __init__(
+ self,
+ name: str,
+ feature_group_id: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ latest_stats_count: Optional[int] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ """Retrieves an existing managed feature.
+
+ Args:
+ name:
+ The resource name
+ (`projects/.../locations/.../featureGroups/.../features/...`) or
+ ID.
+ feature_group_id:
+ The feature group ID. Must be passed in if name is an ID and not
+ a resource path.
+ project:
+ Project to retrieve feature from. If not set, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to retrieve feature from. If not set, the location set
+ in aiplatform.init will be used.
+ gca_feature_arg:
+ The GCA feature object.
+ Only set when calling from get_feature with latest_stats_count set.
+ credentials:
+ Custom credentials to use to retrieve this feature. Overrides
+ credentials set in aiplatform.init.
+ """
+
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=name,
+ )
+
+ if re.fullmatch(
+ r"projects/.+/locations/.+/featureGroups/.+/features/.+",
+ name,
+ ):
+ if feature_group_id:
+ raise ValueError(
+ f"Since feature '{name}' is provided as a path, feature_group_id should not be specified."
+ )
+ feature = name
+ else:
+ from .feature_group import FeatureGroup
+
+ # Construct the feature path using feature group ID if only the
+ # feature group ID is provided.
+ if not feature_group_id:
+ raise ValueError(
+ f"Since feature '{name}' is not provided as a path, please specify feature_group_id."
+ )
+
+ feature_group_path = utils.full_resource_name(
+ resource_name=feature_group_id,
+ resource_noun=FeatureGroup._resource_noun,
+ parse_resource_name_method=FeatureGroup._parse_resource_name,
+ format_resource_name_method=FeatureGroup._format_resource_name,
+ )
+
+ feature = f"{feature_group_path}/features/{name}"
+
+ if latest_stats_count is not None:
+ api_client = self.__class__._instantiate_client(
+ location=location, credentials=credentials
+ )
+
+ feature_obj: gca_feature_v1beta1.Feature = api_client.select_version(
+ "v1beta1"
+ ).get_feature(
+ request=gca_featurestore_service_v1beta1.GetFeatureRequest(
+ name=f"{feature}",
+ feature_stats_and_anomaly_spec=gca_feature_monitor.FeatureStatsAndAnomalySpec(
+ latest_stats_count=latest_stats_count
+ ),
+ )
+ )
+ self._gca_resource = feature_obj
+ else:
+ self._gca_resource = self._get_gca_resource(resource_name=feature)
+
+ @property
+ def version_column_name(self) -> str:
+ """The name of the BigQuery Table/View column hosting data for this version."""
+ return self._gca_resource.version_column_name
+
+ @property
+ def description(self) -> str:
+ """The description of the feature."""
+ return self._gca_resource.description
+
+ @property
+ def point_of_contact(self) -> str:
+ """The point of contact for the feature."""
+ return self._gca_resource.point_of_contact
+
+ @property
+ def feature_stats_and_anomalies(
+ self,
+ ) -> List[gca_feature_monitor.FeatureStatsAndAnomaly]:
+ """The number of latest stats to return. Only present when gca_feature is set."""
+ return self._gca_resource.feature_stats_and_anomaly
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_group.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_group.py
new file mode 100644
index 0000000000000000000000000000000000000000..d235c6fe742d0292ab9c7948a5466224c38f5bb9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_group.py
@@ -0,0 +1,590 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Dict, List, Optional, Sequence, Tuple
+from google.auth import credentials as auth_credentials
+from google.cloud.aiplatform import base, initializer
+from google.cloud.aiplatform import utils
+from google.cloud.aiplatform.compat.types import (
+ feature as gca_feature,
+ feature_group as gca_feature_group,
+ io as gca_io,
+ feature_monitor_v1beta1 as gca_feature_monitor,
+)
+from agentplatform.resources.preview.feature_store.utils import (
+ FeatureGroupBigQuerySource,
+)
+from agentplatform.resources.preview.feature_store import (
+ Feature,
+)
+from agentplatform.resources.preview.feature_store.feature_monitor import (
+ FeatureMonitor,
+)
+
+
+_LOGGER = base.Logger(__name__)
+
+
+class FeatureGroup(base.VertexAiResourceNounWithFutureManager):
+ """Class for managing Feature Group resources."""
+
+ client_class = utils.FeatureRegistryClientWithOverride
+
+ _resource_noun = "feature_groups"
+ _getter_method = "get_feature_group"
+ _list_method = "list_feature_groups"
+ _delete_method = "delete_feature_group"
+ _parse_resource_name_method = "parse_feature_group_path"
+ _format_resource_name_method = "feature_group_path"
+ _gca_resource: gca_feature_group.FeatureGroup
+
+ def __init__(
+ self,
+ name: str,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ """Retrieves an existing managed feature group.
+
+ Args:
+ name:
+ The resource name
+ (`projects/.../locations/.../featureGroups/...`) or ID.
+ project:
+ Project to retrieve feature group from. If unset, the
+ project set in aiplatform.init will be used.
+ location:
+ Location to retrieve feature group from. If not set,
+ location set in aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to retrieve this feature group.
+ Overrides credentials set in aiplatform.init.
+ """
+
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=name,
+ )
+
+ self._gca_resource = self._get_gca_resource(resource_name=name)
+
+ @classmethod
+ def create(
+ cls,
+ name: str,
+ source: FeatureGroupBigQuerySource = None,
+ labels: Optional[Dict[str, str]] = None,
+ description: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
+ create_request_timeout: Optional[float] = None,
+ sync: bool = True,
+ ) -> "FeatureGroup":
+ """Creates a new feature group.
+
+ Args:
+ name: The name of the feature group.
+ source: The BigQuery source of the feature group.
+ labels:
+ The labels with user-defined metadata to organize your
+ FeatureGroup.
+
+ Label keys and values can be no longer than 64
+ characters (Unicode codepoints), can only
+ contain lowercase letters, numeric characters,
+ underscores and dashes. International characters
+ are allowed.
+
+ See https://goo.gl/xmQnxf for more information
+ on and examples of labels. No more than 64 user
+ labels can be associated with one
+ FeatureGroup(System labels are excluded)."
+ System reserved label keys are prefixed with
+ "aiplatform.googleapis.com/" and are immutable.
+ description: Description of the FeatureGroup.
+ project:
+ Project to create feature group in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to create feature group in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to create this feature group.
+ Overrides credentials set in aiplatform.init.
+ request_metadata:
+ Strings which should be sent along with the request as metadata.
+ create_request_timeout:
+ The timeout for the create request in seconds.
+ sync:
+ Whether to execute this creation synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+
+ Returns:
+ FeatureGroup - the FeatureGroup resource object.
+ """
+
+ if not source:
+ raise ValueError("Please specify a valid source.")
+
+ # Only BigQuery source is supported right now.
+ if not isinstance(source, FeatureGroupBigQuerySource):
+ raise ValueError("Only FeatureGroupBigQuerySource is a supported source.")
+
+ # BigQuery source validation.
+ if not source.uri:
+ raise ValueError("Please specify URI in BigQuery source.")
+
+ if not source.entity_id_columns:
+ _LOGGER.info(
+ "No entity ID columns specified in BigQuery source. Defaulting to ['entity_id']."
+ )
+ entity_id_columns = ["entity_id"]
+ else:
+ entity_id_columns = source.entity_id_columns
+
+ gapic_feature_group = gca_feature_group.FeatureGroup(
+ big_query=gca_feature_group.FeatureGroup.BigQuery(
+ big_query_source=gca_io.BigQuerySource(input_uri=source.uri),
+ entity_id_columns=entity_id_columns,
+ ),
+ name=name,
+ description=description,
+ )
+
+ if labels:
+ utils.validate_labels(labels)
+ gapic_feature_group.labels = labels
+
+ if request_metadata is None:
+ request_metadata = ()
+
+ api_client = cls._instantiate_client(location=location, credentials=credentials)
+
+ create_feature_group_lro = api_client.create_feature_group(
+ parent=initializer.global_config.common_location_path(
+ project=project, location=location
+ ),
+ feature_group=gapic_feature_group,
+ feature_group_id=name,
+ metadata=request_metadata,
+ timeout=create_request_timeout,
+ )
+
+ _LOGGER.log_create_with_lro(cls, create_feature_group_lro)
+
+ created_feature_group = create_feature_group_lro.result()
+
+ _LOGGER.log_create_complete(cls, created_feature_group, "feature_group")
+
+ feature_group_obj = cls(
+ name=created_feature_group.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return feature_group_obj
+
+ @base.optional_sync()
+ def delete(self, force: bool = False, sync: bool = True) -> None:
+ """Deletes this feature group.
+
+ WARNING: This deletion is permanent.
+
+ Args:
+ force:
+ If set to True, all features under this online store will be
+ deleted prior to online store deletion. Otherwise, deletion
+ will only succeed if the online store has no FeatureViews.
+
+ If set to true, any Features under this FeatureGroup will also
+ be deleted. (Otherwise, the request will only work if the
+ FeatureGroup has no Features.)
+ sync:
+ Whether to execute this deletion synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+ """
+
+ lro = getattr(self.api_client, self._delete_method)(
+ name=self.resource_name,
+ force=force,
+ )
+ _LOGGER.log_delete_with_lro(self, lro)
+ lro.result()
+ _LOGGER.log_delete_complete(self)
+
+ def get_feature(
+ self,
+ feature_id: str,
+ latest_stats_count: Optional[int] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> Feature:
+ """Retrieves an existing managed feature.
+
+ Args:
+ feature_id: The ID of the feature.
+ latest_stats_count:
+ The number of latest stats to retrieve. Only returns stats if
+ Feature Monitor is created, and historical stats were generated.
+ credentials:
+ Custom credentials to use to retrieve the feature under this
+ feature group. The order of which credentials are used is as
+ follows: (1) this parameter (2) credentials passed to FeatureGroup
+ constructor (3) credentials set in aiplatform.init.
+
+ Returns:
+ Feature - the Feature resource object under this feature group.
+ """
+ credentials = (
+ credentials or self.credentials or initializer.global_config.credentials
+ )
+ if latest_stats_count is not None:
+ return Feature(
+ name=f"{self.resource_name}/features/{feature_id}",
+ latest_stats_count=latest_stats_count,
+ credentials=credentials,
+ )
+ return Feature(
+ f"{self.resource_name}/features/{feature_id}", credentials=credentials
+ )
+
+ def create_feature(
+ self,
+ name: str,
+ version_column_name: Optional[str] = None,
+ description: Optional[str] = None,
+ labels: Optional[Dict[str, str]] = None,
+ point_of_contact: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
+ create_request_timeout: Optional[float] = None,
+ sync: bool = True,
+ ) -> Feature:
+ """Creates a new feature.
+
+ Args:
+ name: The name of the feature.
+ version_column_name:
+ The name of the BigQuery Table/View column hosting data for this
+ version. If no value is provided, will use feature_id.
+ description: Description of the feature.
+ labels:
+ The labels with user-defined metadata to organize your Features.
+ Label keys and values can be no longer than 64 characters
+ (Unicode codepoints), can only contain lowercase letters,
+ numeric characters, underscores and dashes. International
+ characters are allowed.
+
+ See https://goo.gl/xmQnxf for more information on and examples
+ of labels. No more than 64 user labels can be associated with
+ one Feature (System labels are excluded)." System reserved label
+ keys are prefixed with "aiplatform.googleapis.com/" and are
+ immutable.
+ point_of_contact:
+ Entity responsible for maintaining this feature. Can be comma
+ separated list of email addresses or URIs.
+ project:
+ Project to create feature in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to create feature in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to create this feature. Overrides
+ credentials set in aiplatform.init.
+ request_metadata:
+ Strings which should be sent along with the request as metadata.
+ create_request_timeout:
+ The timeout for the create request in seconds.
+ sync:
+ Whether to execute this creation synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+
+ Returns:
+ Feature - the Feature resource object.
+ """
+
+ gapic_feature = gca_feature.Feature()
+
+ if version_column_name:
+ gapic_feature.version_column_name = version_column_name
+
+ if description:
+ gapic_feature.description = description
+
+ if labels:
+ utils.validate_labels(labels)
+ gapic_feature.labels = labels
+
+ if point_of_contact:
+ gapic_feature.point_of_contact = point_of_contact
+
+ if request_metadata is None:
+ request_metadata = ()
+
+ api_client = self.__class__._instantiate_client(
+ location=location, credentials=credentials
+ )
+
+ create_feature_lro = api_client.create_feature(
+ parent=self.resource_name,
+ feature=gapic_feature,
+ feature_id=name,
+ metadata=request_metadata,
+ timeout=create_request_timeout,
+ )
+
+ _LOGGER.log_create_with_lro(Feature, create_feature_lro)
+
+ created_feature = create_feature_lro.result()
+
+ _LOGGER.log_create_complete(Feature, created_feature, "feature")
+
+ feature_obj = Feature(
+ name=created_feature.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return feature_obj
+
+ def list_features(
+ self,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> List[Feature]:
+ """Lists features under this feature group.
+
+ Args:
+ project:
+ Project to list features in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to list features in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to list features. Overrides
+ credentials set in aiplatform.init.
+
+ Returns:
+ List of features under this feature group.
+ """
+
+ return Feature.list(
+ parent=self.resource_name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ def get_feature_monitor(
+ self,
+ feature_monitor_id: str,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> FeatureMonitor:
+ """Retrieves an existing feature monitor.
+
+ Args:
+ feature_monitor_id: The ID of the feature monitor.
+ credentials:
+ Custom credentials to use to retrieve the feature monitor under this
+ feature group. The order of which credentials are used is as
+ follows: (1) this parameter (2) credentials passed to FeatureGroup
+ constructor (3) credentials set in aiplatform.init.
+
+ Returns:
+ FeatureMonitor - the Feature Monitor resource object under this
+ feature group.
+ """
+ credentials = (
+ credentials or self.credentials or initializer.global_config.credentials
+ )
+ return FeatureMonitor(
+ f"{self.resource_name}/featureMonitors/{feature_monitor_id}",
+ credentials=credentials,
+ )
+
+ def create_feature_monitor(
+ self,
+ name: str,
+ description: Optional[str] = None,
+ labels: Optional[Dict[str, str]] = None,
+ schedule_config: Optional[str] = None,
+ feature_selection_configs: Optional[List[Tuple[str, float]]] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
+ create_request_timeout: Optional[float] = None,
+ ) -> FeatureMonitor:
+ """Creates a new feature monitor.
+
+ Args:
+ name: The name of the feature monitor.
+ description: Description of the feature monitor.
+ labels:
+ The labels with user-defined metadata to organize your FeatureMonitors.
+ Label keys and values can be no longer than 64 characters
+ (Unicode codepoints), can only contain lowercase letters,
+ numeric characters, underscores and dashes. International
+ characters are allowed.
+
+ See https://goo.gl/xmQnxf for more information on and examples
+ of labels. No more than 64 user labels can be associated with
+ one FeatureMonitor (System labels are excluded)." System reserved label
+ keys are prefixed with "aiplatform.googleapis.com/" and are
+ immutable.
+ schedule_config:
+ Configures when data is to be monitored for this
+ FeatureMonitor. At the end of the scheduled time,
+ the stats and drift are generated for the selected features.
+ Example format: "TZ=America/New_York 0 9 * * *" (monitors
+ daily at 9 AM EST).
+ feature_selection_configs:
+ List of tuples of feature id and monitoring threshold. If unset,
+ all features in the feature group will be monitored, and the
+ default thresholds 0.3 will be used.
+ project:
+ Project to create feature in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to create feature in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to create this feature. Overrides
+ credentials set in aiplatform.init.
+ request_metadata:
+ Strings which should be sent along with the request as metadata.
+ create_request_timeout:
+ The timeout for the create request in seconds.
+
+ Returns:
+ FeatureMonitor - the FeatureMonitor resource object.
+ """
+
+ gapic_feature_monitor = gca_feature_monitor.FeatureMonitor()
+
+ if description:
+ gapic_feature_monitor.description = description
+
+ if labels:
+ utils.validate_labels(labels)
+ gapic_feature_monitor.labels = labels
+
+ if request_metadata is None:
+ request_metadata = ()
+
+ if schedule_config:
+ gapic_feature_monitor.schedule_config = gca_feature_monitor.ScheduleConfig(
+ cron=schedule_config
+ )
+
+ if feature_selection_configs is None:
+ raise ValueError(
+ "Please specify feature_configs: features to be monitored and"
+ " their thresholds."
+ )
+
+ if feature_selection_configs is not None:
+ gapic_feature_monitor.feature_selection_config.feature_configs = [
+ gca_feature_monitor.FeatureSelectionConfig.FeatureConfig(
+ feature_id=feature_id,
+ drift_threshold=threshold if threshold else 0.3,
+ )
+ for feature_id, threshold in feature_selection_configs
+ ]
+
+ api_client = self.__class__._instantiate_client(
+ location=location, credentials=credentials
+ )
+
+ create_feature_monitor_lro = api_client.select_version(
+ "v1beta1"
+ ).create_feature_monitor(
+ parent=self.resource_name,
+ feature_monitor=gapic_feature_monitor,
+ feature_monitor_id=name,
+ metadata=request_metadata,
+ timeout=create_request_timeout,
+ )
+
+ _LOGGER.log_create_with_lro(FeatureMonitor, create_feature_monitor_lro)
+
+ created_feature_monitor = create_feature_monitor_lro.result()
+
+ _LOGGER.log_create_complete(
+ FeatureMonitor, created_feature_monitor, "feature_monitor"
+ )
+
+ feature_monitor_obj = FeatureMonitor(
+ name=created_feature_monitor.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return feature_monitor_obj
+
+ def list_feature_monitors(
+ self,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> List[FeatureMonitor]:
+ """Lists features monitors under this feature group.
+
+ Args:
+ project:
+ Project to list feature monitors in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to list feature monitors in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to list feature monitors. Overrides
+ credentials set in aiplatform.init.
+
+ Returns:
+ List of feature monitors under this feature group.
+ """
+
+ return FeatureMonitor.list(
+ parent=self.resource_name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ @property
+ def source(self) -> FeatureGroupBigQuerySource:
+ return FeatureGroupBigQuerySource(
+ uri=self._gca_resource.big_query.big_query_source.input_uri,
+ entity_id_columns=self._gca_resource.big_query.entity_id_columns,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_monitor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_monitor.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0172d22f1a49ac864fa7c683abf01688e36db18
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_monitor.py
@@ -0,0 +1,335 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import re
+from typing import List, Dict, Optional, Tuple, Sequence
+from google.auth import credentials as auth_credentials
+from google.cloud.aiplatform import base, initializer
+from google.cloud.aiplatform import utils
+from google.cloud.aiplatform.compat.types import (
+ feature_monitor_v1beta1 as gca_feature_monitor,
+ feature_monitor_job_v1beta1 as gca_feature_monitor_job,
+)
+
+_LOGGER = base.Logger(__name__)
+
+
+class FeatureMonitor(base.VertexAiResourceNounWithFutureManager):
+ """Class for managing Feature Monitor resources."""
+
+ client_class = utils.FeatureRegistryClientV1Beta1WithOverride
+
+ _resource_noun = "feature_monitors"
+ _getter_method = "get_feature_monitor"
+ _list_method = "list_feature_monitors"
+ _delete_method = "delete_feature_monitor"
+ _parse_resource_name_method = "parse_feature_monitor_path"
+ _format_resource_name_method = "feature_monitor_path"
+ _gca_resource: gca_feature_monitor.FeatureMonitor
+
+ def __init__(
+ self,
+ name: str,
+ feature_group_id: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ """Retrieves an existing managed feature.
+
+ Args:
+ name:
+ The resource name
+ (`projects/.../locations/.../featureGroups/.../featureMonitors/...`) or
+ ID.
+ feature_group_id:
+ The feature group ID. Must be passed in if name is an ID and not
+ a resource path.
+ project:
+ Project to retrieve feature from. If not set, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to retrieve feature from. If not set, the location set
+ in aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to retrieve this feature. Overrides
+ credentials set in aiplatform.init.
+ """
+
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=name,
+ )
+
+ if re.fullmatch(
+ r"projects/.+/locations/.+/featureGroups/.+/featureMonitors/.+",
+ name,
+ ):
+ if feature_group_id:
+ raise ValueError(
+ f"Since feature monitor '{name}' is provided as a path, feature_group_id should not be specified."
+ )
+ feature_monitor = name
+ else:
+ from .feature_group import FeatureGroup
+
+ # Construct the feature path using feature group ID if only the
+ # feature group ID is provided.
+ if not feature_group_id:
+ raise ValueError(
+ f"Since feature monitor '{name}' is not provided as a path, please specify feature_group_id."
+ )
+
+ feature_group_path = utils.full_resource_name(
+ resource_name=feature_group_id,
+ resource_noun=FeatureGroup._resource_noun,
+ parse_resource_name_method=FeatureGroup._parse_resource_name,
+ format_resource_name_method=FeatureGroup._format_resource_name,
+ )
+
+ feature_monitor = f"{feature_group_path}/featureMonitors/{name}"
+
+ self._gca_resource = self._get_gca_resource(resource_name=feature_monitor)
+
+ @property
+ def description(self) -> str:
+ """The description of the feature monitor."""
+ return self._gca_resource.description
+
+ @property
+ def schedule_config(self) -> str:
+ """The schedule config of the feature monitor."""
+ return self._gca_resource.schedule_config.cron
+
+ @property
+ def feature_selection_configs(self) -> List[Tuple[str, float]]:
+ """The feature and it's drift threshold configs of the feature monitor."""
+ configs: List[Tuple[str, float]] = []
+ for (
+ feature_config
+ ) in self._gca_resource.feature_selection_config.feature_configs:
+ configs.append(
+ (
+ feature_config.feature_id,
+ (
+ feature_config.drift_threshold
+ if feature_config.drift_threshold
+ else 0.3
+ ),
+ )
+ )
+ return configs
+
+ class FeatureMonitorJob(base.VertexAiResourceNounWithFutureManager):
+ """Class for managing Feature Monitor Job resources."""
+
+ client_class = utils.FeatureRegistryClientV1Beta1WithOverride
+
+ _resource_noun = "featureMonitorJobs"
+ _getter_method = "get_feature_monitor_job"
+ _list_method = "list_feature_monitor_jobs"
+ _delete_method = "delete_feature_monitor_job"
+ _parse_resource_name_method = "parse_feature_monitor_job_path"
+ _format_resource_name_method = "feature_monitor_job_path"
+ _gca_resource: gca_feature_monitor_job.FeatureMonitorJob
+
+ def __init__(
+ self,
+ name: str,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ """Retrieves an existing managed feature monitor job.
+
+ Args:
+ name: The resource name
+ (`projects/.../locations/.../featureGroups/.../featureMonitors/.../featureMonitorJobs/...`)
+ project: Project to retrieve the feature monitor job from. If
+ unset, the project set in aiplatform.init will be used.
+ location: Location to retrieve the feature monitor job from. If
+ not set, location set in aiplatform.init will be used.
+ credentials: Custom credentials to use to retrieve this feature
+ monitor job. Overrides credentials set in aiplatform.init.
+ """
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=name,
+ )
+
+ if not re.fullmatch(
+ r"projects/.+/locations/.+/featureGroups/.+/featureMonitors/.+/featureMonitorJobs/.+",
+ name,
+ ):
+ raise ValueError(
+ "name need to specify the fully qualified"
+ + " feature monitor job resource path."
+ )
+
+ self._gca_resource = self._get_gca_resource(resource_name=name)
+
+ @property
+ def description(self) -> str:
+ """The description of the feature monitor."""
+ return self._gca_resource.description
+
+ @property
+ def feature_stats_and_anomalies(
+ self,
+ ) -> List[gca_feature_monitor.FeatureStatsAndAnomaly]:
+ """The feature stats and anomaly of the feature monitor job."""
+ if self._gca_resource.job_summary:
+ return self._gca_resource.job_summary.feature_stats_and_anomalies
+ return []
+
+ def create_feature_monitor_job(
+ self,
+ description: Optional[str] = None,
+ labels: Optional[Dict[str, str]] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
+ create_request_timeout: Optional[float] = None,
+ ) -> FeatureMonitorJob:
+ """Creates a new feature monitor job.
+
+ Args:
+ description: Description of the feature monitor job.
+ labels:
+ The labels with user-defined metadata to organize your
+ FeatureMonitorJobs.
+ Label keys and values can be no longer than 64 characters
+ (Unicode codepoints), can only contain lowercase letters,
+ numeric characters, underscores and dashes. International
+ characters are allowed.
+
+ See https://goo.gl/xmQnxf for more information on and examples
+ of labels. No more than 64 user labels can be associated with
+ one FeatureMonitor (System labels are excluded)." System reserved label
+ keys are prefixed with "aiplatform.googleapis.com/" and are
+ immutable.
+ project:
+ Project to create feature in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to create feature in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to create this feature. Overrides
+ credentials set in aiplatform.init.
+ request_metadata:
+ Strings which should be sent along with the request as metadata.
+ create_request_timeout:
+ The timeout for the create request in seconds.
+
+ Returns:
+ FeatureMonitorJob - the FeatureMonitorJob resource object.
+ """
+
+ gapic_feature_monitor_job = gca_feature_monitor_job.FeatureMonitorJob()
+
+ if description:
+ gapic_feature_monitor_job.description = description
+
+ if labels:
+ utils.validate_labels(labels)
+ gapic_feature_monitor_job.labels = labels
+
+ if request_metadata is None:
+ request_metadata = ()
+
+ api_client = self.__class__._instantiate_client(
+ location=location, credentials=credentials
+ )
+
+ created_feature_monitor_job = api_client.select_version(
+ "v1beta1"
+ ).create_feature_monitor_job(
+ parent=self.resource_name,
+ feature_monitor_job=gapic_feature_monitor_job,
+ metadata=request_metadata,
+ timeout=create_request_timeout,
+ )
+
+ feature_monitor_job_obj = self.FeatureMonitorJob(
+ name=created_feature_monitor_job.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return feature_monitor_job_obj
+
+ def get_feature_monitor_job(
+ self,
+ feature_monitor_job_id: str,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> FeatureMonitorJob:
+ """Retrieves an existing feature monitor.
+
+ Args:
+ feature_monitor_job_id: The ID of the feature monitor job.
+ credentials:
+ Custom credentials to use to retrieve the feature monitor job under this
+ feature monitor. The order of which credentials are used is as
+ follows - (1) this parameter (2) credentials passed to FeatureMonitor
+ constructor (3) credentials set in aiplatform.init.
+
+ Returns:
+ FeatureMonitorJob - the Feature Monitor Job resource object under this
+ feature monitor.
+ """
+ credentials = (
+ credentials or self.credentials or initializer.global_config.credentials
+ )
+ return FeatureMonitor.FeatureMonitorJob(
+ f"{self.resource_name}/featureMonitorJobs/{feature_monitor_job_id}",
+ credentials=credentials,
+ )
+
+ def list_feature_monitor_jobs(
+ self,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> List[FeatureMonitorJob]:
+ """Lists features monitor jobs under this feature monitor.
+
+ Args:
+ project:
+ Project to list feature monitors in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to list feature monitors in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to list feature monitors. Overrides
+ credentials set in aiplatform.init.
+
+ Returns:
+ List of feature monitor jobs under this feature monitor.
+ """
+
+ return FeatureMonitor.FeatureMonitorJob.list(
+ parent=self.resource_name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_online_store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_online_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..c631494cb22039870c1bd70c38b4fbb80236a61f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_online_store.py
@@ -0,0 +1,647 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import enum
+from typing import (
+ Dict,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+from google.auth import credentials as auth_credentials
+from google.cloud.aiplatform import (
+ base,
+ initializer,
+ utils,
+)
+from google.cloud.aiplatform.compat.types import (
+ feature_online_store as gca_feature_online_store,
+ service_networking as gca_service_networking,
+ feature_view as gca_feature_view,
+)
+from agentplatform.resources.preview.feature_store.feature_view import (
+ FeatureView,
+)
+from agentplatform.resources.preview.feature_store.utils import (
+ IndexConfig,
+ FeatureViewBigQuerySource,
+ FeatureViewVertexRagSource,
+ FeatureViewRegistrySource,
+)
+
+
+_LOGGER = base.Logger(__name__)
+
+
+@enum.unique
+class FeatureOnlineStoreType(enum.Enum):
+ UNKNOWN = 0
+ BIGTABLE = 1
+ OPTIMIZED = 2
+
+
+class FeatureOnlineStore(base.VertexAiResourceNounWithFutureManager):
+ """Class for managing Feature Online Store resources."""
+
+ client_class = utils.FeatureOnlineStoreAdminClientWithOverride
+
+ _resource_noun = "feature_online_stores"
+ _getter_method = "get_feature_online_store"
+ _list_method = "list_feature_online_stores"
+ _delete_method = "delete_feature_online_store"
+ _parse_resource_name_method = "parse_feature_online_store_path"
+ _format_resource_name_method = "feature_online_store_path"
+ _gca_resource: gca_feature_online_store.FeatureOnlineStore
+
+ def __init__(
+ self,
+ name: str,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ """Retrieves an existing managed feature online store.
+
+ Args:
+ name:
+ The resource name
+ (`projects/.../locations/.../featureOnlineStores/...`) or ID.
+ project:
+ Project to retrieve feature online store from. If unset, the
+ project set in aiplatform.init will be used.
+ location:
+ Location to retrieve feature online store from. If not set,
+ location set in aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to retrieve this feature online store.
+ Overrides credentials set in aiplatform.init.
+ """
+
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=name,
+ )
+ self._gca_resource = self._get_gca_resource(resource_name=name)
+
+ @classmethod
+ @base.optional_sync()
+ def create_bigtable_store(
+ cls,
+ name: str,
+ min_node_count: Optional[int] = 1,
+ max_node_count: Optional[int] = 1,
+ cpu_utilization_target: Optional[int] = 50,
+ labels: Optional[Dict[str, str]] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
+ create_request_timeout: Optional[float] = None,
+ sync: bool = True,
+ ) -> "FeatureOnlineStore":
+ """Creates a Bigtable online store.
+
+ Example Usage:
+
+ my_fos = agentplatform.preview.FeatureOnlineStore.create_bigtable_store('my_fos')
+
+ Args:
+ name: The name of the feature online store.
+ min_node_count:
+ The minimum number of Bigtable nodes to scale down to. Must be
+ greater than or equal to 1.
+ max_node_count:
+ The maximum number of Bigtable nodes to scale up to. Must
+ satisfy min_node_count <= max_node_count <= (10 *
+ min_node_count).
+ cpu_utilization_target:
+ A percentage of the cluster's CPU capacity. Can be from 10% to
+ 80%. When a cluster's CPU utilization exceeds the target that
+ you have set, Bigtable immediately adds nodes to the cluster.
+ When CPU utilization is substantially lower than the target,
+ Bigtable removes nodes. If not set will default to 50%.
+ labels:
+ The labels with user-defined metadata to organize your feature
+ online store. Label keys and values can be no longer than 64
+ characters (Unicode codepoints), can only contain lowercase
+ letters, numeric characters, underscores and dashes.
+ International characters are allowed. See https://goo.gl/xmQnxf
+ for more information on and examples of labels. No more than 64
+ user labels can be associated with one feature online store
+ (System labels are excluded)." System reserved label keys are
+ prefixed with "aiplatform.googleapis.com/" and are immutable.
+ project:
+ Project to create feature online store in. If unset, the project
+ set in aiplatform.init will be used.
+ location:
+ Location to create feature online store in. If not set, location
+ set in aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to create this feature online store.
+ Overrides credentials set in aiplatform.init.
+ request_metadata:
+ Strings which should be sent along with the request as metadata.
+ create_request_timeout:
+ The timeout for the create request in seconds.
+ sync:
+ Whether to execute this creation synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+
+ Returns:
+ FeatureOnlineStore - the FeatureOnlineStore resource object.
+ """
+
+ if min_node_count < 1:
+ raise ValueError("min_node_count must be greater than or equal to 1")
+
+ if max_node_count < min_node_count:
+ raise ValueError(
+ "max_node_count must be greater than or equal to min_node_count"
+ )
+ elif 10 * min_node_count < max_node_count:
+ raise ValueError(
+ "max_node_count must be less than or equal to 10 * min_node_count"
+ )
+
+ if cpu_utilization_target < 10 or cpu_utilization_target > 80:
+ raise ValueError("cpu_utilization_target must be between 10 and 80")
+
+ gapic_feature_online_store = gca_feature_online_store.FeatureOnlineStore(
+ bigtable=gca_feature_online_store.FeatureOnlineStore.Bigtable(
+ auto_scaling=gca_feature_online_store.FeatureOnlineStore.Bigtable.AutoScaling(
+ min_node_count=min_node_count,
+ max_node_count=max_node_count,
+ cpu_utilization_target=cpu_utilization_target,
+ ),
+ ),
+ )
+
+ if labels:
+ utils.validate_labels(labels)
+ gapic_feature_online_store.labels = labels
+
+ if request_metadata is None:
+ request_metadata = ()
+
+ api_client = cls._instantiate_client(location=location, credentials=credentials)
+
+ create_online_store_lro = api_client.create_feature_online_store(
+ parent=initializer.global_config.common_location_path(
+ project=project, location=location
+ ),
+ feature_online_store=gapic_feature_online_store,
+ feature_online_store_id=name,
+ metadata=request_metadata,
+ timeout=create_request_timeout,
+ )
+
+ _LOGGER.log_create_with_lro(cls, create_online_store_lro)
+
+ created_online_store = create_online_store_lro.result()
+
+ _LOGGER.log_create_complete(cls, created_online_store, "feature_online_store")
+
+ online_store_obj = cls(
+ name=created_online_store.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return online_store_obj
+
+ @classmethod
+ @base.optional_sync()
+ def create_optimized_store(
+ cls,
+ name: str,
+ enable_private_service_connect: bool = False,
+ project_allowlist: Optional[Sequence[str]] = None,
+ labels: Optional[Dict[str, str]] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
+ create_request_timeout: Optional[float] = None,
+ sync: bool = True,
+ ) -> "FeatureOnlineStore":
+ """Creates an Optimized online store.
+
+ Example Usage:
+
+ ```
+ # Create optimized store with public endpoint.
+ my_fos = agentplatform.preview.FeatureOnlineStore.create_optimized_store(
+ 'my_fos'
+ )
+ ```
+
+ ```
+ # Create optimized online store with private service connect.
+ my_fos = agentplatform.preview.FeatureOnlineStore.create_optimized_store(
+ 'my_fos',
+ enable_private_service_connect=True,
+ project_allowlist=['my-project'],
+ )
+ ```
+
+ Args:
+ name: The name of the feature online store.
+ enable_private_service_connect:
+ Optional. If true, expose the optimized online store
+ via private service connect. Otherwise the optimized online
+ store will be accessible through public endpoint.
+ project_allowlist:
+ A list of Projects from which the forwarding
+ rule will target the service attachment. Only needed when
+ `enable_private_service_connect` is set to true.
+ labels:
+ The labels with user-defined metadata to organize your feature
+ online store. Label keys and values can be no longer than 64
+ characters (Unicode codepoints), can only contain lowercase
+ letters, numeric characters, underscores and dashes.
+ International characters are allowed. See https://goo.gl/xmQnxf
+ for more information on and examples of labels. No more than 64
+ user labels can be associated with one feature online store
+ (System labels are excluded)." System reserved label keys are
+ prefixed with "aiplatform.googleapis.com/" and are immutable.
+ project:
+ Project to create feature online store in. If unset, the project
+ set in aiplatform.init will be used.
+ location:
+ Location to create feature online store in. If not set, location
+ set in aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to create this feature online store.
+ Overrides credentials set in aiplatform.init.
+ request_metadata:
+ Strings which should be sent along with the request as metadata.
+ create_request_timeout:
+ The timeout for the create request in seconds.
+ sync:
+ Whether to execute this creation synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+
+ Returns:
+ FeatureOnlineStore - the FeatureOnlineStore resource object.
+ """
+ if enable_private_service_connect:
+ if not project_allowlist:
+ raise ValueError(
+ "`project_allowlist` cannot be empty when `enable_private_service_connect` is set to true."
+ )
+
+ dedicated_serving_endpoint = gca_feature_online_store.FeatureOnlineStore.DedicatedServingEndpoint(
+ private_service_connect_config=gca_service_networking.PrivateServiceConnectConfig(
+ enable_private_service_connect=True,
+ project_allowlist=project_allowlist,
+ ),
+ )
+ else:
+ dedicated_serving_endpoint = (
+ gca_feature_online_store.FeatureOnlineStore.DedicatedServingEndpoint()
+ )
+
+ gapic_feature_online_store = gca_feature_online_store.FeatureOnlineStore(
+ optimized=gca_feature_online_store.FeatureOnlineStore.Optimized(),
+ dedicated_serving_endpoint=dedicated_serving_endpoint,
+ )
+
+ if labels:
+ utils.validate_labels(labels)
+ gapic_feature_online_store.labels = labels
+
+ if request_metadata is None:
+ request_metadata = ()
+
+ api_client = cls._instantiate_client(location=location, credentials=credentials)
+
+ create_online_store_lro = api_client.create_feature_online_store(
+ parent=initializer.global_config.common_location_path(
+ project=project, location=location
+ ),
+ feature_online_store=gapic_feature_online_store,
+ feature_online_store_id=name,
+ metadata=request_metadata,
+ timeout=create_request_timeout,
+ )
+
+ _LOGGER.log_create_with_lro(cls, create_online_store_lro)
+
+ created_online_store = create_online_store_lro.result()
+
+ _LOGGER.log_create_complete(cls, created_online_store, "feature_online_store")
+
+ online_store_obj = cls(
+ name=created_online_store.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return online_store_obj
+
+ @base.optional_sync()
+ def delete(self, force: bool = False, sync: bool = True) -> None:
+ """Deletes this online store.
+
+ WARNING: This deletion is permanent.
+
+ Args:
+ force:
+ If set to True, all feature views under this online store will
+ be deleted prior to online store deletion. Otherwise, deletion
+ will only succeed if the online store has no FeatureViews.
+ sync:
+ Whether to execute this deletion synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+ """
+
+ lro = getattr(self.api_client, self._delete_method)(
+ name=self.resource_name,
+ force=force,
+ )
+ _LOGGER.log_delete_with_lro(self, lro)
+ lro.result()
+ _LOGGER.log_delete_complete(self)
+
+ @property
+ def feature_online_store_type(self) -> FeatureOnlineStoreType:
+ if self._gca_resource.bigtable:
+ return FeatureOnlineStoreType.BIGTABLE
+ # Optimized is an empty proto, so self._gca_resource.optimized is always false.
+ elif hasattr(self.gca_resource, "optimized"):
+ return FeatureOnlineStoreType.OPTIMIZED
+ else:
+ raise ValueError(
+ f"Online store does not have type or is unsupported by SDK: {self._gca_resource}."
+ )
+
+ @property
+ def labels(self) -> Dict[str, str]:
+ return self._gca_resource.labels
+
+ @base.optional_sync()
+ def create_feature_view(
+ self,
+ name: str,
+ source: Union[
+ FeatureViewBigQuerySource,
+ FeatureViewVertexRagSource,
+ FeatureViewRegistrySource,
+ ],
+ labels: Optional[Dict[str, str]] = None,
+ sync_config: Optional[str] = None,
+ index_config: Optional[IndexConfig] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
+ create_request_timeout: Optional[float] = None,
+ sync: bool = True,
+ ) -> FeatureView:
+ """Creates a FeatureView from a BigQuery source.
+
+ Example Usage:
+ ```
+ existing_fos = FeatureOnlineStore('my_fos')
+ new_fv = existing_fos.create_feature_view(
+ 'my_fos',
+ BigQuerySource(
+ uri='bq://my-proj/dataset/table',
+ entity_id_columns=['entity_id'],
+ )
+ )
+ # Example for how to create an embedding FeatureView.
+ embedding_fv = existing_fos.create_feature_view(
+ 'my_fos',
+ BigQuerySource(
+ uri='bq://my-proj/dataset/table',
+ entity_id_columns=['entity_id'],
+ )
+ index_config=IndexConfig(
+ embedding_column="embedding",
+ filter_column=["currency_code", "gender",
+ crowding_column="crowding",
+ dimentions=1536,
+ distance_measure_type=DistanceMeasureType.SQUARED_L2_DISTANCE,
+ algorithm_config=TreeAhConfig(),
+ )
+ )
+ ```
+ Args:
+ name: The name of the feature view.
+ source:
+ The source to load data from when a feature view sync runs.
+ Currently supports a BigQuery source, Vertex RAG source, Registry source.
+ labels:
+ The labels with user-defined metadata to organize your
+ FeatureViews.
+
+ Label keys and values can be no longer than 64 characters
+ (Unicode codepoints), can only contain lowercase letters,
+ numeric characters, underscores and dashes. International
+ characters are allowed.
+
+ See https://goo.gl/xmQnxf for more information on and examples
+ of labels. No more than 64 user labels can be associated with
+ one FeatureOnlineStore(System labels are excluded)." System
+ reserved label keys are prefixed with
+ "aiplatform.googleapis.com/" and are immutable.
+ sync_config:
+ Configures when data is to be synced/updated for this
+ FeatureView. At the end of the sync the latest feature values
+ for each entity ID of this FeatureView are made ready for online
+ serving. Example format: "TZ=America/New_York 0 9 * * *" (sync
+ daily at 9 AM EST).
+ index_config:
+ Configuration for index preparation for vector search. It
+ contains the required configurations to create an index from
+ source data, so that approximate nearest neighbor (a.k.a ANN)
+ algorithms search can be performed during online serving.
+ project:
+ Project to create feature view in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to create feature view in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to create this feature view.
+ Overrides credentials set in aiplatform.init.
+ request_metadata:
+ Strings which should be sent along with the request as metadata.
+ create_request_timeout:
+ The timeout for the create request in seconds.
+ sync:
+ Whether to execute this creation synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+
+ Returns:
+ FeatureView - the FeatureView resource object.
+ """
+ if not source:
+ raise ValueError("Please specify a valid source.")
+
+ big_query_source = None
+ vertex_rag_source = None
+ feature_registry_source = None
+
+ if isinstance(source, FeatureViewBigQuerySource):
+ if not source.uri:
+ raise ValueError("Please specify URI in BigQuery source.")
+
+ if not source.entity_id_columns:
+ raise ValueError("Please specify entity ID columns in BigQuery source.")
+
+ big_query_source = gca_feature_view.FeatureView.BigQuerySource(
+ uri=source.uri,
+ entity_id_columns=source.entity_id_columns,
+ )
+ elif isinstance(source, FeatureViewVertexRagSource):
+ if not source.uri:
+ raise ValueError("Please specify URI in Vertex RAG source.")
+
+ vertex_rag_source = gca_feature_view.FeatureView.VertexRagSource(
+ uri=source.uri,
+ rag_corpus_id=source.rag_corpus_id or None,
+ )
+ elif isinstance(source, FeatureViewRegistrySource):
+ if not source.features:
+ raise ValueError(
+ "Please specify features in Registry Source in format `.`."
+ )
+ feature_group_mappings = {}
+ for feature in source.features:
+ feature_group_id, feature_id = feature.split(".")
+ if not feature_id or not feature_group_id:
+ raise ValueError(
+ "Please specify features in Registry Source in format `.`."
+ )
+ if feature_group_id in feature_group_mappings:
+ feature_group_mappings[feature_group_id].append(feature_id)
+ else:
+ feature_group_mappings[feature_group_id] = [feature_id]
+ feature_groups = []
+ for feature_group_id in feature_group_mappings:
+ feature_ids = feature_group_mappings[feature_group_id]
+ feature_groups.append(
+ gca_feature_view.FeatureView.FeatureRegistrySource.FeatureGroup(
+ feature_group_id=feature_group_id,
+ feature_ids=feature_ids,
+ )
+ )
+ feature_registry_source = (
+ gca_feature_view.FeatureView.FeatureRegistrySource(
+ feature_groups=feature_groups,
+ project_number=source.project_number or None,
+ )
+ )
+ else:
+ raise ValueError(
+ "Only FeatureViewBigQuerySource, FeatureViewVertexRagSource and FeatureViewRegistrySource are supported sources."
+ )
+
+ gapic_feature_view = gca_feature_view.FeatureView(
+ big_query_source=big_query_source,
+ vertex_rag_source=vertex_rag_source,
+ feature_registry_source=feature_registry_source,
+ sync_config=(
+ gca_feature_view.FeatureView.SyncConfig(cron=sync_config)
+ if sync_config
+ else None
+ ),
+ )
+
+ if labels:
+ utils.validate_labels(labels)
+ gapic_feature_view.labels = labels
+
+ if request_metadata is None:
+ request_metadata = ()
+
+ if index_config:
+ gapic_feature_view.index_config = gca_feature_view.FeatureView.IndexConfig(
+ index_config.as_dict()
+ )
+
+ api_client = self.__class__._instantiate_client(
+ location=location, credentials=credentials
+ )
+
+ create_feature_view_lro = api_client.create_feature_view(
+ parent=self.resource_name,
+ feature_view=gapic_feature_view,
+ feature_view_id=name,
+ metadata=request_metadata,
+ timeout=create_request_timeout,
+ )
+
+ _LOGGER.log_create_with_lro(FeatureView, create_feature_view_lro)
+
+ created_feature_view = create_feature_view_lro.result()
+
+ _LOGGER.log_create_complete(FeatureView, created_feature_view, "feature_view")
+
+ feature_view_obj = FeatureView(
+ name=created_feature_view.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return feature_view_obj
+
+ def list_feature_views(
+ self,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> List[FeatureView]:
+ """Lists feature views under this feature online store.
+
+ Args:
+ project:
+ Project to list feature views in. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ Location to list feature views in. If not set, location set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to list feature views. Overrides
+ credentials set in aiplatform.init.
+
+ Returns:
+ List of feature views under this feature online store.
+ """
+
+ return FeatureView.list(
+ feature_online_store_id=self.name,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_view.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_view.py
new file mode 100644
index 0000000000000000000000000000000000000000..84ba9a65c7029765e722edbbdf8eeb215f747d61
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/feature_view.py
@@ -0,0 +1,537 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import re
+from typing import List, Dict, Optional
+from google.cloud.aiplatform import initializer
+from google.auth import credentials as auth_credentials
+from google.cloud.aiplatform import base
+from google.cloud.aiplatform import utils
+from google.cloud.aiplatform.compat.types import (
+ feature_view_sync as gca_feature_view_sync,
+ feature_view as gca_feature_view,
+ feature_online_store_service as fos_service,
+)
+import agentplatform.resources.preview.feature_store.utils as fs_utils
+
+_LOGGER = base.Logger(__name__)
+
+
+class FeatureView(base.VertexAiResourceNounWithFutureManager):
+ """Class for managing Feature View resources."""
+
+ client_class = utils.FeatureOnlineStoreAdminClientWithOverride
+
+ _resource_noun = "featureViews"
+ _getter_method = "get_feature_view"
+ _list_method = "list_feature_views"
+ _delete_method = "delete_feature_view"
+ _parse_resource_name_method = "parse_feature_view_path"
+ _format_resource_name_method = "feature_view_path"
+ _gca_resource: gca_feature_view.FeatureView
+ _online_store_client: utils.FeatureOnlineStoreClientWithOverride
+
+ _online_store_clients_with_connection_options: Dict[
+ fs_utils.ConnectionOptions, utils.FeatureOnlineStoreClientWithOverride
+ ] = None
+
+ def __init__(
+ self,
+ name: str,
+ feature_online_store_id: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ """Retrieves an existing managed feature view.
+
+ Args:
+ name:
+ The resource name
+ (`projects/.../locations/.../featureOnlineStores/.../featureViews/...`)
+ or ID.
+ feature_online_store_id:
+ The feature online store ID. Must be passed in if name is an ID
+ and not a resource path.
+ project:
+ Project to retrieve the feature view from. If unset, the project
+ set in aiplatform.init will be used.
+ location:
+ Location to retrieve the feature view from. If not set, location
+ set in aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to retrieve this feature view.
+ Overrides credentials set in aiplatform.init.
+ """
+
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=name,
+ )
+
+ if re.fullmatch(
+ r"projects/.+/locations/.+/featureOnlineStores/.+/featureViews/.+",
+ name,
+ ):
+ feature_view = name
+ else:
+ from .feature_online_store import FeatureOnlineStore
+
+ # Construct the feature view path using feature online store ID if
+ # only the feature view ID is provided.
+ if not feature_online_store_id:
+ raise ValueError(
+ "Since feature view is not provided as a path, please specify"
+ + " feature_online_store_id."
+ )
+
+ feature_online_store_path = utils.full_resource_name(
+ resource_name=feature_online_store_id,
+ resource_noun=FeatureOnlineStore._resource_noun,
+ parse_resource_name_method=FeatureOnlineStore._parse_resource_name,
+ format_resource_name_method=FeatureOnlineStore._format_resource_name,
+ )
+
+ feature_view = f"{feature_online_store_path}/featureViews/{name}"
+
+ self._gca_resource = self._get_gca_resource(resource_name=feature_view)
+
+ def _get_online_store_client(
+ self, connection_options: Optional[fs_utils.ConnectionOptions] = None
+ ) -> utils.FeatureOnlineStoreClientWithOverride:
+ """Return the online store client.
+
+ Also sets the `_online_store_client` attr if not set yet. Note that if
+ `connection_options` is passed in, the `_online_store_client` attr will
+ not be set - only the client will be returned. If the same
+ `connection_options` is passed in, this code will return the same
+ (cached) client as previously built.
+ """
+ if getattr(self, "_online_store_client", None):
+ return self._online_store_client
+
+ fos_name = fs_utils.get_feature_online_store_name(self.resource_name)
+ from .feature_online_store import FeatureOnlineStore
+
+ fos = FeatureOnlineStore(name=fos_name)
+
+ if connection_options:
+ # Check if we have a previously client created for these
+ # connection_options.
+ if self._online_store_clients_with_connection_options is None:
+ self._online_store_clients_with_connection_options = {}
+ if connection_options in self._online_store_clients_with_connection_options:
+ return self._online_store_clients_with_connection_options[
+ connection_options
+ ]
+ host = connection_options.host
+
+ if isinstance(
+ connection_options.transport,
+ fs_utils.ConnectionOptions.InsecureGrpcChannel,
+ ):
+ import grpc
+ from google.cloud.aiplatform_v1.services import (
+ feature_online_store_service as feature_online_store_service_v1,
+ )
+ from google.cloud.aiplatform_v1beta1.services import (
+ feature_online_store_service as feature_online_store_service_v1beta1,
+ )
+
+ gapic_client_class = (
+ utils.FeatureOnlineStoreClientWithOverride.get_gapic_client_class()
+ )
+ gapic_client_class_to_transport_class = {
+ feature_online_store_service_v1.client.FeatureOnlineStoreServiceClient: (
+ feature_online_store_service_v1.transports.grpc.FeatureOnlineStoreServiceGrpcTransport
+ ),
+ feature_online_store_service_v1beta1.client.FeatureOnlineStoreServiceClient: (
+ feature_online_store_service_v1beta1.transports.grpc.FeatureOnlineStoreServiceGrpcTransport
+ ),
+ }
+ if gapic_client_class not in gapic_client_class_to_transport_class:
+ raise ValueError(
+ f"Unexpected gapic class '{gapic_client_class}' used by internal client."
+ )
+
+ transport_class = gapic_client_class_to_transport_class[
+ gapic_client_class
+ ]
+
+ client = gapic_client_class(
+ transport=transport_class(
+ channel=grpc.insecure_channel(host + ":10002")
+ ),
+ )
+
+ self._online_store_clients_with_connection_options[
+ connection_options
+ ] = client
+ return client
+ else:
+ raise ValueError(
+ f"Unsupported connection transport type, got transport: {connection_options.transport}"
+ )
+
+ if fos._gca_resource.bigtable.auto_scaling:
+ # This is Bigtable online store.
+ _LOGGER.info(f"Connecting to Bigtable online store name {fos_name}")
+ self._online_store_client = initializer.global_config.create_client(
+ client_class=utils.FeatureOnlineStoreClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ return self._online_store_client
+
+ if (
+ fos._gca_resource.dedicated_serving_endpoint.private_service_connect_config.enable_private_service_connect
+ ):
+ raise ValueError(
+ "Use `connection_options` to specify an IP address. Required for optimized online store with private service connect."
+ )
+
+ # From here, optimized serving with public endpoint.
+ if not fos._gca_resource.dedicated_serving_endpoint.public_endpoint_domain_name:
+ raise fs_utils.PublicEndpointNotFoundError(
+ "Public endpoint is not created yet for the optimized online store:"
+ f"{fos_name}. Please run sync and wait for it to complete."
+ )
+
+ _LOGGER.info(
+ f"Public endpoint for the optimized online store {fos_name} is"
+ f" {fos._gca_resource.dedicated_serving_endpoint.public_endpoint_domain_name}"
+ )
+ self._online_store_client = initializer.global_config.create_client(
+ client_class=utils.FeatureOnlineStoreClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ prediction_client=True,
+ api_path_override=fos._gca_resource.dedicated_serving_endpoint.public_endpoint_domain_name,
+ )
+ return self._online_store_client
+
+ @classmethod
+ def list(
+ cls,
+ feature_online_store_id: str,
+ filter: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> List["FeatureView"]:
+ """List all feature view under feature_online_store_id.
+
+ Example Usage:
+ ```
+ feature_views = agentplatform.preview.FeatureView.list(
+ feature_online_store_id="my_fos",
+ filter=labels.label_key=label_value)
+ ```
+ Args:
+ feature_online_store_id:
+ Parentfeature online store ID.
+ filter:
+ Filter to apply on the returned feature online store.
+ project:
+ Project to use to get a list of feature views. If unset, the
+ project set in aiplatform.init will be used.
+ location:
+ Location to use to get a list feature views. If not set,
+ location set in aiplatform.init will be used.
+ credentials:
+ Custom credentials to use to get a list of feature views.
+ Overrides credentials set in aiplatform.init.
+
+ Returns:
+ List[FeatureView] - list of FeatureView resource object.
+ """
+ from .feature_online_store import FeatureOnlineStore
+
+ fos = FeatureOnlineStore(
+ name=feature_online_store_id,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+ return cls._list(
+ filter=filter, credentials=credentials, parent=fos.resource_name
+ )
+
+ @base.optional_sync()
+ def delete(self, sync: bool = True) -> None:
+ """Deletes this feature view.
+
+ WARNING: This deletion is permanent.
+
+ Args:
+ sync:
+ Whether to execute this deletion synchronously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+ """
+ lro = getattr(self.api_client, self._delete_method)(name=self.resource_name)
+ _LOGGER.log_delete_with_lro(self, lro)
+ lro.result()
+ _LOGGER.log_delete_complete(self)
+
+ def sync(self) -> "FeatureViewSync":
+ """Starts an on-demand Sync for the FeatureView.
+
+ Args: None
+
+ Returns:
+ "FeatureViewSync" - FeatureViewSync instance
+ """
+ sync_method = getattr(self.api_client, self.FeatureViewSync.sync_method())
+
+ sync_request = {
+ "feature_view": self.resource_name,
+ }
+ sync_response = sync_method(request=sync_request)
+
+ return self.FeatureViewSync(name=sync_response.feature_view_sync)
+
+ def get_sync(self, name) -> "FeatureViewSync":
+ """Gets the FeatureViewSync resource for the given name.
+
+ Args:
+ name: The resource ID
+
+ Returns:
+ "FeatureViewSync" - FeatureViewSync instance
+ """
+ feature_view_path = self.resource_name
+ feature_view_sync = f"{feature_view_path}/featureViewSyncs/{name}"
+ return self.FeatureViewSync(name=feature_view_sync)
+
+ def list_syncs(
+ self,
+ filter: Optional[str] = None,
+ ) -> List["FeatureViewSync"]:
+ """List all feature view under this FeatureView.
+
+ Args:
+ parent_resource_name: Fully qualified name of the parent FeatureView
+ resource.
+ filter: Filter to apply on the returned feature online store.
+
+ Returns:
+ List[FeatureViewSync] - list of FeatureViewSync resource object.
+ """
+
+ return self.FeatureViewSync._list(
+ filter=filter, credentials=self.credentials, parent=self.resource_name
+ )
+
+ def read(
+ self,
+ key: List[str],
+ connection_options: Optional[fs_utils.ConnectionOptions] = None,
+ request_timeout: Optional[float] = None,
+ ) -> fs_utils.FeatureViewReadResponse:
+ """Read the feature values from FeatureView.
+
+ Example Usage:
+ Read feature view. Use this for Bigtable online stores and for
+ Optimized online stores that use public endpoint.
+ ```
+ data = agentplatform.preview.FeatureView(
+ name='feature_view_name', feature_online_store_id='fos_name')
+ .read(key=[12345, 6789])
+ .to_dict()
+ ```
+
+ Read feature view using IP with an insecure gRPC channel. Use this
+ for optimized online stores using private service connect.
+ ```
+ data = agentplatform.preview.FeatureView(
+ name='feature_view_name', feature_online_store_id='fos_name')
+ .read(
+ key=[12345, 6789],
+ connection_options=fs_utils.ConnectionOptions(
+ host="",
+ transport=fs_utils.ConnectionOptions.InsecureGrpcChannel()))
+ .to_dict()
+ ```
+ Args:
+ key: The request key to read feature values for.
+ connection_options:
+ If specified, use these options to connect to a host for sending
+ requests instead of the default
+ `-aiplatform.googleapis.com` or the feature online
+ store's public endpoint.
+
+ Returns:
+ "FeatureViewReadResponse" - FeatureViewReadResponse object. It is
+ intermediate class that can be further converted by to_dict() or
+ to_proto().
+ """
+ self.wait()
+
+ online_store_client = self._get_online_store_client(
+ connection_options=connection_options
+ )
+
+ response = online_store_client.fetch_feature_values(
+ feature_view=self.resource_name,
+ data_key=fos_service.FeatureViewDataKey(
+ composite_key=fos_service.FeatureViewDataKey.CompositeKey(parts=key)
+ ),
+ timeout=request_timeout,
+ )
+ return fs_utils.FeatureViewReadResponse(response)
+
+ def search(
+ self,
+ entity_id: Optional[str] = None,
+ embedding_value: Optional[List[float]] = None,
+ neighbor_count: Optional[int] = None,
+ string_filters: Optional[
+ List[fos_service.NearestNeighborQuery.StringFilter]
+ ] = None,
+ per_crowding_attribute_neighbor_count: Optional[int] = None,
+ return_full_entity: bool = False,
+ approximate_neighbor_candidates: Optional[int] = None,
+ leaf_nodes_search_fraction: Optional[float] = None,
+ request_timeout: Optional[float] = None,
+ ) -> fs_utils.SearchNearestEntitiesResponse:
+ """Search the nearest entities from FeatureView.
+
+ Example Usage:
+ ```
+ data = agentplatform.preview.FeatureView(
+ name='feature_view_name', feature_online_store_id='fos_name')
+ .search(entity_id='sample_entity')
+ .to_dict()
+ ```
+ Args:
+ entity_id: The entity id whose similar entities should be searched
+ for.
+ embedding_value: The embedding vector that be used for similar
+ search.
+ neighbor_count: The number of similar entities to be retrieved
+ from feature view for each query.
+ string_filters: The list of string filters.
+ per_crowding_attribute_neighbor_count: Crowding is a constraint on a
+ neighbor list produced by nearest neighbor search requiring that
+ no more than sper_crowding_attribute_neighbor_count of the k
+ neighbors returned have the same value of crowding_attribute.
+ It's used for improving result diversity.
+ return_full_entity: If true, return full entities including the
+ features other than embeddings.
+ approximate_neighbor_candidates: The number of neighbors to find via
+ approximate search before exact reordering is performed; if set,
+ this value must be > neighbor_count.
+ leaf_nodes_search_fraction: The fraction of the number of leaves to
+ search, set at query time allows user to tune search performance.
+ This value increase result in both search accuracy and latency
+ increase. The value should be between 0.0 and 1.0.
+
+ Returns:
+ "SearchNearestEntitiesResponse" - SearchNearestEntitiesResponse
+ object. It is intermediate class that can be further converted by
+ to_dict() or to_proto()
+ """
+ self.wait()
+ if entity_id:
+ embedding = None
+ elif embedding_value:
+ embedding = fos_service.NearestNeighborQuery.Embedding(
+ value=embedding_value
+ )
+ else:
+ raise ValueError(
+ "Either entity_id or embedding_value needs to be provided for search."
+ )
+ response = self._get_online_store_client().search_nearest_entities(
+ request=fos_service.SearchNearestEntitiesRequest(
+ feature_view=self.resource_name,
+ query=fos_service.NearestNeighborQuery(
+ entity_id=entity_id,
+ embedding=embedding,
+ neighbor_count=neighbor_count,
+ string_filters=string_filters,
+ per_crowding_attribute_neighbor_count=per_crowding_attribute_neighbor_count, # pylint: disable=line-too-long
+ parameters=fos_service.NearestNeighborQuery.Parameters(
+ approximate_neighbor_candidates=approximate_neighbor_candidates,
+ leaf_nodes_search_fraction=leaf_nodes_search_fraction,
+ ),
+ ),
+ return_full_entity=return_full_entity,
+ ),
+ timeout=request_timeout,
+ )
+ return fs_utils.SearchNearestEntitiesResponse(response)
+
+ class FeatureViewSync(base.VertexAiResourceNounWithFutureManager):
+ """Class for managing Feature View Sync resources."""
+
+ client_class = utils.FeatureOnlineStoreAdminClientWithOverride
+
+ _resource_noun = "featureViewSyncs"
+ _getter_method = "get_feature_view_sync"
+ _list_method = "list_feature_view_syncs"
+ _delete_method = "delete_feature_view"
+ _sync_method = "sync_feature_view"
+ _parse_resource_name_method = "parse_feature_view_sync_path"
+ _format_resource_name_method = "feature_view_sync_path"
+ _gca_resource: gca_feature_view_sync.FeatureViewSync
+
+ def __init__(
+ self,
+ name: str,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ """Retrieves an existing managed feature view sync.
+
+ Args:
+ name: The resource name
+ (`projects/.../locations/.../featureOnlineStores/.../featureViews/.../featureViewSyncs/...`)
+ project: Project to retrieve the feature view from. If unset, the
+ project set in aiplatform.init will be used.
+ location: Location to retrieve the feature view from. If not set,
+ location set in aiplatform.init will be used.
+ credentials: Custom credentials to use to retrieve this feature view.
+ Overrides credentials set in aiplatform.init.
+ """
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=name,
+ )
+
+ if not re.fullmatch(
+ r"projects/.+/locations/.+/featureOnlineStores/.+/featureViews/.+/featureViewSyncs/.+",
+ name,
+ ):
+ raise ValueError(
+ "name need to specify the fully qualified"
+ + " feature_view_sync resource path."
+ )
+
+ self._gca_resource = getattr(self.api_client, self._getter_method)(
+ name=name, retry=base._DEFAULT_RETRY
+ )
+
+ @classmethod
+ def sync_method(cls) -> str:
+ """Returns the sync method."""
+ return cls._sync_method
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/offline_store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/offline_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ba369d16838ec95b9547faa188f7ceed24b56c6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/offline_store.py
@@ -0,0 +1,289 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import datetime
+import re
+
+from typing import Optional, List, Tuple, Union, TYPE_CHECKING
+from google.auth import credentials as auth_credentials
+from agentplatform.resources.preview.feature_store import (
+ FeatureGroup,
+ Feature,
+)
+from google.cloud.aiplatform import initializer, __version__
+
+from . import _offline_store_impl as impl
+
+
+if TYPE_CHECKING:
+ try:
+ import bigframes
+ except ImportError:
+ bigframes = None
+
+ try:
+ import pandas as pd
+ except ImportError:
+ pd = None
+
+
+def _try_import_bigframes():
+ """Try to import `bigframes` and return it if successful - otherwise raise an import error."""
+ try:
+ import bigframes
+ import bigframes.pandas
+
+ return bigframes
+ except ImportError as exc:
+ raise ImportError(
+ "`bigframes` is not installed but required for this functionality."
+ ) from exc
+
+
+def _get_feature_group_from_feature(
+ feature: Feature, credentials: auth_credentials.Credentials
+):
+ """Given a feature, return the feature group resource."""
+ result = re.fullmatch(
+ r"projects/(?P.+)/locations/(?P.+)/featureGroups/(?P.+)/features/.+",
+ feature.resource_name,
+ )
+
+ if not result:
+ raise ValueError("Couldn't find feature group in feature.")
+
+ project = feature.project
+ location = feature.location
+ feature_group = result.group("feature_group")
+
+ return FeatureGroup(
+ feature_group, project=project, location=location, credentials=credentials
+ )
+
+
+def _extract_feature_from_str_repr(
+ str_feature: str, credentials: auth_credentials.Credentials
+) -> Tuple[FeatureGroup, Feature]:
+ """Given a feature in string representation, return the feature and feature group."""
+ # TODO: compile expr + place it in a constant
+ result = re.fullmatch(
+ r"((?P.*)\.)?(?P.*)\.(?P.*)",
+ str_feature,
+ )
+ if not result:
+ raise ValueError(
+ f"Feature '{str_feature}' is a string but not in expected format 'feature_group.feature' or 'project.feature_group.feature'."
+ )
+
+ feature_group = FeatureGroup(
+ result.group("feature_group"),
+ project=result.group("project"), # None if no match.
+ credentials=credentials,
+ )
+ feature = feature_group.get_feature(result.group("feature"))
+
+ return (feature_group, feature)
+
+
+def _feature_to_data_source(
+ feature_group: FeatureGroup, feature: Feature
+) -> impl.DataSource:
+ qualifying_name = f"{feature_group.name}__{feature.name}"
+ gbq_column = feature.version_column_name
+ assert gbq_column
+
+ column_name = feature.name
+ assert column_name
+
+ timestamp_column = "feature_timestamp"
+
+ # TODO: Expose entity_id_columns as a property in FeatureGroup
+ entity_id_columns = feature_group._gca_resource.big_query.entity_id_columns
+ assert entity_id_columns
+
+ bq_uri = feature_group._gca_resource.big_query.big_query_source.input_uri
+ assert bq_uri
+
+ fully_qualified_table = bq_uri.lstrip("bq://")
+ assert fully_qualified_table
+
+ query = (
+ f"SELECT\n"
+ f' {", ".join(entity_id_columns)},\n'
+ f" {gbq_column} AS {column_name},\n"
+ f" {timestamp_column}\n"
+ f"FROM {fully_qualified_table}"
+ )
+
+ return impl.DataSource(
+ qualifying_name=qualifying_name,
+ sql=query,
+ data_columns=[column_name],
+ # TODO: this will be parameterized in the future
+ timestamp_column=timestamp_column,
+ entity_id_columns=entity_id_columns,
+ )
+
+
+class _DataFrameToBigQueryDataFramesConverter:
+ @classmethod
+ def to_bigquery_dataframe(
+ cls, df: "pd.DataFrame", session: "Optional[bigframes.session.Session]" = None
+ ) -> "bigframes.pandas.DataFrame":
+ bigframes = _try_import_bigframes()
+ return bigframes.pandas.DataFrame(data=df, session=session)
+
+
+def fetch_historical_feature_values(
+ entity_df: "bigframes.pandas.DataFrame",
+ # TODO: Add support for FeatureView | FeatureGroup | bigframes.pandas.DataFrame
+ features: List[Union[str, Feature]],
+ # TODO: Add support for feature_age_threshold
+ feature_age_threshold: Optional[datetime.timedelta] = None,
+ dry_run: bool = False,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+) -> "Union[bigframes.pandas.DataFrame, None]":
+ """Fetch historical data at the timestamp specified for each entity.
+
+ This runs a Point-In-Time Lookup (PITL) query in BigQuery across all
+ features and returns the historical feature values. Feature data will be
+ joined by matching their entity_id_column(s) with corresponding columns in
+ the entity data frame.
+
+ Args:
+ entity_df:
+ An entity DataFrame where one/multiple columns have entity ID.
+ One column should have a timestamp (used for feature lookup). Other
+ columns may have feature data. Entity IDs may be repeated with
+ different timestamp values (in the timestamp column) to lookup data for
+ entities at different points in time.
+ features:
+ Feature data will be joined with the entity data frame.
+ * If `str` is given use `project.feature_group.feature` as the format.
+ `project_id.feature_group_id.feature_id` may be used if features are
+ in another project.
+ * If `FeatureView` is given, the *sources* of the FeatureView will be
+ used - but data will be read from the backing BigQuery table.
+ feature_age_threshold:
+ How far back from the timestamp to look for features values. If no
+ feature values are found, empty/null value will be populated.
+ dry_run:
+ Build the Point-In-Time Lookup (PITL) query but don't run it. The PITL
+ query will be printed to stdout.
+ project:
+ The project to use for feature lookup and running the Point-In-Time
+ Lookup (PITL) query in BigQuery. If unset, the project set in
+ aiplatform.init will be used.
+ location:
+ The location to use for feature lookup and running the Point-In-Time
+ Lookup (PITL) query in BigQuery. If unset, the project set in
+ aiplatform.init will be used.
+ credentials:
+ Custom credentials to use for feature lookup and running the
+ Point-In-Time Lookup (PITL) query in BigQuery. Overrides credentials
+ set in aiplatform.init.
+
+ Returns:
+ A `bigframes.pandas.DataFrame` with the historical feature values. `None`
+ if in `dry_run` mode.
+ """
+
+ bigframes = _try_import_bigframes()
+ project = project or initializer.global_config.project
+ location = location or initializer.global_config.location
+ credentials = credentials or initializer.global_config.credentials
+ application_name = (
+ f"vertexai-offline-store/{__version__}+fetch-historical-feature-values"
+ )
+ session_options = bigframes.BigQueryOptions(
+ credentials=credentials,
+ project=project,
+ location=location,
+ application_name=application_name,
+ )
+ session = bigframes.connect(session_options)
+
+ if feature_age_threshold is not None:
+ raise NotImplementedError("feature_age_threshold is not yet supported.")
+
+ if not features:
+ raise ValueError("Please specify a non-empty list of features.")
+
+ # Convert to bigframe if needed.
+ if not isinstance(entity_df, bigframes.pandas.DataFrame):
+ entity_df = _DataFrameToBigQueryDataFramesConverter.to_bigquery_dataframe(
+ df=entity_df,
+ session=session,
+ )
+
+ # Ensure one timestamp column is present in the entity DataFrame.
+ ts_cols = entity_df.select_dtypes(include=["datetime"]).columns
+ if len(ts_cols) > 1:
+ # TODO: Support multiple timestamp columns by specifying feature_timestamp column in an override.
+ raise ValueError(
+ 'Multiple timestamp columns ("datetime" dtype) found in entity DataFrame. '
+ "Only one timestamp column is allowed. "
+ f"Timestamp columns: {', '.join([col for col in ts_cols])}"
+ )
+ elif len(ts_cols) == 0:
+ raise ValueError(
+ 'No timestamp column ("datetime" dtype) found in entity DataFrame.'
+ )
+ entity_df_ts_col = ts_cols[0]
+ entity_df_non_ts_cols = [c for c in entity_df.columns if c != entity_df_ts_col]
+ entity_data_source = impl.DataSource(
+ qualifying_name="entity_df",
+ sql=entity_df.sql,
+ data_columns=entity_df_non_ts_cols,
+ timestamp_column=entity_df_ts_col,
+ )
+
+ feature_data: List[impl.DataSource] = []
+ for feature in features:
+ if isinstance(feature, Feature):
+ feature_group = _get_feature_group_from_feature(feature, credentials)
+ feature_data.append(_feature_to_data_source(feature_group, feature))
+ elif isinstance(feature, str):
+ feature_group, feature = _extract_feature_from_str_repr(
+ feature, credentials
+ )
+ feature_data.append(_feature_to_data_source(feature_group, feature))
+ else:
+ raise ValueError(
+ f"Unsupported feature type {type(feature)} found in feature list. Feature: {feature}"
+ )
+
+ # TODO: Verify `feature_data`.
+ # * Ensure that qualifying_names are not interfering.
+ # * Ensure that feature names are not interfering.
+ # * Ensure that entity id columns of all features are present in the entity DF.
+
+ query = impl.render_pitl_query(
+ entity_data=entity_data_source,
+ feature_data=feature_data,
+ )
+
+ if dry_run:
+ print("--- Dry run mode: PITL QUERY BEGIN ---")
+ print(query)
+ print("--- Dry run mode: PITL QUERY END ---")
+ return None
+
+ return session.read_gbq_query(
+ query,
+ index_col=bigframes.enums.DefaultIndexKind.NULL,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3f1e90fe2e45093b928699d06709165aa2ae8c8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/feature_store/utils.py
@@ -0,0 +1,231 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import abc
+from dataclasses import dataclass
+from dataclasses import field
+import enum
+from typing import Any, Dict, List, Optional, Union
+from google.cloud.aiplatform.compat.types import (
+ feature_online_store_service as fos_service,
+)
+import proto
+from typing_extensions import override
+
+
+def get_feature_online_store_name(online_store_name: str) -> str:
+ """Extract Feature Online Store's name from FeatureView's full resource name.
+
+ Args:
+ online_store_name: Full resource name is projects/project_number/
+ locations/us-central1/featureOnlineStores/fos_name/featureViews/fv_name
+
+ Returns:
+ str: feature online store name.
+ """
+ arr = online_store_name.split("/")
+ return arr[5]
+
+
+class PublicEndpointNotFoundError(RuntimeError):
+ """Public endpoint has not been created yet."""
+
+
+@dataclass
+class FeatureViewBigQuerySource:
+ uri: str
+ entity_id_columns: List[str]
+
+
+@dataclass
+class FeatureViewVertexRagSource:
+ uri: str
+ rag_corpus_id: Optional[str] = None
+
+
+@dataclass
+class FeatureViewRegistrySource:
+ """Configuration options for Feature View being registered with Feature Registry features.
+
+ Attributes:
+ features : Use `.` as
+ the format for each feature.
+ project_number : Optional. The project number of the project that owns the
+ Feature Registry if in a different project.
+ """
+
+ features: List[str]
+ project_number: Optional[int] = None
+
+
+@dataclass(frozen=True)
+class ConnectionOptions:
+ """Represents connection options used for sending RPCs to the online store."""
+
+ @dataclass(frozen=True)
+ class InsecureGrpcChannel:
+ """Use an insecure gRPC channel to connect to the host."""
+
+ pass
+
+ host: str # IP address or DNS.
+ transport: Union[
+ InsecureGrpcChannel
+ ] # Currently only insecure gRPC channel is supported.
+
+ def __eq__(self, other):
+ if self.host != other.host:
+ return False
+
+ if isinstance(self.transport, ConnectionOptions.InsecureGrpcChannel):
+ # Insecure grpc channel has no other parameters to check.
+ if isinstance(other.transport, ConnectionOptions.InsecureGrpcChannel):
+ return True
+
+ # Otherwise, can't compare against a different transport type.
+ raise ValueError(
+ f"Transport '{self.transport}' cannot be compared to transport '{other.transport}'."
+ )
+
+ # Currently only InsecureGrpcChannel is supported.
+ raise ValueError(f"Unsupported transport supplied: {self.transport}")
+
+
+@dataclass
+class FeatureViewReadResponse:
+ _response: fos_service.FetchFeatureValuesResponse
+
+ def __init__(self, response: fos_service.FetchFeatureValuesResponse):
+ self._response = response
+
+ def to_dict(self) -> Dict[str, Any]:
+ return proto.Message.to_dict(self._response.key_values)
+
+ def to_proto(self) -> fos_service.FetchFeatureValuesResponse:
+ return self._response
+
+
+@dataclass
+class SearchNearestEntitiesResponse:
+ _response: fos_service.SearchNearestEntitiesResponse
+
+ def __init__(self, response: fos_service.SearchNearestEntitiesResponse):
+ self._response = response
+
+ def to_dict(self) -> Dict[str, Any]:
+ return proto.Message.to_dict(self._response.nearest_neighbors)
+
+ def to_proto(self) -> fos_service.SearchNearestEntitiesResponse:
+ return self._response
+
+
+class DistanceMeasureType(enum.Enum):
+ """The distance measure used in nearest neighbor search."""
+
+ DISTANCE_MEASURE_TYPE_UNSPECIFIED = 0
+ # Euclidean (L_2) Distance.
+ SQUARED_L2_DISTANCE = 1
+ # Cosine Distance. Defined as 1 - cosine similarity.
+ COSINE_DISTANCE = 2
+ # Dot Product Distance. Defined as a negative of the dot product.
+ DOT_PRODUCT_DISTANCE = 3
+
+
+class AlgorithmConfig(abc.ABC):
+ """Base class for configuration options for matching algorithm."""
+
+ def as_dict(self) -> Dict:
+ """Returns the configuration as a dictionary.
+
+ Returns:
+ Dict[str, Any]
+ """
+ pass
+
+
+@dataclass
+class TreeAhConfig(AlgorithmConfig):
+ """Configuration options for using the tree-AH algorithm (Shallow tree + Asymmetric Hashing).
+
+ Please refer to this paper for more details: https://arxiv.org/abs/1908.10396
+
+ Args:
+ leaf_node_embedding_count (int): Optional. Number of embeddings on each
+ leaf node. The default value is 1000 if not set.
+ """
+
+ leaf_node_embedding_count: Optional[int] = None
+
+ @override
+ def as_dict(self) -> Dict:
+ return {"leaf_node_embedding_count": self.leaf_node_embedding_count}
+
+
+@dataclass
+class BruteForceConfig(AlgorithmConfig):
+ """Configuration options for using brute force search.
+
+ It simply implements the standard linear search in the database for each
+ query.
+ """
+
+ @override
+ def as_dict(self) -> Dict[str, Any]:
+ return {"bruteForceConfig": {}}
+
+
+@dataclass
+class IndexConfig:
+ """Configuration options for the Vertex FeatureView for embedding."""
+
+ embedding_column: str
+ dimensions: int
+ algorithm_config: AlgorithmConfig = field(default_factory=TreeAhConfig())
+ filter_columns: Optional[List[str]] = None
+ crowding_column: Optional[str] = None
+ distance_measure_type: Optional[DistanceMeasureType] = None
+
+ def as_dict(self) -> Dict[str, Any]:
+ """Returns the configuration as a dictionary.
+
+ Returns:
+ Dict[str, Any]
+ """
+ config = {
+ "embedding_column": self.embedding_column,
+ "embedding_dimension": self.dimensions,
+ }
+ if self.distance_measure_type is not None:
+ config["distance_measure_type"] = self.distance_measure_type.value
+ if self.filter_columns is not None:
+ config["filter_columns"] = self.filter_columns
+ if self.crowding_column is not None:
+ config["crowding_column"] = self.crowding_column
+
+ if isinstance(self.algorithm_config, TreeAhConfig):
+ config["tree_ah_config"] = self.algorithm_config.as_dict()
+ else:
+ config["brute_force_config"] = self.algorithm_config.as_dict()
+ return config
+
+
+@dataclass
+class FeatureGroupBigQuerySource:
+ """BigQuery source for the Feature Group."""
+
+ # The URI for the BigQuery table/view.
+ uri: str
+ # The entity ID columns. If not specified, defaults to ['entity_id'].
+ entity_id_columns: Optional[List[str]] = None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..41bbc1427fa95c73f895b6e55d94f74b2b59d13e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__init__.py
@@ -0,0 +1,24 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from agentplatform.resources.preview.ml_monitoring.model_monitors import (
+ ModelMonitor,
+ ModelMonitoringJob,
+)
+
+__all__ = (
+ "ModelMonitor",
+ "ModelMonitoringJob",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad0c72135455e6d3c805344e907bc2b19f0e4f52
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__pycache__/model_monitors.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__pycache__/model_monitors.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed4c20e529b4c41cd721498d550ef5f3f5ad85d2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/__pycache__/model_monitors.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/model_monitors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/model_monitors.py
new file mode 100644
index 0000000000000000000000000000000000000000..364b7f7c46a3f1fb03348ebf1d0dc376841ffbb6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/model_monitors.py
@@ -0,0 +1,1866 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import copy
+import dataclasses
+import json
+import re
+import time
+from typing import Any, Dict, List, Optional
+
+from google.auth import credentials as auth_credentials
+from agentplatform.resources.preview.ml_monitoring.spec import (
+ notification,
+ objective,
+ output,
+ schema,
+)
+from google.cloud.aiplatform import base, initializer, utils
+from google.cloud.aiplatform.compat.types import (
+ explanation_v1beta1 as explanation,
+ job_state_v1beta1 as gca_job_state,
+ model_monitor_v1beta1 as gca_model_monitor_compat,
+ model_monitoring_alert_v1beta1 as model_monitoring_alert,
+ model_monitoring_job_v1beta1 as gca_model_monitoring_job_compat,
+ model_monitoring_service_v1beta1 as model_monitoring_service,
+ model_monitoring_spec_v1beta1 as model_monitoring_spec,
+ model_monitoring_stats_v1beta1 as model_monitoring_stats,
+ schedule_service_v1beta1 as gca_schedule_service,
+ schedule_v1beta1 as gca_schedule,
+)
+import proto
+
+from google.protobuf import field_mask_pb2
+from google.protobuf import timestamp_pb2
+from google.type import interval_pb2
+from google.protobuf import text_format
+
+try:
+ import tensorflow as tf
+except ImportError:
+ tf = None
+try:
+ import tensorflow_data_validation as tfdv
+except ImportError:
+ tfdv = None
+try:
+ from tensorflow_metadata.proto.v0 import statistics_pb2
+ from tensorflow_metadata.proto.v0 import anomalies_pb2
+except ImportError:
+ statistics_pb2 = None
+ anomalies_pb2 = None
+
+_LOGGER = base.Logger(__name__)
+
+_JOB_COMPLETE_STATES = (
+ gca_job_state.JobState.JOB_STATE_SUCCEEDED,
+ gca_job_state.JobState.JOB_STATE_FAILED,
+ gca_job_state.JobState.JOB_STATE_PARTIALLY_SUCCEEDED,
+)
+
+_JOB_ERROR_STATES = (gca_job_state.JobState.JOB_STATE_FAILED,)
+
+# _block_until_complete wait times
+_JOB_WAIT_TIME = 5 # start at five seconds
+_LOG_WAIT_TIME = 5
+_MAX_WAIT_TIME = 60 * 5 # 5 minute wait
+_WAIT_TIME_MULTIPLIER = 2 # scale wait by 2 every iteration
+
+
+def _visualize_stats(
+ baseline_stats_output: str, target_stats_output: str
+) -> None:
+ """Visualizes the model monitoring stats from output directory."""
+ import tensorflow as tf
+
+ if not statistics_pb2:
+ raise TypeError(
+ "statistics_pb2 should be installed to visualize the results"
+ )
+ if not tf.io.gfile.exists(target_stats_output):
+ raise ValueError("No stats were generated.")
+ if tf.io.gfile.exists(baseline_stats_output):
+ with tf.io.gfile.GFile(
+ baseline_stats_output, "rb"
+ ) as baseline, tf.io.gfile.GFile(target_stats_output, "rb") as target:
+ baseline_combined_stats = statistics_pb2.DatasetFeatureStatisticsList()
+ baseline_combined_stats.ParseFromString(baseline.read())
+ target_combined_stats = statistics_pb2.DatasetFeatureStatisticsList()
+ target_combined_stats.ParseFromString(target.read())
+ baseline.close()
+ target.close()
+ tfdv.visualize_statistics(
+ lhs_statistics=baseline_combined_stats,
+ rhs_statistics=target_combined_stats,
+ lhs_name="Baseline Stats",
+ rhs_name="Target Stats",
+ )
+ else:
+ with tf.io.gfile.GFile(target_stats_output, "rb") as target:
+ target_combined_stats = statistics_pb2.DatasetFeatureStatisticsList()
+ target_combined_stats.ParseFromString(target.read())
+ target.close()
+ tfdv.visualize_statistics(target_combined_stats)
+
+
+def _visualize_anomalies(anomalies_output: str) -> None:
+ """Visualizes the model monitoring anomalies from output directory."""
+ import tensorflow as tf
+
+ if not anomalies_pb2:
+ raise TypeError(
+ "anomalies_pb2 should be installed to visualize the results"
+ )
+ with tf.io.gfile.GFile(anomalies_output, "r") as f:
+ anomalies = anomalies_pb2.Anomalies()
+ text_format.Merge(f.read(), anomalies)
+ f.close()
+ tfdv.display_anomalies(anomalies)
+
+
+def _visualize_feature_attribution(feature_attribution_output: str) -> None:
+ """Visualizes the model monitoring feature attribution from output directory."""
+ import tensorflow as tf
+
+ with tf.io.gfile.GFile(feature_attribution_output, "r") as f:
+ print(json.dumps(json.loads(f.read()), indent=4))
+
+
+def _feature_drift_stats_output_path(
+ output_directory: str, job_id: str
+) -> (str, str):
+ """Returns the baseline and target output paths for the model monitoring feature drift stats."""
+ return (
+ f"{output_directory}/tabular/jobs/{job_id}/feature_drift/baseline/statistics",
+ f"{output_directory}/tabular/jobs/{job_id}/feature_drift/target/statistics",
+ )
+
+
+def _feature_drift_anomalies_output_path(
+ output_directory: str, job_id: str
+) -> str:
+ """Returns the output path for the model monitoring anomalies."""
+ return f"{output_directory}/tabular/jobs/{job_id}/feature_drift/anomalies.textproto"
+
+
+def _prediction_output_stats_output_path(
+ output_directory: str, job_id: str
+) -> (str, str):
+ """Returns the baseline and target output paths for the model monitoring prediction output stats."""
+ return (
+ f"{output_directory}/tabular/jobs/{job_id}/output_drift/baseline/statistics",
+ f"{output_directory}/tabular/jobs/{job_id}/output_drift/target/statistics",
+ )
+
+
+def _prediction_output_anomalies_output_path(
+ output_directory: str, job_id: str
+) -> str:
+ """Returns the output path for the model monitoring anomalies."""
+ return f"{output_directory}/tabular/jobs/{job_id}/output_drift/anomalies.textproto"
+
+
+def _feature_attribution_target_stats_output_path(
+ output_directory: str, job_id: str
+) -> str:
+ """Returns the output path for the model monitoring stats."""
+ return (
+ f"{output_directory}/tabular/jobs/{job_id}/xai/target/feature_score.json"
+ )
+
+
+def _feature_attribution_baseline_stats_output_path(
+ output_directory: str, job_id: str
+) -> str:
+ """Returns the output path for the model monitoring anomalies."""
+ return f"{output_directory}/tabular/jobs/{job_id}/xai/baseline/feature_score.json"
+
+
+def _transform_schema_pandas(
+ dataset: Dict[str, str],
+ feature_fields: Optional[List[str]] = None,
+ ground_truth_fields: Optional[List[str]] = None,
+ prediction_fields: Optional[List[str]] = None,
+) -> schema.ModelMonitoringSchema:
+ """Transforms the pandas schema to model monitoring schema."""
+ ground_truth_fields_list = list()
+ prediction_fields_list = list()
+ feature_fields_list = list()
+ pandas_integer_types = ["integer", "Int32", "Int64", "UInt32", "UInt64"]
+ pandas_string_types = [
+ "string",
+ "bytes",
+ "date",
+ "time",
+ "datetime64",
+ "datetime",
+ "mixed-integer",
+ "inteval",
+ "Interval",
+ ]
+ pandas_float_types = [
+ "floating",
+ "decimal",
+ "mixed-integer-float",
+ "Float32",
+ "Float64",
+ ]
+ for field in dataset:
+ infer_type = dataset[field]
+ if infer_type in pandas_string_types:
+ data_type = "string"
+ elif infer_type in pandas_integer_types:
+ data_type = "integer"
+ elif infer_type in pandas_float_types:
+ data_type = "float"
+ elif infer_type == "boolean":
+ data_type = "boolean"
+ elif infer_type == "categorical" or infer_type == "category":
+ data_type = "categorical"
+ else:
+ raise ValueError(f"Unsupported data type: {infer_type}")
+ if ground_truth_fields and field in ground_truth_fields:
+ ground_truth_fields_list.append(
+ schema.FieldSchema(name=field, data_type=data_type, repeated=False)
+ )
+ elif prediction_fields and field in prediction_fields:
+ prediction_fields_list.append(
+ schema.FieldSchema(name=field, data_type=data_type, repeated=False)
+ )
+ elif (feature_fields and field in feature_fields) or not feature_fields:
+ feature_fields_list.append(
+ schema.FieldSchema(name=field, data_type=data_type, repeated=False)
+ )
+ return schema.ModelMonitoringSchema(
+ ground_truth_fields=ground_truth_fields_list
+ if ground_truth_fields
+ else None,
+ prediction_fields=prediction_fields_list if prediction_fields else None,
+ feature_fields=feature_fields_list,
+ )
+
+
+def _transform_field_schema(
+ field_schema: gca_model_monitor_compat.ModelMonitoringSchema.FieldSchema,
+) -> Dict[str, Any]:
+ result = dict()
+ result["name"] = field_schema.name
+ result["data_type"] = field_schema.data_type
+ result["repeated"] = field_schema.repeated
+ return result
+
+
+def _get_schedule_name(schedule_name: str) -> str:
+ if schedule_name:
+ client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ )
+ if client.parse_schedule_path(schedule_name):
+ return schedule_name
+ elif re.match("^{}$".format("[0-9]{0,127}"), schedule_name):
+ return client.schedule_path(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ schedule=schedule_name,
+ )
+ else:
+ raise ValueError(
+ "schedule name must be of the format"
+ " `projects/{project}/locations/{location}/schedules/{schedule}` or"
+ " `{schedule}`"
+ )
+ return schedule_name
+
+
+def _get_model_monitoring_job_name(
+ model_monitoring_job_name: str,
+ model_monitor_name: str,
+) -> str:
+ if model_monitoring_job_name:
+ client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ )
+ if client.parse_model_monitoring_job_path(model_monitoring_job_name):
+ return model_monitoring_job_name
+ elif re.match("^{}$".format("[0-9]{0,127}"), model_monitoring_job_name):
+ model_monitor_name = model_monitor_name.split("/")[-1]
+ return client.model_monitoring_job_path(
+ project=initializer.global_config.project,
+ location=initializer.global_config.location,
+ model_monitor=model_monitor_name,
+ model_monitoring_job=model_monitoring_job_name,
+ )
+ else:
+ raise ValueError(
+ "model monitoring job name must be of the format"
+ " `projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}`"
+ " or `{model_monitoring_job}`"
+ )
+ return model_monitoring_job_name
+
+
+@dataclasses.dataclass
+class MetricsSearchResponse:
+ """MetricsSearchResponse represents a response of the search metrics request.
+
+ Attributes:
+ monitoring_stats (List[model_monitoring_stats.ModelMonitoringStats]):
+ Stats retrieved for requested objectives.
+ next_page_token (str): The page token that can be used by the next call.
+ """
+
+ next_page_token: str
+ _search_metrics_response: Any
+ monitoring_stats: List[model_monitoring_stats.ModelMonitoringStats] = (
+ dataclasses.field(default_factory=list)
+ )
+
+ @property
+ def raw_search_metrics_response(
+ self,
+ ) -> model_monitoring_service.SearchModelMonitoringStatsResponse:
+ """Raw search metrics response."""
+ return self._search_metrics_response
+
+
+# TODO: b/307946658 - Return a dict or a new dataclass for search_alert
+@dataclasses.dataclass
+class AlertsSearchResponse:
+ """AlertsSearchResponse represents a response of the search alerts request.
+
+ Attributes:
+ next_page_token (str): The page token that can be used by the next call.
+ model_monitoring_alerts
+ (List[model_monitoring_alert.ModelMonitoringAlert]): Alerts retrieved
+ for requested objectives.
+ total_alerts (int): Total number of alerts retrieved for requested
+ objectives.
+ """
+
+ next_page_token: str
+ _search_alerts_response: Any
+ total_alerts: int
+ model_monitoring_alerts: List[model_monitoring_alert.ModelMonitoringAlert] = (
+ dataclasses.field(default_factory=list)
+ )
+
+ @property
+ def raw_search_alerts_response(
+ self,
+ ) -> model_monitoring_service.SearchModelMonitoringAlertsResponse:
+ """Raw search metrics response."""
+ return self._search_alerts_response
+
+
+@dataclasses.dataclass
+class ListJobsResponse:
+ """ListJobsResponse represents a response of the list jobs request.
+
+ Attributes:
+ list_jobs (List[model_monitoring_job.ModelMonitoringJob]): Jobs retrieved
+ for request.
+ next_page_token (str): The page token that can be used by the next call.
+ """
+
+ next_page_token: str
+ _list_jobs_response: Any
+ list_jobs: List[gca_model_monitoring_job_compat.ModelMonitoringJob] = (
+ dataclasses.field(default_factory=list)
+ )
+
+ @property
+ def raw_list_jobs_response(
+ self,
+ ) -> model_monitoring_service.ListModelMonitoringJobsResponse:
+ """Raw list jobs response."""
+ return self._list_jobs_response
+
+
+@dataclasses.dataclass
+class ListSchedulesResponse:
+ """ListSchedulesResponse represents a response of the list jobs request.
+
+ Attributes:
+ list_schedules (List[schedule.Schedule]): Jobs retrieved for request.
+ next_page_token (str): The page token that can be used by the next call.
+ """
+
+ next_page_token: str
+ _list_schedules_response: Any
+ list_schedules: List[gca_schedule.Schedule] = dataclasses.field(
+ default_factory=list
+ )
+
+ @property
+ def raw_list_schedules_response(
+ self,
+ ) -> gca_schedule_service.ListSchedulesResponse:
+ """Raw list jobs response."""
+ return self._list_schedules_response
+
+
+class ModelMonitor(base.VertexAiResourceNounWithFutureManager):
+ """Initializer for ModelMonitor.
+
+ Args:
+ model_monitor_name (str): Required. A fully-qualified model monitor
+ resource name or model monitor ID.
+ Example: "projects/123/locations/us-central1/modelMonitors/456" or
+ "456" when project and location are initialized or passed.
+ project (str): Required. Project to retrieve model monitor from. If not
+ set, project set in aiplatform.init will be used.
+ location (str): Required. Location to retrieve model monitor from. If not
+ set, location set in aiplatform.init will be used.
+ credentials (auth_credentials.Credentials): Optional. Custom credentials
+ to use to retrieve this model monitor. Overrides credentials set in
+ aiplatform.init.
+ """
+
+ client_class = utils.ModelMonitoringClientWithOverride
+ _resource_noun = "modelMonitors"
+ _getter_method = "get_model_monitor"
+ _list_method = "list_model_monitors"
+ _delete_method = "delete_model_monitor"
+ _parse_resource_name_method = "parse_model_monitor_path"
+ _format_resource_name_method = "model_monitor_path"
+
+ def __init__(
+ self,
+ model_monitor_name: str,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=model_monitor_name,
+ )
+ self._gca_resource = self._get_gca_resource(
+ resource_name=model_monitor_name
+ )
+
+ @classmethod
+ def create(
+ cls,
+ model_name: str,
+ model_version_id: str,
+ training_dataset: Optional[objective.MonitoringInput] = None,
+ display_name: Optional[str] = None,
+ model_monitoring_schema: Optional[schema.ModelMonitoringSchema] = None,
+ tabular_objective_spec: Optional[objective.TabularObjective] = None,
+ output_spec: Optional[output.OutputSpec] = None,
+ notification_spec: Optional[notification.NotificationSpec] = None,
+ explanation_spec: Optional[explanation.ExplanationSpec] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ model_monitor_id: Optional[str] = None,
+ ) -> "ModelMonitor":
+ """Creates a new ModelMonitor.
+
+ Args:
+ model_name (str): Required. A model resource name as model monitoring
+ target.
+ Format: ``projects/{project}/locations/{location}/models/{model}``
+ model_version_id (str): Required. Model version id.
+ training_dataset (objective.MonitoringInput): Optional. Training dataset
+ used to train the model. It can serve as a baseline dataset to
+ identify changes in production.
+ display_name (str): Optional. The user-defined name of the ModelMonitor.
+ The name can be up to 128 characters long and can comprise any UTF-8
+ character. Display name of the ModelMonitor.
+ model_monitoring_schema (schema.ModelMonitoringSchema): Required for
+ most models, but optional for Gemini Enterprise Agent Platform AutoML
+ Tables unless the schema information is not available. The Monitoring
+ Schema specifies the model's features, prediction outputs and ground
+ truth properties. It is used to extract pertinent data from the
+ dataset and to process features based on their properties. Make sure
+ that the schema aligns with your dataset, if it does not, Gemini
+ Enterprise Agent Platform will be unable to extract data form the
+ dataset.
+ tabular_objective_spec (objective.TabularObjective): Optional. The
+ default tabular monitoring objective spec for the model monitor. It
+ can be overriden in the ModelMonitoringJob objective spec.
+ output_spec (output.OutputSpec): Optional. The default monitoring
+ metrics/logs export spec, it can be overriden in the
+ ModelMonitoringJob output spec. If not specified, a default Google
+ Cloud Storage bucket will be created under your project.
+ notification_spec (notification.NotificationSpec): Optional. The default
+ notification spec for monitoring result. It can be overriden in the
+ ModelMonitoringJob notification spec.
+ explanation_spec (explanation.ExplanationSpec): Optional. The default
+ explanation spec for feature attribution monitoring. It can be
+ overriden in the ModelMonitoringJob explanation spec.
+ project (str): Optional. Project to retrieve model monitor from. If not
+ set, project set in aiplatform.init will be used.
+ location (str): Optional. Location to retrieve model monitor from. If
+ not set, location set in aiplatform.init will be used.
+ credentials (auth_credentials.Credentials): Optional. Custom credentials
+ to use to create this model monitor. Overrides credentials set in
+ aiplatform.init.
+ model_monitor_id (str): Optional. The unique ID of the model monitor,
+ which will become the final component of the model monitor resource
+ name. If not specified, it will be generated by Gemini Enterprise
+ Agent Platform.
+
+ Returns:
+ ModelMonitor: The model monitor that was created.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=cls.client_class,
+ credentials=credentials,
+ location_override=location,
+ )
+
+ if display_name:
+ utils.validate_display_name(display_name)
+ else:
+ display_name = cls._generate_display_name()
+
+ project = project or initializer.global_config.project
+ location = location or initializer.global_config.location
+
+ user_monitoring_target = gca_model_monitor_compat.ModelMonitor.ModelMonitoringTarget(
+ vertex_model=gca_model_monitor_compat.ModelMonitor.ModelMonitoringTarget.VertexModelSource(
+ model=model_name, model_version_id=model_version_id
+ )
+ )
+
+ operation_future = api_client.create_model_monitor(
+ request=model_monitoring_service.CreateModelMonitorRequest(
+ parent=initializer.global_config.common_location_path(
+ project=project, location=location
+ ),
+ model_monitor=gca_model_monitor_compat.ModelMonitor(
+ display_name=display_name,
+ model_monitoring_target=user_monitoring_target,
+ training_dataset=(
+ training_dataset._as_proto() if training_dataset else None
+ ),
+ model_monitoring_schema=(
+ model_monitoring_schema._as_proto()
+ if model_monitoring_schema
+ else None
+ ),
+ tabular_objective=(
+ tabular_objective_spec._as_proto()
+ if tabular_objective_spec
+ else None
+ ),
+ notification_spec=(
+ notification_spec._as_proto() if notification_spec else None
+ ),
+ output_spec=output_spec._as_proto() if output_spec else None,
+ explanation_spec=explanation_spec,
+ ),
+ model_monitor_id=model_monitor_id,
+ ),
+ )
+ _LOGGER.log_create_with_lro(cls, operation_future)
+ created_model_monitor = operation_future.result(timeout=None)
+ _LOGGER.log_create_complete(cls, created_model_monitor, "model_monitor")
+ self = cls._construct_sdk_resource_from_gapic(
+ gapic_resource=created_model_monitor,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+ model_monitor_id = self._gca_resource.name.split("/")[-1]
+ _LOGGER.info(
+ f"https://console.cloud.google.com/vertex-ai/model-monitoring/locations/{location}/model-monitors/{model_monitor_id}?project={project}"
+ )
+ return self
+
+ def update(
+ self,
+ display_name: Optional[str] = None,
+ training_dataset: Optional[objective.MonitoringInput] = None,
+ model_monitoring_schema: Optional[schema.ModelMonitoringSchema] = None,
+ tabular_objective_spec: Optional[objective.TabularObjective] = None,
+ output_spec: Optional[output.OutputSpec] = None,
+ notification_spec: Optional[notification.NotificationSpec] = None,
+ explanation_spec: Optional[explanation.ExplanationSpec] = None,
+ ) -> "ModelMonitor":
+ """Updates an existing ModelMonitor.
+
+ Args:
+ display_name (str): Optional. The user-defined name of the ModelMonitor.
+ The name can be up to 128 characters long and can comprise any UTF-8
+ character. Display name of the ModelMonitor.
+ training_dataset (objective.MonitoringInput): Optional. Training dataset
+ used to train the model. It can serve as a baseline dataset to
+ identify changes in production.
+ model_monitoring_schema (schema.ModelMonitoringSchema): Optional. The
+ Monitoring Schema specifies the model's features, prediction outputs
+ and ground truth properties. It is used to extract pertinent data from
+ the dataset and to process features based on their properties. Make
+ sure that the schema aligns with your dataset, if it does not, Gemini
+ Enterprise Agent Platform will be unable to extract data form the
+ dataset.
+ tabular_objective_spec (objective.TabularObjective): Optional. The
+ default tabular monitoring objective spec for the model monitor. It
+ can be overriden in the ModelMonitoringJob objective spec.
+ output_spec (output.OutputSpec): Optional. The default monitoring
+ metrics/logs export spec, it can be overriden in the
+ ModelMonitoringJob output spec.
+ notification_spec (notification.NotificationSpec): Optional. The default
+ notification spec for monitoring result. It can be overriden in the
+ ModelMonitoringJob notification spec.
+ explanation_spec (explanation.ExplanationSpec): Optional. The default
+ explanation spec for feature attribution monitoring. It can be
+ overriden in the ModelMonitoringJob explanation spec.
+
+ Returns:
+ ModelMonitor: The updated model monitor.
+ """
+ self._sync_gca_resource()
+ current_monitor = copy.deepcopy(self._gca_resource)
+ update_mask: List[str] = []
+ if display_name is not None:
+ update_mask.append("display_name")
+ current_monitor.display_name = display_name
+ if training_dataset is not None:
+ update_mask.append("training_dataset")
+ current_monitor.training_dataset = training_dataset._as_proto()
+ if model_monitoring_schema is not None:
+ update_mask.append("model_monitoring_schema")
+ current_monitor.model_monitoring_schema = (
+ model_monitoring_schema._as_proto()
+ )
+ if tabular_objective_spec is not None:
+ update_mask.append("tabular_objective")
+ current_monitor.tabular_objective = tabular_objective_spec._as_proto()
+ if output_spec is not None:
+ update_mask.append("output_spec")
+ current_monitor.output_spec = output_spec._as_proto()
+ if notification_spec is not None:
+ update_mask.append("notification_spec")
+ current_monitor.notification_spec = notification_spec._as_proto()
+ if explanation_spec is not None:
+ update_mask.append("explanation_spec")
+ current_monitor.explanation_spec = explanation_spec
+ lro = self.api_client.update_model_monitor(
+ model_monitor=current_monitor,
+ update_mask=field_mask_pb2.FieldMask(paths=update_mask),
+ )
+ self._gca_resource = lro.result()
+ return self
+
+ @base.optional_sync()
+ def delete(self, force: bool = False, sync: bool = True) -> None:
+ """Force delete the model monitor.
+
+ Args:
+ force (bool): Required. If force is set to True, all schedules on this
+ ModelMonitor will be deleted first. Default is False.
+ sync (bool): Whether to execute this method synchronously. If False,
+ this method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future has
+ completed. Default is True.
+ """
+ _LOGGER.log_action_start_against_resource("Deleting", "", self)
+ lro = self.api_client.delete_model_monitor(
+ request=model_monitoring_service.DeleteModelMonitorRequest(
+ name=self._gca_resource.name, force=force
+ )
+ )
+ _LOGGER.log_action_started_against_resource_with_lro(
+ "Delete", "", self.__class__, lro
+ )
+ _LOGGER.log_action_completed_against_resource("deleted.", "", self)
+
+ def create_schedule(
+ self,
+ cron: str,
+ target_dataset: objective.MonitoringInput,
+ display_name: Optional[str] = None,
+ model_monitoring_job_display_name: Optional[str] = None,
+ start_time: Optional[timestamp_pb2.Timestamp] = None,
+ end_time: Optional[timestamp_pb2.Timestamp] = None,
+ tabular_objective_spec: Optional[objective.TabularObjective] = None,
+ baseline_dataset: Optional[objective.MonitoringInput] = None,
+ output_spec: Optional[output.OutputSpec] = None,
+ notification_spec: Optional[notification.NotificationSpec] = None,
+ explanation_spec: Optional[explanation.ExplanationSpec] = None,
+ ) -> "gca_schedule.Schedule":
+ """Creates a new Scheduled run for model monitoring job.
+
+ Args:
+ cron (str): Required. Cron schedule (https://en.wikipedia.org/wiki/Cron)
+ to launch scheduled runs. To explicitly set a timezone to the cron
+ tab, apply a prefix in the cron tab: "CRON_TZ=${IANA_TIME_ZONE}" or
+ "TZ=${IANA_TIME_ZONE}". The ${IANA_TIME_ZONE} may only be a valid
+ string from IANA time zone database. For example,
+ "CRON_TZ=America/New_York 1 * * * *", or "TZ=America/New_York 1 * * *
+ *".
+ target_dataset (objective.MonitoringInput): Required. The target dataset
+ for analysis.
+ display_name (str): Optional. The user-defined name of the Schedule. The
+ name can be up to 128 characters long and can be consist of any UTF-8
+ characters. Display name of the Schedule.
+ model_monitoring_job_display_name (str): Optional. The user-defined name
+ of the ModelMonitoringJob. The name can be up to 128 characters long
+ and can be consist of any UTF-8 characters. Display name of the
+ ModelMonitoringJob.
+ start_time (timestamp_pb2.Timestamp): Optional. Timestamp after which
+ the first run can be scheduled. Default to Schedule create time if not
+ specified.
+ end_time (timestamp_pb2.Timestamp): Optional. Timestamp after which no
+ new runs can be scheduled. If specified, The schedule will be
+ completed when the end_time is reached. If not specified, new runs
+ will keep getting scheduled until this Schedule is paused or deleted.
+ Already scheduled runs will be allowed to complete. Unset if not
+ specified.
+ tabular_objective_spec (objective.TabularObjective): Optional. The
+ tabular monitoring objective spec. If not set, the default tabular
+ objective spec in ModelMonitor will be used. You must either set here
+ or set the default one in the ModelMonitor.
+ baseline_dataset (objective.MonitoringInput): Optional. The baseline
+ dataset for monitoring job. If not set, the training dataset in
+ ModelMonitor will be used as baseline dataset.
+ output_spec (output.OutputSpec): Optional. The monitoring metrics/logs
+ export spec. If not set, will use the default output_spec defined in
+ ModelMonitor.
+ notification_spec (notification.NotificationSpec): Optional. The
+ notification spec for monitoring result. If not set, will use the
+ default notification_spec defined in ModelMonitor.
+ explanation_spec (explanation.ExplanationSpec): Optional. The
+ explanation spec for feature attribution monitoring. If not set, will
+ use the default explanation_spec defined in ModelMonitor.
+
+ Returns:
+ Schedule: The created schedule.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+
+ model_monitor_name = utils.full_resource_name(
+ resource_name=self._gca_resource.name,
+ resource_noun=self._resource_noun,
+ parse_resource_name_method=self._parse_resource_name,
+ format_resource_name_method=self._format_resource_name,
+ project=self.project,
+ location=self.location,
+ )
+
+ schedule_request = gca_schedule_service.CreateScheduleRequest(
+ parent=initializer.global_config.common_location_path(
+ project=self.project, location=self.location
+ ),
+ schedule=gca_schedule.Schedule(
+ display_name=display_name,
+ start_time=start_time,
+ end_time=end_time,
+ cron=cron,
+ create_model_monitoring_job_request=model_monitoring_service.CreateModelMonitoringJobRequest(
+ parent=model_monitor_name,
+ model_monitoring_job=gca_model_monitoring_job_compat.ModelMonitoringJob(
+ display_name=model_monitoring_job_display_name,
+ model_monitoring_spec=model_monitoring_spec.ModelMonitoringSpec(
+ objective_spec=model_monitoring_spec.ModelMonitoringObjectiveSpec(
+ tabular_objective=(
+ tabular_objective_spec._as_proto()
+ if tabular_objective_spec
+ else self._gca_resource.tabular_objective
+ ),
+ target_dataset=target_dataset._as_proto(),
+ baseline_dataset=(
+ baseline_dataset._as_proto()
+ if baseline_dataset
+ else self._gca_resource.training_dataset
+ ),
+ explanation_spec=(
+ explanation_spec
+ if explanation_spec
+ else self._gca_resource.explanation_spec
+ ),
+ ),
+ output_spec=(
+ output_spec._as_proto()
+ if output_spec
+ else self._gca_resource.output_spec
+ ),
+ notification_spec=(
+ notification_spec._as_proto()
+ if notification_spec
+ else self._gca_resource.notification_spec
+ ),
+ ),
+ ),
+ ),
+ max_concurrent_run_count=1,
+ ),
+ )
+ created_schedule = api_client.select_version("v1beta1").create_schedule(
+ request=schedule_request
+ )
+ _LOGGER.log_create_complete(
+ gca_schedule.Schedule, created_schedule, "schedule"
+ )
+ return created_schedule
+
+ def update_schedule(
+ self,
+ schedule_name: str,
+ display_name: Optional[str] = None,
+ model_monitoring_job_display_name: Optional[str] = None,
+ cron: Optional[str] = None,
+ baseline_dataset: Optional[objective.MonitoringInput] = None,
+ target_dataset: Optional[objective.MonitoringInput] = None,
+ tabular_objective_spec: Optional[objective.TabularObjective] = None,
+ output_spec: Optional[output.OutputSpec] = None,
+ notification_spec: Optional[notification.NotificationSpec] = None,
+ explanation_spec: Optional[explanation.ExplanationSpec] = None,
+ end_time: Optional[timestamp_pb2.Timestamp] = None,
+ ) -> "gca_schedule.Schedule":
+ """Updates an existing Schedule.
+
+ Args:
+ schedule_name (str): Required. The resource name of schedule that needs
+ to be updated.
+ Format:
+ ``projects/{project}/locations/{location}/schedules/{schedule}``
+ or ``{schedule}``
+ display_name (str): Optional. The user-defined name of the Schedule. The
+ name can be up to 128 characters long and can be consist of any UTF-8
+ characters. Display name of the Schedule.
+ model_monitoring_job_display_name (str): Optional. The user-defined
+ display name of the ModelMonitoringJob that needs to be updated.
+ cron (str): Optional. Cron schedule (https://en.wikipedia.org/wiki/Cron)
+ to launch scheduled runs. To explicitly set a timezone to the cron
+ tab, apply a prefix in the cron tab: "CRON_TZ=${IANA_TIME_ZONE}" or
+ "TZ=${IANA_TIME_ZONE}". The ${IANA_TIME_ZONE} may only be a valid
+ string from IANA time zone database. For example,
+ "CRON_TZ=America/New_York 1 * * * *", or "TZ=America/New_York 1 * * *
+ *".
+ baseline_dataset (objective.MonitoringInput): Optional. The baseline
+ dataset for monitoring job.
+ target_dataset (objective.MonitoringInput): Optional. The target dataset
+ for analysis.
+ tabular_objective_spec (objective.TabularObjective): Optional. The
+ tabular monitoring objective spec.
+ output_spec (output.OutputSpec): Optional. The monitoring metrics/logs
+ export spec.
+ notification_spec (notification.NotificationSpec): Optional. The
+ notification spec for monitoring result.
+ explanation_spec (explanation.ExplanationSpec): Optional. The
+ explanation spec for feature attribution monitoring.
+ end_time (timestamp_pb2.Timestamp): Optional. Timestamp after which no
+ new runs can be scheduled.
+
+ Returns:
+ Schedule: The updated schedule.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+
+ model_monitor_name = utils.full_resource_name(
+ resource_name=self._gca_resource.name,
+ resource_noun=self._resource_noun,
+ parse_resource_name_method=self._parse_resource_name,
+ format_resource_name_method=self._format_resource_name,
+ project=self.project,
+ location=self.location,
+ )
+ schedule_name = _get_schedule_name(schedule_name)
+ current_schedule = copy.deepcopy(
+ self.get_schedule(schedule_name=schedule_name)
+ )
+ update_mask = []
+ if display_name is not None:
+ update_mask.append("display_name")
+ current_schedule.display_name = display_name
+ if cron is not None:
+ update_mask.append("cron")
+ current_schedule.cron = cron
+ if end_time is not None:
+ update_mask.append("end_time")
+ current_schedule.end_time = end_time
+ current_job_request = current_schedule.create_model_monitoring_job_request
+ current_spec = (
+ current_job_request.model_monitoring_job.model_monitoring_spec
+ )
+ if (
+ tabular_objective_spec is not None
+ or output_spec is not None
+ or notification_spec is not None
+ or model_monitoring_job_display_name is not None
+ or baseline_dataset is not None
+ or target_dataset is not None
+ ):
+ update_mask.append("create_model_monitoring_job_request")
+ updated_model_monitoring_spec = model_monitoring_spec.ModelMonitoringSpec(
+ objective_spec=model_monitoring_spec.ModelMonitoringObjectiveSpec(
+ tabular_objective=(
+ tabular_objective_spec._as_proto()
+ if tabular_objective_spec
+ else current_spec.objective_spec.tabular_objective
+ ),
+ baseline_dataset=(
+ baseline_dataset._as_proto()
+ if baseline_dataset
+ else current_spec.objective_spec.baseline
+ ),
+ target_dataset=(
+ target_dataset._as_proto()
+ if target_dataset
+ else current_spec.objective_spec.target
+ ),
+ explanation_spec=(
+ explanation_spec
+ if explanation_spec
+ else current_spec.objective_spec.explanation_spec
+ ),
+ ),
+ output_spec=(
+ output_spec._as_proto()
+ if output_spec
+ else current_spec.output_spec
+ ),
+ notification_spec=(
+ notification_spec._as_proto()
+ if notification_spec
+ else current_spec.notification_spec
+ ),
+ )
+ current_schedule.create_model_monitoring_job_request = model_monitoring_service.CreateModelMonitoringJobRequest(
+ parent=model_monitor_name,
+ model_monitoring_job=gca_model_monitoring_job_compat.ModelMonitoringJob(
+ display_name=(
+ model_monitoring_job_display_name
+ if model_monitoring_job_display_name
+ else current_job_request.model_monitoring_job.display_name
+ ),
+ model_monitoring_spec=updated_model_monitoring_spec,
+ ),
+ )
+ return api_client.select_version("v1beta1").update_schedule(
+ schedule=current_schedule,
+ update_mask=field_mask_pb2.FieldMask(paths=update_mask),
+ )
+
+ def delete_schedule(self, schedule_name: str) -> None:
+ """Deletes an existing Schedule.
+
+ Args:
+ schedule_name (str): Required. The resource name of schedule that needs
+ to be deleted.
+ Format:
+ ``projects/{project}/locations/{location}/schedules/{schedule}``
+ or ``{schedule}``
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ schedule_name = _get_schedule_name(schedule_name)
+ return api_client.select_version("v1beta1").delete_schedule(
+ name=schedule_name
+ )
+
+ def pause_schedule(self, schedule_name: str) -> None:
+ """Pauses an existing Schedule.
+
+ Args:
+ schedule_name (str): Required. The resource name of schedule that needs
+ to be paused.
+ Format:
+ ``projects/{project}/locations/{location}/schedules/{schedule}``
+ or ``{schedule}``
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ schedule_name = _get_schedule_name(schedule_name)
+ return api_client.select_version("v1beta1").pause_schedule(
+ name=schedule_name
+ )
+
+ def resume_schedule(self, schedule_name: str) -> None:
+ """Resumes an existing Schedule.
+
+ Args:
+ schedule_name (str): Required. The resource name of schedule that needs
+ to be resumed.
+ Format:
+ ``projects/{project}/locations/{location}/schedules/{schedule}``
+ or ``{schedule}``
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ schedule_name = _get_schedule_name(schedule_name)
+ return api_client.select_version("v1beta1").resume_schedule(
+ name=schedule_name
+ )
+
+ def get_schedule(self, schedule_name: str) -> "gca_schedule.Schedule":
+ """Gets an existing Schedule.
+
+ Args:
+ schedule_name (str): Required. The resource name of schedule that needs
+ to be fetched.
+ Format:
+ ``projects/{project}/locations/{location}/schedules/{schedule}``
+ or ``{schedule}``
+
+ Returns:
+ Schedule: The schedule requested.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ schedule_name = _get_schedule_name(schedule_name)
+ return api_client.select_version("v1beta1").get_schedule(name=schedule_name)
+
+ def list_schedules(
+ self,
+ filter: Optional[str] = None,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+ ) -> "ListSchedulesResponse.list_schedules":
+ """List Schedules.
+
+ Args:
+ filter (str): Optional. Lists the Schedules that match the filter
+ expression. The following fields are supported: - ``display_name``:
+ Supports ``=``, ``!=`` comparisons, and ``:`` wildcard. - ``state``:
+ Supports ``=`` and ``!=`` comparisons. - ``request``: Supports
+ existence of the check. (e.g.
+ ``create_pipeline_job_request:*`` --> Schedule has
+ create_pipeline_job_request). - ``create_time``: Supports ``=``,
+ ``!=``, ``<``, ``>``, ``<=``, and ``>=`` comparisons. Values must be
+ in RFC 3339 format. - ``start_time``: Supports ``=``, ``!=``, ``<``,
+ ``>``, ``<=``, and ``>=`` comparisons. Values must be in RFC 3339
+ format. - ``end_time``: Supports ``=``, ``!=``, ``<``, ``>``, ``<=``,
+ ``>=`` comparisons and ``:*`` existence check. Values must be in RFC
+ 3339 format. - ``next_run_time``: Supports ``=``, ``!=``, ``<``,
+ ``>``, ``<=``, and ``>=`` comparisons. Values must be in RFC 3339
+ format. Filter expressions can be combined together using logical
+ operators (``NOT``, ``AND`` & ``OR``). The syntax to define filter
+ expression is based on https://google.aip.dev/160.
+ page_size (int): Optional. The standard page list size.
+ page_token (str): Optional. A page token received from a previous call.
+
+ Returns:
+ MetricsSearchResponse: The model monitoring stats results.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ScheduleClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+
+ filter = (
+ f"{filter} AND"
+ f" create_model_monitoring_job_request.parent={self._gca_resource.name}"
+ if filter
+ else f"create_model_monitoring_job_request.parent={self._gca_resource.name}"
+ )
+ list_schedules_response = (
+ api_client.select_version("v1beta1")
+ .list_schedules(
+ request=gca_schedule_service.ListSchedulesRequest(
+ parent=f"projects/{self.project}/locations/{self.location}",
+ filter=filter,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ )
+ ._response
+ )
+ return ListSchedulesResponse(
+ list_schedules=list_schedules_response.schedules,
+ next_page_token=list_schedules_response.next_page_token,
+ _list_schedules_response=list_schedules_response,
+ ).list_schedules
+
+ def run(
+ self,
+ target_dataset: objective.MonitoringInput,
+ display_name: Optional[str] = None,
+ model_monitoring_job_id: Optional[str] = None,
+ sync: Optional[bool] = False,
+ tabular_objective_spec: Optional[objective.TabularObjective] = None,
+ baseline_dataset: Optional[objective.MonitoringInput] = None,
+ output_spec: Optional[output.OutputSpec] = None,
+ notification_spec: Optional[notification.NotificationSpec] = None,
+ explanation_spec: Optional[explanation.ExplanationSpec] = None,
+ ) -> "ModelMonitoringJob":
+ """Creates a new ModelMonitoringJob.
+
+ Args:
+ target_dataset (objective.MonitoringInput): Required. The target dataset
+ for analysis.
+ display_name (str): Optional. The user-defined name of the
+ ModelMonitoringJob. The name can be up to 128 characters long and can
+ comprise any UTF-8 character. Display name of the ModelMonitoringJob.
+ model_monitoring_job_id (str): Optional. The unique ID of the model
+ monitoring job run, which will become the final component of the model
+ monitoring job resource name. The maximum length is 63 characters, and
+ valid characters are /^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/. If not
+ specified, it will be generated by Gemini Enterprise Agent Platform.
+ sync (bool): Whether to execute this method synchronously. If False,
+ this method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future has
+ completed. Default is False.
+ tabular_objective_spec (objective.TabularObjective): Optional. The
+ tabular monitoring objective spec for the model monitoring job.
+ baseline_dataset (objective.MonitoringInput): Optional. The baseline
+ dataset for monitoring job. If not set, the training dataset in
+ ModelMonitor will be used as baseline dataset.
+ output_spec (output.OutputSpec): Optional. The monitoring metrics/logs
+ export spec. If not set, will use the default output_spec defined in
+ ModelMonitor.
+ notification_spec (notification.NotificationSpec): Optional. The
+ notification spec for monitoring result. If not set, will use the
+ default notification_spec defined in ModelMonitor.
+ explanation_config (explanation.ExplanationSpec): Optional. The
+ explanation spec for feature attribution monitoring. If not set, will
+ use the default explanation_spec defined in ModelMonitor.
+
+ Returns:
+ ModelMonitoringJob: The model monitoring job that was created.
+ """
+ model_monitor_name = utils.full_resource_name(
+ resource_name=self._gca_resource.name,
+ resource_noun=self._resource_noun,
+ parse_resource_name_method=self._parse_resource_name,
+ format_resource_name_method=self._format_resource_name,
+ project=self.project,
+ location=self.location,
+ )
+
+ return ModelMonitoringJob.create(
+ model_monitor_name=model_monitor_name,
+ project=self.project,
+ location=self.location,
+ credentials=self.credentials,
+ display_name=display_name,
+ target_dataset=target_dataset,
+ baseline_dataset=baseline_dataset,
+ model_monitoring_job_id=model_monitoring_job_id,
+ tabular_objective_spec=tabular_objective_spec,
+ output_spec=output_spec,
+ notification_spec=notification_spec,
+ explanation_spec=explanation_spec,
+ sync=sync,
+ )
+
+ def search_metrics(
+ self,
+ stats_name: Optional[str] = None,
+ objective_type: Optional[str] = None,
+ model_monitoring_job_name: Optional[str] = None,
+ schedule_name: Optional[str] = None,
+ algorithm: Optional[str] = None,
+ start_time: Optional[timestamp_pb2.Timestamp] = None,
+ end_time: Optional[timestamp_pb2.Timestamp] = None,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+ ) -> "MetricsSearchResponse.monitoring_stats":
+ """Search ModelMonitoringStats.
+
+ Args:
+ stats_name (str): Optional. The stats name filter for the search, if not
+ set, all stats will be returned. For tabular model it's the feature
+ name.
+ objective_type (str): Optional. One of the supported monitoring
+ objectives: `raw-feature-drift` `prediction-output-drift`
+ `feature-attribution`
+ model_monitoring_job_name (str): Optional. The resource name of a
+ particular model monitoring job that the user wants to search metrics
+ result from.
+ Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}``
+ schedule_name (str): Optional. The resource name of a particular model
+ monitoring schedule that the user wants to search metrics result from.
+ Format:
+ ``projects/{project}/locations/{location}/schedules/{schedule}``
+ algorithm (str): Optional. The algorithm type filter for the search, eg:
+ jensen_shannon_divergence, l_infinity.
+ start_time (timestamp_pb2.Timestamp): Optional. Inclusive start of the
+ time interval for which results should be returned.
+ end_time (timestamp_pb2.Timestamp): Optional. Exclusive end of the time
+ interval for which results should be returned.
+ page_size (int): Optional. The standard page list size.
+ page_token (str): Optional. A page token received from a previous call.
+
+ Returns:
+ MetricsSearchResponse: The model monitoring stats results.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+
+ user_time_interval = (
+ interval_pb2.Interval(start_time=start_time, end_time=end_time)
+ if start_time or end_time
+ else None
+ )
+ model_monitoring_stats_response = api_client.search_model_monitoring_stats(
+ request=model_monitoring_service.SearchModelMonitoringStatsRequest(
+ model_monitor=self._gca_resource.name,
+ stats_filter=model_monitoring_stats.SearchModelMonitoringStatsFilter(
+ tabular_stats_filter=model_monitoring_stats.SearchModelMonitoringStatsFilter.TabularStatsFilter(
+ stats_name=stats_name,
+ objective_type=objective_type,
+ model_monitoring_job=model_monitoring_job_name,
+ model_monitoring_schedule=schedule_name,
+ algorithm=algorithm,
+ ),
+ ),
+ time_interval=user_time_interval,
+ page_size=page_size,
+ page_token=page_token,
+ ),
+ )._response
+ return MetricsSearchResponse(
+ monitoring_stats=model_monitoring_stats_response.monitoring_stats,
+ next_page_token=model_monitoring_stats_response.next_page_token,
+ _search_metrics_response=model_monitoring_stats_response,
+ ).monitoring_stats
+
+ def search_alerts(
+ self,
+ stats_name: Optional[str] = None,
+ objective_type: Optional[str] = None,
+ model_monitoring_job_name: Optional[str] = None,
+ start_time: Optional[timestamp_pb2.Timestamp] = None,
+ end_time: Optional[timestamp_pb2.Timestamp] = None,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Search ModelMonitoringAlerts.
+
+ Args:
+ stats_name (str): Optional. The stats name filter for the search, if not
+ set, all stats will be returned. For tabular models, provide the name
+ of the feature to return alerts from.
+ objective_type (str): Optional. Return alerts from one of the supported
+ monitoring
+ objectives: `raw-feature-drift` `prediction-output-drift`
+ `feature-attribution`
+ model_monitoring_job_name (str): Optional. The resource name of a
+ particular model monitoring job that the user wants to search metrics
+ result from.
+ Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}``
+ start_time (timestamp_pb2.Timestamp): Optional. Inclusive start of the
+ time interval for which alerts should be returned.
+ end_time (timestamp_pb2.Timestamp): Optional. Exclusive end of the time
+ interval for which alerts should be returned.
+ page_size (int): Optional. The standard page list size.
+ page_token (str): Optional. A page token received from a previous call.
+
+ Returns:
+ AlertsSearchResponse: The model monitoring alerts results.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+
+ user_time_interval = (
+ interval_pb2.Interval(start_time=start_time, end_time=end_time)
+ if start_time or end_time
+ else None
+ )
+ model_monitoring_alerts_response = (
+ api_client.search_model_monitoring_alerts(
+ request=model_monitoring_service.SearchModelMonitoringAlertsRequest(
+ model_monitor=self._gca_resource.name,
+ stats_name=stats_name,
+ objective_type=objective_type,
+ model_monitoring_job=model_monitoring_job_name,
+ alert_time_interval=user_time_interval,
+ page_size=page_size,
+ page_token=page_token,
+ ),
+ )._response
+ )
+ alert_response = AlertsSearchResponse(
+ model_monitoring_alerts=model_monitoring_alerts_response.model_monitoring_alerts,
+ next_page_token=model_monitoring_alerts_response.next_page_token,
+ total_alerts=model_monitoring_alerts_response.total_number_alerts,
+ _search_alerts_response=model_monitoring_alerts_response,
+ )
+ return {
+ "total_number_alerts": alert_response.total_alerts,
+ "model_monitoring_alerts": alert_response.model_monitoring_alerts,
+ }
+
+ def list_jobs(
+ self,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+ ) -> "ListJobsResponse.list_jobs":
+ """List ModelMonitoringJobs.
+
+ Args:
+ page_size (int): Optional. The standard page list size.
+ page_token (str): Optional. A page token received from a previous call.
+
+ Returns:
+ ListJobsResponse.list_jobs: The list model monitoring jobs responses.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+
+ model_monitor_name = utils.full_resource_name(
+ resource_name=self._gca_resource.name,
+ resource_noun=self._resource_noun,
+ parse_resource_name_method=self._parse_resource_name,
+ format_resource_name_method=self._format_resource_name,
+ project=self.project,
+ location=self.location,
+ )
+
+ list_jobs_response = api_client.list_model_monitoring_jobs(
+ request=model_monitoring_service.ListModelMonitoringJobsRequest(
+ parent=model_monitor_name,
+ page_size=page_size,
+ page_token=page_token,
+ )
+ )._response
+ return ListJobsResponse(
+ list_jobs=list_jobs_response.model_monitoring_jobs,
+ next_page_token=list_jobs_response.next_page_token,
+ _list_jobs_response=list_jobs_response,
+ ).list_jobs
+
+ def delete_model_monitoring_job(self, model_monitoring_job_name: str) -> None:
+ """Delete a model monitoring job.
+
+ Args:
+ model_monitoring_job_name (str): Required. The resource name of the
+ model monitoring job that needs to be deleted.
+ Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}``
+ or ``{model_monitoring_job}``
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ job_resource_name = _get_model_monitoring_job_name(
+ model_monitoring_job_name, self._gca_resource.name
+ )
+ api_client.delete_model_monitoring_job(name=job_resource_name)
+
+ def get_model_monitoring_job(
+ self, model_monitoring_job_name: str
+ ) -> "ModelMonitoringJob":
+ """Get the specified ModelMonitoringJob.
+
+ Args:
+ model_monitoring_job_name (str): Required. The resource name of the
+ ModelMonitoringJob that is needed.
+ Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}``
+ or ``{model_monitoring_job}``
+
+ Returns:
+ ModelMonitoringJob: The model monitoring job get.
+ """
+ self.wait()
+ job_resource_name = _get_model_monitoring_job_name(
+ model_monitoring_job_name, self._gca_resource.name
+ )
+ return ModelMonitoringJob(
+ model_monitoring_job_name=job_resource_name,
+ project=self.project,
+ location=self.location,
+ credentials=self.credentials,
+ )
+
+ def show_feature_drift_stats(self, model_monitoring_job_name: str) -> None:
+ """The method to visualize the feature drift result from a model monitoring job as a histogram chart and a table.
+
+ Args:
+ model_monitoring_job_name (str): Required. The resource name of model
+ monitoring job to show the drift stats from.
+ Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}``
+ or ``{model_monitoring_job}``
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ if model_monitoring_job_name.startswith("projects/"):
+ job_resource_name = model_monitoring_job_name
+ job_id = model_monitoring_job_name.split("/")[-1]
+ else:
+ job_resource_name = f"{self._gca_resource.name}/modelMonitoringJobs/{model_monitoring_job_name}"
+ job_id = model_monitoring_job_name
+ job = api_client.get_model_monitoring_job(name=job_resource_name)
+ output_directory = (
+ job.model_monitoring_spec.output_spec.gcs_base_directory.output_uri_prefix
+ )
+ target_output, baseline_output = _feature_drift_stats_output_path(
+ output_directory, job_id
+ )
+ anomoaly_output = _feature_drift_anomalies_output_path(
+ output_directory, job_id
+ )
+ _visualize_stats(baseline_output, target_output)
+ _visualize_anomalies(anomoaly_output)
+
+ def get_schema(self) -> gca_model_monitor_compat.ModelMonitoringSchema:
+ """Get the schema of the model monitor."""
+ self._sync_gca_resource()
+ return self._gca_resource.model_monitoring_schema
+
+ def show_output_drift_stats(self, model_monitoring_job_name: str) -> None:
+ """The method to visualize the prediction output drift result from a model monitoring job as a histogram chart and a table.
+
+ Args:
+ model_monitoring_job_name (str): Required. The resource name of model
+ monitoring job to show the drift stats from.
+ Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}``
+ or ``{model_monitoring_job}``
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ if model_monitoring_job_name.startswith("projects/"):
+ job_resource_name = model_monitoring_job_name
+ job_id = model_monitoring_job_name.split("/")[-1]
+ else:
+ job_resource_name = f"{self._gca_resource.name}/modelMonitoringJobs/{model_monitoring_job_name}"
+ job_id = model_monitoring_job_name
+ job = api_client.get_model_monitoring_job(name=job_resource_name)
+ output_directory = (
+ job.model_monitoring_spec.output_spec.gcs_base_directory.output_uri_prefix
+ )
+ target_output, baseline_output = _prediction_output_stats_output_path(
+ output_directory, job_id
+ )
+ anomoaly_output = _prediction_output_anomalies_output_path(
+ output_directory, job_id
+ )
+ _visualize_stats(baseline_output, target_output)
+ _visualize_anomalies(anomoaly_output)
+
+ def show_feature_attribution_drift_stats(
+ self, model_monitoring_job_name: str
+ ) -> None:
+ """The method to visualize the feature attribution drift result from a model monitoring job as a histogram chart and a table.
+
+ Args:
+ model_monitoring_job_name (str): Required. The resource name of model
+ monitoring job to show the feature attribution drift stats from.
+ Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}/modelMonitoringJobs/{model_monitoring_job}``
+ or ``{model_monitoring_job}``
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=utils.ModelMonitoringClientWithOverride,
+ credentials=self.credentials,
+ location_override=self.location,
+ )
+ if model_monitoring_job_name.startswith("projects/"):
+ job_resource_name = model_monitoring_job_name
+ job_id = model_monitoring_job_name.split("/")[-1]
+ else:
+ job_resource_name = f"{self._gca_resource.name}/modelMonitoringJobs/{model_monitoring_job_name}"
+ job_id = model_monitoring_job_name
+ job = api_client.get_model_monitoring_job(name=job_resource_name)
+ output_directory = (
+ job.model_monitoring_spec.output_spec.gcs_base_directory.output_uri_prefix
+ )
+ target_stats_output = _feature_attribution_target_stats_output_path(
+ output_directory, job_id
+ )
+ baseline_stats_output = _feature_attribution_baseline_stats_output_path(
+ output_directory, job_id
+ )
+ _visualize_feature_attribution(baseline_stats_output)
+ _visualize_feature_attribution(target_stats_output)
+
+
+class ModelMonitoringJob(base.VertexAiStatefulResource):
+ r"""Initializer for ModelMonitoringJob.
+
+ Example Usage:
+
+ my_monitoring_job = aiplatform.ModelMonitoringJob(
+ model_monitoring_job_name='projects/123/locations/us-central1/modelMonitors/\
+ my_model_monitor_id/modelMonitoringJobs/my_monitoring_job_id'
+ )
+ or
+ my_monitoring_job = aiplatform.aiplatform.ModelMonitoringJob(
+ model_monitoring_job_name='my_monitoring_job_id',
+ model_monitor_id='my_model_monitor_id',
+ )
+ Args:
+ model_monitoring_job_name (str):
+ Required. The resource name for the Model Monitoring Job if
+ provided alone, or the model monitoring job id if provided with
+ model_monitor_id.
+ model_monitor_id (str):
+ Optional. The model monitor id depends on the way of initializing
+ ModelMonitoringJob.
+ project (str):
+ Required. Project to retrieve endpoint from. If not set, project
+ set in aiplatform.init will be used.
+ location (str):
+ Required. Location to retrieve endpoint from. If not set,
+ location set in aiplatform.init will be used.
+ credentials (auth_credentials.Credentials):
+ Optional. Custom credentials to use to init model monitoring job.
+ Overrides credentials set in aiplatform.init.
+ """
+
+ client_class = utils.ModelMonitoringClientWithOverride
+ _resource_noun = "modelMonitoringJobs"
+ _getter_method = "get_model_monitoring_job"
+ _list_method = "list_model_monitoring_jobs"
+ _delete_method = "delete_model_monitoring_job"
+ _parse_resource_name_method = "parse_model_monitoring_job_path"
+ _format_resource_name_method = "model_monitoring_job_path"
+
+ # Required by the done() method
+ _valid_done_states = _JOB_COMPLETE_STATES
+
+ def __init__(
+ self,
+ model_monitoring_job_name: str,
+ model_monitor_id: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ):
+ super().__init__(
+ project=project,
+ location=location,
+ credentials=credentials,
+ resource_name=model_monitoring_job_name,
+ )
+ self._gca_resource = self._get_gca_resource(
+ resource_name=model_monitoring_job_name,
+ parent_resource_name_fields=(
+ {ModelMonitor._resource_noun: model_monitor_id}
+ if model_monitor_id
+ else model_monitor_id
+ ),
+ )
+
+ @property
+ def state(self) -> gca_job_state.JobState:
+ """Fetch Job again and return the current JobState.
+
+ Returns:
+ state (job_state.JobState):
+ Enum that describes the state of a Model Monitoring Job.
+ """
+
+ # Fetch the Job again for most up-to-date job state
+ self._sync_gca_resource()
+ return self._gca_resource.state
+
+ @classmethod
+ def _construct_sdk_resource_from_gapic(
+ cls,
+ gapic_resource: proto.Message,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> "ModelMonitoringJob":
+ """Given a GAPIC ModelMonitoringJob object, return the SDK representation.
+
+ Args:
+ gapic_resource (proto.Message): A GAPIC representation of a
+ ModelMonitoringJob resource, usually retrieved by a get_* or in a
+ list_* API call.
+ project (str): Optional. Project to construct ModelMonitoringJob object
+ from. If not set, project set in aiplatform.init will be used.
+ location (str): Optional. Location to construct ModelMonitoringJob
+ object from. If not set, location set in aiplatform.init will be used.
+ credentials (auth_credentials.Credentials): Optional. Custom credentials
+ to use to construct ModelMonitoringJob. Overrides credentials set in
+ aiplatform.init.
+
+ Returns:
+ ModelMonitoringJob: The model monitoring job that was created.
+ """
+ model_monitoring_job = super()._construct_sdk_resource_from_gapic(
+ gapic_resource=gapic_resource,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ return model_monitoring_job
+
+ def _block_until_complete(self) -> None:
+ """Helper method to block and check on job until complete."""
+ # Used these numbers so failures surface fast
+ wait = _JOB_WAIT_TIME # start at five seconds
+ log_wait = _LOG_WAIT_TIME
+ max_wait = _MAX_WAIT_TIME # 5 minute wait
+ multiplier = _WAIT_TIME_MULTIPLIER # scale wait by 2 every iteration
+
+ previous_time = time.time()
+ while not self.done():
+ current_time = time.time()
+ if current_time - previous_time >= log_wait:
+ _LOGGER.info(
+ "%s %s current state:\n%s"
+ % (
+ self.__class__.__name__,
+ self._gca_resource.name,
+ self._gca_resource.state,
+ )
+ )
+ log_wait = min(log_wait * multiplier, max_wait)
+ previous_time = current_time
+ time.sleep(wait)
+
+ # Error is only populated when the job state is JOB_STATE_FAILED.
+ if self._gca_resource.state in _JOB_ERROR_STATES:
+ raise RuntimeError(
+ "Job failed with:\n%s" % self._gca_resource.job_execution_detail.error
+ )
+ elif (
+ self._gca_resource.state
+ == gca_job_state.JobState.JOB_STATE_PARTIALLY_SUCCEEDED
+ ):
+ obj_status_msg = ""
+ for (
+ obj,
+ status,
+ ) in self._gca_resource.job_execution_detail.objective_status.items():
+ obj_status_msg += f"{obj}: {status}\n"
+ _LOGGER.warning("Job partially succeeded:\n%s" % obj_status_msg)
+ else:
+ _LOGGER.log_action_completed_against_resource("run", "completed", self)
+
+ @classmethod
+ def create(
+ cls,
+ model_monitor_name: str = None,
+ target_dataset: objective.MonitoringInput = None,
+ display_name: Optional[str] = None,
+ model_monitoring_job_id: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ baseline_dataset: Optional[objective.MonitoringInput] = None,
+ tabular_objective_spec: Optional[objective.TabularObjective] = None,
+ output_spec: Optional[output.OutputSpec] = None,
+ notification_spec: Optional[notification.NotificationSpec] = None,
+ explanation_spec: Optional[explanation.ExplanationSpec] = None,
+ sync: bool = False,
+ ) -> "ModelMonitoringJob":
+ """Creates a new ModelMonitoringJob.
+
+ Args:
+ model_monitor_name (str): Required. The parent model monitor resource
+ name. Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}``
+ target_dataset (objective.MonitoringInput): Required. The target dataset
+ for analysis.
+ display_name (str): Optional. The user-defined name of the
+ ModelMonitoringJob. The name can be up to 128 characters long and can
+ comprise any UTF-8 character.
+ model_monitoring_job_id (str): Optional. The unique ID of the model
+ monitoring job run, which will become the final component of the model
+ monitoring job resource name. The maximum length is 63 characters, and
+ valid characters are /^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/. If not
+ specified, it will be generated by Gemini Enterprise Agent Platform.
+ project (str): Optional. Project to retrieve endpoint from. If not set,
+ project set in aiplatform.init will be used.
+ location (str): Optional. Location to retrieve endpoint from. If not
+ set, location set in aiplatform.init will be used.
+ credentials (auth_credentials.Credentials): Optional. Custom credentials
+ to use to create model monitoring job. Overrides credentials set in
+ aiplatform.init.
+ baseline_dataset (objective.MonitoringInput): Optional. The baseline
+ dataset for monitoring job. If not set, the training dataset in
+ ModelMonitor will be used as baseline dataset.
+ output_spec (output.OutputSpec): Optional. The monitoring metrics/logs
+ export spec. If not set, will use the default output_spec defined in
+ ModelMonitor.
+ notification_spec (notification.NotificationSpec): Optional. The
+ notification spec for monitoring result. If not set, will use the
+ default notification_spec defined in ModelMonitor.
+ explanation_spec (explanation.ExplanationSpec): Optional. The
+ explanation spec for feature attribution monitoring. If not set, will
+ use the default explanation_spec defined in ModelMonitor.
+ sync (bool): Required. Whether to execute this method synchronously. If
+ False, this method will be executed in concurrent Future and any
+ downstream object will be immediately returned and synced when the
+ Future has completed. Default is False.
+
+ Returns:
+ ModelMonitoringJob: The model monitoring job that was created.
+ """
+ if not display_name:
+ display_name = cls._generate_display_name()
+ utils.validate_display_name(display_name)
+
+ project = project or initializer.global_config.project
+ location = location or initializer.global_config.location
+
+ parent = utils.full_resource_name(
+ resource_name=model_monitor_name,
+ resource_noun=ModelMonitor._resource_noun,
+ parse_resource_name_method=ModelMonitor._parse_resource_name,
+ format_resource_name_method=ModelMonitor._format_resource_name,
+ project=project,
+ location=location,
+ )
+
+ gca_model_monitoring_job = gca_model_monitoring_job_compat.ModelMonitoringJob(
+ display_name=display_name,
+ model_monitoring_spec=model_monitoring_spec.ModelMonitoringSpec(
+ objective_spec=model_monitoring_spec.ModelMonitoringObjectiveSpec(
+ tabular_objective=(
+ tabular_objective_spec._as_proto()
+ if tabular_objective_spec
+ else None
+ ),
+ baseline_dataset=(
+ baseline_dataset._as_proto() if baseline_dataset else None
+ ),
+ target_dataset=(
+ target_dataset._as_proto() if target_dataset else None
+ ),
+ explanation_spec=explanation_spec,
+ ),
+ output_spec=(output_spec._as_proto() if output_spec else None),
+ notification_spec=(
+ notification_spec._as_proto() if notification_spec else None
+ ),
+ ),
+ )
+ empty_model_monitoring_job = cls._empty_constructor(
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+ return cls._submit_job(
+ model_monitor_name=parent,
+ empty_model_monitoring_job=empty_model_monitoring_job,
+ gca_model_monitoring_job=gca_model_monitoring_job,
+ model_monitoring_job_id=model_monitoring_job_id,
+ sync=sync,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+
+ @classmethod
+ @base.optional_sync(return_input_arg="empty_model_monitoring_job")
+ def _submit_job(
+ cls,
+ model_monitor_name: str,
+ empty_model_monitoring_job: "ModelMonitoringJob",
+ gca_model_monitoring_job: gca_model_monitoring_job_compat.ModelMonitoringJob,
+ sync: bool = False,
+ model_monitoring_job_id: Optional[str] = None,
+ project: Optional[str] = None,
+ location: Optional[str] = None,
+ credentials: Optional[auth_credentials.Credentials] = None,
+ ) -> "ModelMonitoringJob":
+ """Submits a new ModelMonitoringJob.
+
+ Args:
+ model_monitor_name (str): Required. The parent model monitor resource
+ name. Format:
+ ``projects/{project}/locations/{location}/modelMonitors/{model_monitor}``
+ empty_model_monitoring_job (ModelMonitoringJob): Required.
+ ModelMonitoringJob without _gca_resource populated.
+ gca_model_monitoring_job
+ (gca_model_monitoring_job_compat.ModelMonitoringJob): Required. a
+ model monitoring job proto for creating a model monitoring job on
+ Gemini Enterprise Agent Platform.
+ sync (bool): Required. Whether to execute this method synchronously. If
+ False, this method will be executed in concurrent Future and any
+ downstream object will be immediately returned and synced when the
+ Future has completed. Default is False.
+ model_monitoring_job_id (str): Optional. The unique ID of the model
+ monitoring job run, which will become the final component of the model
+ monitoring job resource name. The maximum length is 63 characters, and
+ valid characters are /^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/. If not
+ specified, it will be generated by Gemini Enterprise Agent Platform.
+ project (str): Optional. Project to retrieve endpoint from. If not set,
+ project set in aiplatform.init will be used.
+ location (str): Optional. Location to retrieve endpoint from. If not
+ set, location set in aiplatform.init will be used.
+ credentials (auth_credentials.Credentials): Optional. Custom credentials
+ to use to create model monitoring job. Overrides credentials set in
+ aiplatform.init.
+
+ Returns:
+ ModelMonitoringJob: The model monitoring job that was created.
+ """
+ api_client = initializer.global_config.create_client(
+ client_class=cls.client_class,
+ credentials=credentials,
+ location_override=location,
+ )
+ _LOGGER.log_create_with_lro(cls)
+ created_model_monitoring_job = api_client.create_model_monitoring_job(
+ request=model_monitoring_service.CreateModelMonitoringJobRequest(
+ parent=model_monitor_name,
+ model_monitoring_job=gca_model_monitoring_job,
+ model_monitoring_job_id=model_monitoring_job_id,
+ ),
+ )
+ empty_model_monitoring_job._gca_resource = created_model_monitoring_job
+ model_monitoring_job = cls._construct_sdk_resource_from_gapic(
+ gapic_resource=created_model_monitoring_job,
+ project=project,
+ location=location,
+ credentials=credentials,
+ )
+ _LOGGER.log_create_complete(
+ cls, created_model_monitoring_job, "model_monitoring_job"
+ )
+ model_monitoring_job._block_until_complete()
+ return model_monitoring_job
+
+ def delete(self) -> None:
+ """Deletes an Model Monitoring Job."""
+ self.api_client.delete_model_monitoring_job(name=self._gca_resource.name)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5fd1c3a73dee97065ce383f2c2176d03ee53c5d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__init__.py
@@ -0,0 +1,44 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from agentplatform.resources.preview.ml_monitoring.spec.notification import (
+ NotificationSpec,
+)
+from agentplatform.resources.preview.ml_monitoring.spec.objective import (
+ DataDriftSpec,
+ FeatureAttributionSpec,
+ MonitoringInput,
+ ObjectiveSpec,
+ TabularObjective,
+)
+from agentplatform.resources.preview.ml_monitoring.spec.output import (
+ OutputSpec,
+)
+from agentplatform.resources.preview.ml_monitoring.spec.schema import (
+ FieldSchema,
+ ModelMonitoringSchema,
+)
+
+__all__ = (
+ "NotificationSpec",
+ "OutputSpec",
+ "ObjectiveSpec",
+ "FeatureAttributionSpec",
+ "DataDriftSpec",
+ "MonitoringInput",
+ "TabularObjective",
+ "FieldSchema",
+ "ModelMonitoringSchema",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb7088b99fcc83961f44b2c99000e73157b45823
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/notification.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/notification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59912ee1cece2f433f66cf22d8b32d6252aa0865
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/notification.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/objective.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/objective.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b5cc4f2fd941e92d1d9088bc97d474702334155
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/objective.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/output.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/output.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64e27ef59fec8c98423143810eb45003769511db
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/output.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..905bf5cc38e52d5f08f24ec8bef20a817c06191b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/__pycache__/schema.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/notification.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/notification.py
new file mode 100644
index 0000000000000000000000000000000000000000..46972141a3610e6bd8ea7fdad77432d7324a361f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/notification.py
@@ -0,0 +1,72 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Optional, List
+from google.cloud.aiplatform.compat.types import (
+ model_monitoring_spec_v1beta1 as model_monitoring_spec,
+)
+
+
+class NotificationSpec:
+ """Initializer for NotificationSpec.
+
+ Args:
+ user_emails (List[str]):
+ Optional. The email addresses to send the alert to.
+ notification_channels (List[str]):
+ Optional. The notification channels to send the alert to.
+ Format: ``projects/{project}/notificationChannels/{channel}``
+ enable_cloud_logging (bool):
+ Optional. If dump the anomalies to Cloud Logging. The anomalies will
+ be put to json payload. This can be further sinked to Pub/Sub or any
+ other services supported by Cloud Logging.
+ """
+
+ def __init__(
+ self,
+ user_emails: Optional[List[str]] = None,
+ notification_channels: Optional[List[str]] = None,
+ enable_cloud_logging: Optional[bool] = False,
+ ):
+ self.user_emails = user_emails
+ self.notification_channels = notification_channels
+ self.enable_cloud_logging = enable_cloud_logging
+
+ def _as_proto(self) -> model_monitoring_spec.ModelMonitoringNotificationSpec:
+ """Converts ModelMonitoringNotificationSpec to a proto message.
+
+ Returns:
+ The GAPIC representation of the notification alert config.
+ """
+ user_email_config = None
+ if self.user_emails is not None:
+ user_email_config = (
+ model_monitoring_spec.ModelMonitoringNotificationSpec.EmailConfig(
+ user_emails=self.user_emails
+ )
+ )
+ user_notification_channel_config = []
+ if self.notification_channels:
+ for notification_channel in self.notification_channels:
+ user_notification_channel_config.append(
+ model_monitoring_spec.ModelMonitoringNotificationSpec.NotificationChannelConfig(
+ notification_channel=notification_channel
+ )
+ )
+ return model_monitoring_spec.ModelMonitoringNotificationSpec(
+ email_config=user_email_config,
+ notification_channel_configs=user_notification_channel_config,
+ enable_cloud_logging=self.enable_cloud_logging,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/objective.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/objective.py
new file mode 100644
index 0000000000000000000000000000000000000000..089512141d283506f5dee065341855ba1b4adefb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/objective.py
@@ -0,0 +1,498 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Dict, List, Optional
+
+from google.cloud.aiplatform.compat.types import (
+ explanation_v1beta1 as explanation,
+ machine_resources_v1beta1 as machine_resources,
+ model_monitoring_alert_v1beta1 as model_monitoring_alert,
+ model_monitoring_spec_v1beta1 as model_monitoring_spec,
+)
+
+from google.protobuf import timestamp_pb2
+from google.type import interval_pb2
+
+TF_RECORD = "tf-record"
+CSV = "csv"
+JSONL = "jsonl"
+JENSEN_SHANNON_DIVERGENCE = "jensen_shannon_divergence"
+L_INFINITY = "l_infinity"
+SUPPORTED_NUMERIC_METRICS = [JENSEN_SHANNON_DIVERGENCE]
+SUPPORTED_CATEGORICAL_METRICS = [JENSEN_SHANNON_DIVERGENCE, L_INFINITY]
+
+
+class DataDriftSpec:
+ """Data drift monitoring spec.
+
+ Data drift measures the distribution distance between the current dataset
+ and a baseline dataset. A typical use case is to detect data drift between
+ the recent production serving dataset and the training dataset, or to
+ compare the recent production dataset with a dataset from a previous period.
+
+ Example:
+ feature_drift_spec=DataDriftSpec(
+ features=["feature1"]
+ categorical_metric_type="l_infinity",
+ numeric_metric_type="jensen_shannon_divergence",
+ default_categorical_alert_threshold=0.01,
+ default_numeric_alert_threshold=0.02,
+ feature_alert_thresholds={"feature1":0.02, "feature2":0.01},
+ )
+
+ Attributes:
+ features (List[str]): Optional. Feature names / Prediction output names
+ interested in monitoring. These should be a subset of the input feature
+ names or prediction output names specified in the monitoring schema. If
+ not specified, all features / prediction outputs outlied in the
+ monitoring schema will be used.
+ categorical_metric_type (str): Optional. Supported metrics type:
+ l_infinity, jensen_shannon_divergence
+ numeric_metric_type (str): Optional. Supported metrics type:
+ jensen_shannon_divergence
+ default_categorical_alert_threshold (float): Optional. Default alert
+ threshold for all the categorical features.
+ default_numeric_alert_threshold (float): Optional. Default alert threshold
+ for all the numeric features.
+ feature_alert_thresholds (Dict[str, float]): Optional. Per feature alert
+ threshold will override default alert threshold.
+ """
+
+ def __init__(
+ self,
+ features: Optional[List[str]] = None,
+ categorical_metric_type: Optional[str] = L_INFINITY,
+ numeric_metric_type: Optional[str] = JENSEN_SHANNON_DIVERGENCE,
+ default_categorical_alert_threshold: Optional[float] = None,
+ default_numeric_alert_threshold: Optional[float] = None,
+ feature_alert_thresholds: Optional[Dict[str, float]] = None,
+ ):
+ self.features = features
+ self.categorical_metric_type = categorical_metric_type
+ self.numeric_metric_type = numeric_metric_type
+ self.default_categorical_alert_threshold = (
+ default_categorical_alert_threshold
+ )
+ self.default_numeric_alert_threshold = default_numeric_alert_threshold
+ self.feature_alert_thresholds = feature_alert_thresholds
+
+ def _as_proto(
+ self,
+ ) -> model_monitoring_spec.ModelMonitoringObjectiveSpec.DataDriftSpec:
+ """Converts DataDriftSpec to a proto message.
+
+ Returns:
+ The GAPIC representation of the data drift spec.
+ """
+ user_default_categorical_alert_threshold = None
+ user_default_numeric_alert_threshold = None
+ user_alert_thresholds = None
+ user_features = None
+ if self.numeric_metric_type not in SUPPORTED_NUMERIC_METRICS:
+ raise ValueError(
+ f"The numeric metric type is not supported {self.numeric_metric_type}"
+ )
+ user_numeric_metric_type = self.numeric_metric_type
+ if self.categorical_metric_type not in SUPPORTED_CATEGORICAL_METRICS:
+ raise ValueError(
+ "The categorical metric type is not supported"
+ f" {self.categorical_metric_type}"
+ )
+ user_categorical_metric_type = self.categorical_metric_type
+ if self.default_categorical_alert_threshold:
+ user_default_categorical_alert_threshold = (
+ model_monitoring_alert.ModelMonitoringAlertCondition(
+ threshold=self.default_categorical_alert_threshold
+ )
+ )
+ if self.default_numeric_alert_threshold:
+ user_default_numeric_alert_threshold = (
+ model_monitoring_alert.ModelMonitoringAlertCondition(
+ threshold=self.default_numeric_alert_threshold
+ )
+ )
+ if self.feature_alert_thresholds:
+ user_alert_thresholds = {}
+ for feature in self.feature_alert_thresholds:
+ user_alert_thresholds.update({
+ feature: model_monitoring_alert.ModelMonitoringAlertCondition(
+ threshold=self.feature_alert_thresholds[feature]
+ )
+ })
+ if self.features:
+ user_features = self.features
+ return model_monitoring_spec.ModelMonitoringObjectiveSpec.DataDriftSpec(
+ default_categorical_alert_condition=user_default_categorical_alert_threshold,
+ default_numeric_alert_condition=user_default_numeric_alert_threshold,
+ categorical_metric_type=user_categorical_metric_type,
+ numeric_metric_type=user_numeric_metric_type,
+ feature_alert_conditions=user_alert_thresholds,
+ features=user_features,
+ )
+
+
+class FeatureAttributionSpec:
+ """Feature attribution spec.
+
+ Example:
+ feature_attribution_spec=FeatureAttributionSpec(
+ features=["feature1"]
+ default_alert_threshold=0.01,
+ feature_alert_thresholds={"feature1":0.02, "feature2":0.01},
+ batch_dedicated_resources=BatchDedicatedResources(
+ starting_replica_count=1,
+ max_replica_count=2,
+ machine_spec=my_machine_spec,
+ ),
+ )
+
+ Attributes:
+ features (List[str]): Optional. Input feature names interested in
+ monitoring. These should be a subset of the input feature names
+ specified in the monitoring schema. If not specified, all features
+ outlied in the monitoring schema will be used.
+ default_alert_threshold (float): Optional. Default alert threshold for all
+ the features.
+ feature_alert_thresholds (Dict[str, float]): Optional. Per feature alert
+ threshold will override default alert threshold.
+ batch_dedicated_resources (machine_resources.BatchDedicatedResources):
+ Optional. The config of resources used by the Model Monitoring during
+ the batch explanation for non-AutoML models. If not set, `n1-standard-2`
+ machine type will be used by default.
+ """
+
+ def __init__(
+ self,
+ features: Optional[List[str]] = None,
+ default_alert_threshold: Optional[float] = None,
+ feature_alert_thresholds: Optional[Dict[str, float]] = None,
+ batch_dedicated_resources: Optional[
+ machine_resources.BatchDedicatedResources
+ ] = None,
+ ):
+ self.features = features
+ self.default_alert_threshold = default_alert_threshold
+ self.feature_alert_thresholds = feature_alert_thresholds
+ self.batch_dedicated_resources = batch_dedicated_resources
+
+ def _as_proto(
+ self,
+ ) -> (
+ model_monitoring_spec.ModelMonitoringObjectiveSpec.FeatureAttributionSpec
+ ):
+ """Converts FeatureAttributionSpec to a proto message.
+
+ Returns:
+ The GAPIC representation of the feature attribution spec.
+ """
+ user_default_alert_threshold = None
+ user_alert_thresholds = None
+ user_features = None
+ if self.default_alert_threshold:
+ user_default_alert_threshold = (
+ model_monitoring_alert.ModelMonitoringAlertCondition(
+ threshold=self.default_alert_threshold
+ )
+ )
+ if self.feature_alert_thresholds:
+ user_alert_thresholds = {}
+ for feature in self.feature_alert_thresholds:
+ user_alert_thresholds.update({
+ feature: model_monitoring_alert.ModelMonitoringAlertCondition(
+ threshold=self.feature_alert_thresholds[feature]
+ )
+ })
+ if self.features:
+ user_features = self.features
+ return model_monitoring_spec.ModelMonitoringObjectiveSpec.FeatureAttributionSpec(
+ default_alert_condition=user_default_alert_threshold,
+ feature_alert_conditions=user_alert_thresholds,
+ features=user_features,
+ batch_explanation_dedicated_resources=self.batch_dedicated_resources,
+ )
+
+
+class MonitoringInput:
+ """Model monitoring data input spec.
+
+ Attributes:
+ vertex_dataset (str): Optional. Resource name of the Gemini Enterprise
+ Agent Platform managed dataset.
+ Format: ``projects/{project}/locations/{location}/datasets/{dataset}``
+ At least one source of dataset should be provided, and if one of the
+ fields is set, no need to set other sources (vertex_dataset,
+ gcs_uri, table_uri, query, batch_prediction_job, endpoints).
+ gcs_uri (str): Optional. Google Cloud Storage URI to the input file(s).
+ May contain wildcards.
+ data_format (str): Optional. Data format of Google Cloud Storage file(s).
+ Should be provided if a gcs_uri is set. Supported formats: "csv",
+ "jsonl", "tf-record"
+ table_uri (str): Optonal. BigQuery URI to a table, up to 2000 characters
+ long. All the columns in the table will be selected. Accepted forms: -
+ BigQuery path. For example: ``bq://projectId.bqDatasetId.bqTableId``.
+ query (str): Optional. Standard SQL for BigQuery to be used instead of the
+ ``table_uri``.
+ timestamp_field (str): Optional. The timestamp field in the dataset. the
+ ``timestamp_field`` must be specified if you'd like to use
+ ``start_time``, ``end_time``, ``offset`` or ``window``. If you use
+ ``query`` to specify the dataset, make sure the ``timestamp_field`` is
+ in the selection fields.
+ batch_prediction_job (str): Optional. Gemini Enterprise Agent Platform
+ Batch Prediction Job resource name.
+ Format:
+ ``projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}``
+ endpoints (List[str]): Optional. List of Gemini Enterprise Agent Platform
+ Endpoint resource names.
+ Format:
+ ``projects/{project}/locations/{location}/endpoints/{endpoint}``
+ start_time (timestamp_pb2.Timestamp): Optional. Inclusive start of the
+ time interval for which results should be returned. Should be set
+ together with ``end_time``.
+ end_time (timestamp_pb2.Timestamp): Optional. Exclusive end of the time
+ interval for which results should be returned. Should be set together
+ with ``start_time`.`
+ offset (str): Optional. Offset is the time difference from the cut-off
+ time. For scheduled jobs, the cut-off time is the scheduled time. For
+ non-scheduled jobs, it's the time when the job was created. Currently we
+ support the following format: 'w|W': Week, 'd|D': Day, 'h|H': Hour E.g.
+ '1h' stands for 1 hour, '2d' stands for 2 days.
+ window (str): Optional. Window refers to the scope of data selected for
+ analysis. It allows you to specify the quantity of data you wish to
+ examine. It refers to the data time window prior to the cut-off time or
+ the cut-off time minus the offset. Currently we support the following
+ format: 'w|W': Week, 'd|D': Day, 'h|H': Hour E.g. '1h' stands for 1
+ hour, '2d' stands for 2 days.
+ """
+
+ def __init__(
+ self,
+ vertex_dataset: Optional[str] = None,
+ gcs_uri: Optional[str] = None,
+ data_format: Optional[str] = None,
+ table_uri: Optional[str] = None,
+ query: Optional[str] = None,
+ timestamp_field: Optional[str] = None,
+ batch_prediction_job: Optional[str] = None,
+ endpoints: Optional[List[str]] = None,
+ start_time: Optional[timestamp_pb2.Timestamp] = None,
+ end_time: Optional[timestamp_pb2.Timestamp] = None,
+ offset: Optional[str] = None,
+ window: Optional[str] = None,
+ ):
+ self.vertex_dataset = vertex_dataset
+ self.gcs_uri = gcs_uri
+ self.data_format = data_format
+ self.table_uri = table_uri
+ self.query = query
+ self.timestamp_field = timestamp_field
+ self.batch_prediction_job = batch_prediction_job
+ self.endpoints = endpoints
+ self.start_time = start_time
+ self.end_time = end_time
+ self.offset = offset
+ self.window = window
+
+ def _as_proto(self) -> model_monitoring_spec.ModelMonitoringInput:
+ """Converts ModelMonitoringInput to a proto message.
+
+ Returns:
+ The GAPIC representation of the model monitoring input.
+ """
+ user_time_interval = None
+ user_time_spec = None
+ if self.offset or self.window:
+ user_time_spec = model_monitoring_spec.ModelMonitoringInput.TimeOffset(
+ offset=self.offset if self.offset else None,
+ window=self.window if self.window else None,
+ )
+ elif self.start_time or self.end_time:
+ user_time_interval = interval_pb2.Interval(
+ start_time=self.start_time if self.start_time else None,
+ end_time=self.end_time if self.end_time else None,
+ )
+ if self.vertex_dataset or self.gcs_uri or self.table_uri or self.query:
+ user_vertex_dataset = None
+ user_gcs_source = None
+ user_bigquery_source = None
+ if self.vertex_dataset:
+ user_vertex_dataset = self.vertex_dataset
+ elif self.gcs_uri:
+ if not self.data_format:
+ raise ValueError("`data_format` must be provided with gcs uri.")
+ if self.data_format == CSV:
+ user_data_format = (
+ model_monitoring_spec.ModelMonitoringInput.ModelMonitoringDataset.ModelMonitoringGcsSource.DataFormat.CSV
+ )
+ elif self.data_format == JSONL:
+ user_data_format = (
+ model_monitoring_spec.ModelMonitoringInput.ModelMonitoringDataset.ModelMonitoringGcsSource.DataFormat.JSONL
+ )
+ elif self.data_format == TF_RECORD:
+ user_data_format = (
+ model_monitoring_spec.ModelMonitoringInput.ModelMonitoringDataset.ModelMonitoringGcsSource.DataFormat.TF_RECORD
+ )
+ else:
+ raise ValueError(
+ (
+ "Unsupported value in data format. `data_format` "
+ "must be one of %s, %s, or %s"
+ )
+ % (TF_RECORD, CSV, JSONL)
+ )
+ user_gcs_source = model_monitoring_spec.ModelMonitoringInput.ModelMonitoringDataset.ModelMonitoringGcsSource(
+ gcs_uri=self.gcs_uri,
+ format_=user_data_format,
+ )
+ elif self.table_uri or self.query:
+ user_bigquery_source = model_monitoring_spec.ModelMonitoringInput.ModelMonitoringDataset.ModelMonitoringBigQuerySource(
+ table_uri=self.table_uri,
+ query=self.query,
+ )
+ else:
+ raise ValueError("At least one source of dataset must be provided.")
+ user_model_monitoring_dataset = (
+ model_monitoring_spec.ModelMonitoringInput.ModelMonitoringDataset(
+ vertex_dataset=user_vertex_dataset,
+ gcs_source=user_gcs_source,
+ bigquery_source=user_bigquery_source,
+ timestamp_field=self.timestamp_field,
+ )
+ )
+ return model_monitoring_spec.ModelMonitoringInput(
+ columnized_dataset=user_model_monitoring_dataset,
+ time_offset=user_time_spec,
+ time_interval=user_time_interval,
+ )
+ elif self.batch_prediction_job:
+ user_batch_prediction_output = (
+ model_monitoring_spec.ModelMonitoringInput.BatchPredictionOutput(
+ batch_prediction_job=self.batch_prediction_job,
+ )
+ )
+ return model_monitoring_spec.ModelMonitoringInput(
+ batch_prediction_output=user_batch_prediction_output,
+ time_offset=user_time_spec,
+ time_interval=user_time_interval,
+ )
+ elif self.endpoints:
+ user_vertex_endpoint_logs = (
+ model_monitoring_spec.ModelMonitoringInput.VertexEndpointLogs(
+ endpoints=self.endpoints,
+ )
+ )
+ return model_monitoring_spec.ModelMonitoringInput(
+ vertex_endpoint_logs=user_vertex_endpoint_logs,
+ time_offset=user_time_spec,
+ time_interval=user_time_interval,
+ )
+ else:
+ raise ValueError("At least one source of dataInput must be provided.")
+
+
+class TabularObjective:
+ """Initializer for TabularObjective.
+
+ Attributes:
+ feature_drift_spec (DataDriftSpec): Optional. Input feature distribution
+ drift monitoring spec.
+ prediction_output_drift_spec (DataDriftSpec): Optional. Prediction output
+ distribution drift monitoring spec.
+ feature_attribution_spec (FeatureAttributionSpec): Optional. Feature
+ attribution monitoring spec.
+ """
+
+ def __init__(
+ self,
+ feature_drift_spec: Optional[DataDriftSpec] = None,
+ prediction_output_drift_spec: Optional[DataDriftSpec] = None,
+ feature_attribution_spec: Optional[FeatureAttributionSpec] = None,
+ ):
+ self.feature_drift_spec = feature_drift_spec
+ self.prediction_output_drift_spec = prediction_output_drift_spec
+ self.feature_attribution_spec = feature_attribution_spec
+
+ def _as_proto(
+ self,
+ ) -> model_monitoring_spec.ModelMonitoringObjectiveSpec.TabularObjective:
+ """Converts TabularObjective to a proto message.
+
+ Returns:
+ The GAPIC representation of the model monitoring tabular objective.
+ """
+ user_feature_drift_spec = None
+ user_prediction_output_drift_spec = None
+ user_feature_attribution_spec = None
+ if self.feature_drift_spec:
+ user_feature_drift_spec = self.feature_drift_spec._as_proto()
+ if self.prediction_output_drift_spec:
+ user_prediction_output_drift_spec = (
+ self.prediction_output_drift_spec._as_proto()
+ )
+ if self.feature_attribution_spec:
+ user_feature_attribution_spec = self.feature_attribution_spec._as_proto()
+ return model_monitoring_spec.ModelMonitoringObjectiveSpec.TabularObjective(
+ feature_drift_spec=user_feature_drift_spec,
+ prediction_output_drift_spec=user_prediction_output_drift_spec,
+ feature_attribution_spec=user_feature_attribution_spec,
+ )
+
+
+class ObjectiveSpec:
+ """Initializer for ObjectiveSpec.
+
+ Args:
+ baseline_dataset (MonitoringInput): Required. Baseline datasets that are
+ used by all the monitoring objectives. It could be the training dataset
+ or production serving dataset from a previous period.
+ target_dataset (MonitoringInput): Required. Target dataset for monitoring
+ analysis, it's used by all the monitoring objectives.
+ tabular_objective (TabularObjective): Optional. The tabular monitoring
+ objective.
+ explanation_spec (explanation.ExplanationSpec): Optional. The explanation
+ spec. This spec is required when the objectives spec includes feature
+ attribution objectives.
+ """
+
+ def __init__(
+ self,
+ baseline_dataset: MonitoringInput,
+ target_dataset: MonitoringInput,
+ tabular_objective: Optional[TabularObjective] = None,
+ explanation_spec: Optional[explanation.ExplanationSpec] = None,
+ ):
+ self.baseline = baseline_dataset
+ self.target = target_dataset
+ self.tabular_objective = tabular_objective
+ self.explanation_spec = explanation_spec
+
+ def _as_proto(self) -> model_monitoring_spec.ModelMonitoringObjectiveSpec:
+ """Converts ModelMonitoringObjectiveSpec to a proto message.
+
+ Returns:
+ The GAPIC representation of the model monitoring objective config.
+ """
+ user_tabular_objective = None
+ if not self.baseline or not self.target:
+ raise ValueError("At least one objective must be provided.")
+ if self.tabular_objective:
+ user_tabular_objective = self.tabular_objective._as_proto()
+ return model_monitoring_spec.ModelMonitoringObjectiveSpec(
+ tabular_objective=user_tabular_objective,
+ explanation_spec=self.explanation_spec
+ if self.explanation_spec
+ else None,
+ target_dataset=self.target._as_proto(),
+ baseline_dataset=self.baseline._as_proto(),
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/output.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/output.py
new file mode 100644
index 0000000000000000000000000000000000000000..0156082e4860a21a579fd66cbd3217b51c32213d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/output.py
@@ -0,0 +1,46 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from google.cloud.aiplatform.compat.types import (
+ io_v1beta1 as io,
+ model_monitoring_spec_v1beta1 as model_monitoring_spec,
+)
+
+
+class OutputSpec:
+ """Initializer for OutputSpec.
+
+ Args:
+ data_source (str):
+ Optional. Google Cloud Storage base folder path for metrics, error
+ logs, etc.
+ """
+
+ def __init__(
+ self,
+ gcs_base_dir: str,
+ ):
+ self.gcs_base_dir = gcs_base_dir
+
+ def _as_proto(self) -> model_monitoring_spec.ModelMonitoringOutputSpec:
+ """Converts ModelMonitoringOutputSpec to a proto message.
+
+ Returns:
+ The GAPIC representation of the notification alert config.
+ """
+ user_gcs_base_dir = io.GcsDestination(output_uri_prefix=self.gcs_base_dir)
+ return model_monitoring_spec.ModelMonitoringOutputSpec(
+ gcs_base_directory=user_gcs_base_dir,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/schema.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..58ed5dcae4f70d266fdafcb56a768f34cb486cd8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/resources/preview/ml_monitoring/spec/schema.py
@@ -0,0 +1,439 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import json
+import logging
+import os
+from typing import Dict, List, MutableSequence, Optional
+from google.cloud import bigquery
+from google.cloud.aiplatform.compat.types import (
+ model_monitor_v1beta1 as model_monitor,
+)
+
+try:
+ import pandas as pd
+except ImportError:
+ pd = None
+try:
+ import tensorflow as tf
+except ImportError:
+ tf = None
+
+
+class FieldSchema:
+ """Field Schema.
+
+ The class identifies the data type of a single feature,
+ which combines together to form the Schema for different fields in
+ ModelMonitoringSchema.
+
+ Attributes:
+ name (str):
+ Required. Field name.
+ data_type (str):
+ Required. Supported data types are: ``float``, ``integer``
+ ``boolean``, ``string``, ``categorical``.
+ repeated (bool):
+ Optional. Describes if the schema field is an array of given data
+ type.
+ """
+
+ def __init__(
+ self,
+ name: str,
+ data_type: str,
+ repeated: Optional[bool] = False,
+ ):
+ self.name = name
+ self.data_type = data_type
+ self.repeated = repeated
+
+ def _as_proto(self) -> model_monitor.ModelMonitoringSchema.FieldSchema:
+ """Converts ModelMonitoringSchema.FieldSchema to a proto message.
+
+ Returns:
+ The GAPIC representation of the model monitoring field schema.
+ """
+ return model_monitor.ModelMonitoringSchema.FieldSchema(
+ name=self.name,
+ data_type=self.data_type,
+ repeated=self.repeated,
+ )
+
+
+class ModelMonitoringSchema:
+ """Initializer for ModelMonitoringSchema.
+
+ Args:
+ feature_fields (MutableSequence[FieldSchema]):
+ Required. Feature names of the model. Gemini Enterprise Agent Platform will try to match
+ the features from your dataset as follows:
+ * For 'csv' files, the header names are required, and we will
+ extract thecorresponding feature values when the header names
+ align with the feature names.
+ * For 'jsonl' files, we will extract the corresponding feature
+ values if the key names match the feature names. Note: Nested
+ features are not supported, so please ensure your features are
+ flattened. Ensure the feature values are scalar or an array of
+ scalars.
+ * For 'bigquery' dataset, we will extract the corresponding feature
+ values if the column names match the feature names.
+ Note: The column type can be a scalar or an array of scalars.
+ STRUCT or JSON types are not supported. You may use SQL queries to
+ select or aggregate the relevant features from your original
+ table. However, ensure that the 'schema' of the query results
+ meets our requirements.
+ * For the Gemini Enterprise Agent Platform Endpoint Request Response Logging table or
+ Gemini Enterprise Agent Platform Batch Prediction Job results. If the prediction
+ instance format is an array, ensure that the sequence in
+ ``feature_fields`` matches the order of features in the prediction
+ instance. We will match the feature with the array in the order
+ specified in ``feature_fields``.
+ prediction_fields (MutableSequence[FieldSchema]):
+ Optional. Prediction output names of the model. The requirements are
+ the same as the ``feature_fields``.
+ For AutoML Tables, the prediction output name presented in schema
+ will be: `predicted_{target_column}`, the `target_column` is the one
+ you specified when you train the model.
+ For Prediction output drift analysis:
+ * AutoML Classification, the distribution of the argmax label will
+ be analyzed.
+ * AutoML Regression, the distribution of the value will be analyzed.
+ ground_truth_fields (MutableSequence[FieldSchema]):
+ Optional. Target /ground truth names of the model.
+ """
+
+ def __init__(
+ self,
+ feature_fields: MutableSequence[FieldSchema],
+ ground_truth_fields: Optional[MutableSequence[FieldSchema]] = None,
+ prediction_fields: Optional[MutableSequence[FieldSchema]] = None,
+ ):
+ self.feature_fields = feature_fields
+ self.prediction_fields = prediction_fields
+ self.ground_truth_fields = ground_truth_fields
+
+ def _as_proto(self) -> model_monitor.ModelMonitoringSchema:
+ """Converts ModelMonitoringSchema to a proto message.
+
+ Returns:
+ The GAPIC representation of the model monitoring schema.
+ """
+ user_feature_fields = list()
+ user_prediction_fields = list()
+ user_ground_truth_fields = list()
+ for field in self.feature_fields:
+ user_feature_fields.append(field._as_proto())
+ if self.prediction_fields:
+ for field in self.prediction_fields:
+ user_prediction_fields.append(field._as_proto())
+ if self.ground_truth_fields:
+ for field in self.ground_truth_fields:
+ user_ground_truth_fields.append(field._as_proto())
+ return model_monitor.ModelMonitoringSchema(
+ feature_fields=user_feature_fields,
+ prediction_fields=(
+ user_prediction_fields if self.prediction_fields else None
+ ),
+ ground_truth_fields=(
+ user_ground_truth_fields if self.ground_truth_fields else None
+ ),
+ )
+
+ def to_json(self, output_dir: Optional[str] = None) -> str:
+ """Transform ModelMonitoringSchema to json format.
+
+ Args:
+ output_dir (str):
+ Optional. The output directory that the transformed json file
+ would be put into.
+ """
+ result = model_monitor.ModelMonitoringSchema.to_json(self._as_proto())
+ if output_dir:
+ result_path = os.path.join(output_dir, "model_monitoring_schema.json")
+ with tf.io.gfile.GFile(result_path, "w") as f:
+ json.dump(result, f)
+ f.close()
+ logging.info("Transformed schema to json file: %s", result_path)
+ return result
+
+
+def _check_duplicate(
+ field: str,
+ feature_fields: Optional[List[str]] = None,
+ ground_truth_fields: Optional[List[str]] = None,
+ prediction_fields: Optional[List[str]] = None,
+) -> bool:
+ """Check if a field appears in two field lists."""
+ feature = True
+ ground_truth = True
+ prediction = True
+ if not feature_fields or field not in feature_fields:
+ feature = False
+ if not ground_truth_fields or field not in ground_truth_fields:
+ ground_truth = False
+ if not prediction_fields or field not in prediction_fields:
+ prediction = False
+ return feature if (feature == ground_truth) else prediction
+
+
+def _transform_schema_pandas(
+ dataset: Dict[str, str],
+ feature_fields: Optional[List[str]] = None,
+ ground_truth_fields: Optional[List[str]] = None,
+ prediction_fields: Optional[List[str]] = None,
+) -> ModelMonitoringSchema:
+ """Transforms the pandas schema to model monitoring schema."""
+ ground_truth_fields_list = list()
+ prediction_fields_list = list()
+ feature_fields_list = list()
+ pandas_integer_types = ["integer", "Int32", "Int64", "UInt32", "UInt64"]
+ pandas_string_types = [
+ "string",
+ "bytes",
+ "date",
+ "time",
+ "datetime64",
+ "datetime",
+ "mixed-integer",
+ "inteval",
+ "Interval",
+ ]
+ pandas_float_types = [
+ "floating",
+ "decimal",
+ "mixed-integer-float",
+ "Float32",
+ "Float64",
+ ]
+ for field in dataset:
+ infer_type = dataset[field]
+ if infer_type in pandas_string_types:
+ data_type = "string"
+ elif infer_type in pandas_integer_types:
+ data_type = "integer"
+ elif infer_type in pandas_float_types:
+ data_type = "float"
+ elif infer_type == "boolean":
+ data_type = "boolean"
+ elif infer_type == "categorical" or infer_type == "category":
+ data_type = "categorical"
+ else:
+ raise ValueError(f"Unsupported data type: {infer_type}")
+ if _check_duplicate(
+ field, feature_fields, ground_truth_fields, prediction_fields
+ ):
+ raise ValueError(f"The field {field} specified in two or more field lists")
+ if ground_truth_fields and field in ground_truth_fields:
+ ground_truth_fields_list.append(
+ FieldSchema(
+ name=field,
+ data_type=data_type,
+ )
+ )
+ elif prediction_fields and field in prediction_fields:
+ prediction_fields_list.append(
+ FieldSchema(
+ name=field,
+ data_type=data_type,
+ )
+ )
+ elif (feature_fields and field in feature_fields) or not feature_fields:
+ feature_fields_list.append(
+ FieldSchema(
+ name=field,
+ data_type=data_type,
+ )
+ )
+ return ModelMonitoringSchema(
+ ground_truth_fields=ground_truth_fields_list if ground_truth_fields else None,
+ prediction_fields=prediction_fields_list if prediction_fields else None,
+ feature_fields=feature_fields_list,
+ )
+
+
+def transform_schema_from_bigquery(
+ feature_fields: Optional[List[str]] = None,
+ ground_truth_fields: Optional[List[str]] = None,
+ prediction_fields: Optional[List[str]] = None,
+ table: Optional[str] = None,
+ query: Optional[str] = None,
+) -> ModelMonitoringSchema:
+ """Transform the existing dataset to ModelMonitoringSchema as model monitor
+ could accept.
+
+ Args:
+ feature_fields (List[str]):
+ Optional. The input feature fields for given dataset.
+ By default all features we find would be the input features.
+ ground_truth_fields (List[str]):
+ Optional. The ground truth fields for given dataset.
+ By default all features we find would be the input features.
+ prediction_fields (List[str]):
+ Optional. The prediction output field for given dataset.
+ By default all features we find would be the input features.
+ table (str):
+ Optional. The BigQuery table uri.
+ query (str):
+ Optional. The BigQuery query.
+ """
+ ground_truth_fields_list = list()
+ prediction_fields_list = list()
+ feature_fields_list = list()
+ bq_string_types = [
+ "STRING",
+ "BYTES",
+ "DATE",
+ "TIME",
+ "GEOGRAPHY",
+ "DATETIME",
+ "JSON",
+ "INTEVAL",
+ "RANGE",
+ ]
+ bq_integer_types = ["INTEGER", "INT64", "TIMESTAMP"]
+ bq_float_types = ["FLOAT", "DOUBLE", "FLOAT64", "NUMERIC", "BIGNUMERIC"]
+ if table:
+ if table.startswith("bq://"):
+ table = table[len("bq://") :]
+ try:
+ client = bigquery.Client()
+ table = client.get_table(table)
+ bq_schema = table.schema
+ except Exception as e:
+ raise ValueError("Failed to get table from bq address provided.") from e
+ elif query:
+ try:
+ client = bigquery.Client()
+ bq_schema = client.query(
+ query=query, job_config=bigquery.job.QueryJobConfig(dry_run=True)
+ ).schema
+ except Exception as e:
+ raise ValueError("Failed to get query from bq address provided.") from e
+ else:
+ raise ValueError("Either table or query must be provided.")
+ for field in bq_schema:
+ if field.field_type in bq_string_types:
+ data_type = "string"
+ elif field.field_type in bq_integer_types:
+ data_type = "integer"
+ elif field.field_type in bq_float_types:
+ data_type = "float"
+ elif field.field_type == "BOOLEAN" or field.field_type == "BOOL":
+ data_type = "boolean"
+ else:
+ raise ValueError(f"Unsupported data type: {field.field_type}")
+ if _check_duplicate(
+ field.name, feature_fields, ground_truth_fields, prediction_fields
+ ):
+ raise ValueError(
+ f"The field {field.name} specified in two or more field lists"
+ )
+ if ground_truth_fields and field.name in ground_truth_fields:
+ ground_truth_fields_list.append(
+ FieldSchema(
+ name=field.name,
+ data_type=data_type,
+ repeated=True if field.mode == "REPEATED" else False,
+ )
+ )
+ elif prediction_fields and field.name in prediction_fields:
+ prediction_fields_list.append(
+ FieldSchema(
+ name=field.name,
+ data_type=data_type,
+ repeated=True if field.mode == "REPEATED" else False,
+ )
+ )
+ elif (feature_fields and field.name in feature_fields) or not feature_fields:
+ feature_fields_list.append(
+ FieldSchema(
+ name=field.name,
+ data_type=data_type,
+ repeated=True if field.mode == "REPEATED" else False,
+ )
+ )
+ return ModelMonitoringSchema(
+ ground_truth_fields=ground_truth_fields_list if ground_truth_fields else None,
+ prediction_fields=prediction_fields_list if prediction_fields else None,
+ feature_fields=feature_fields_list,
+ )
+
+
+def transform_schema_from_csv(
+ file_path: str,
+ feature_fields: Optional[List[str]] = None,
+ ground_truth_fields: Optional[List[str]] = None,
+ prediction_fields: Optional[List[str]] = None,
+) -> ModelMonitoringSchema:
+ """Transform the existing dataset to ModelMonitoringSchema as model monitor could accept.
+
+ Args:
+ file_path (str):
+ Required. The dataset file path.
+ feature_fields (List[str]):
+ Optional. The input feature fields for given dataset.
+ By default all features we find would be the input features.
+ ground_truth_fields (List[str]):
+ Optional. The ground truth fields for given dataset.
+ By default all features we find would be the input features.
+ prediction_fields (List[str]):s
+ Optional. The prediction output field for given dataset.
+ By default all features we find would be the input features.
+ """
+ with tf.io.gfile.GFile(file_path, "r") as f:
+ input_dataset = pd.read_csv(f)
+ dict_dataset = dict()
+ for field in input_dataset.columns:
+ dict_dataset[field] = input_dataset.convert_dtypes().dtypes[field]
+ monitoring_schema = _transform_schema_pandas(
+ dict_dataset, feature_fields, ground_truth_fields, prediction_fields
+ )
+ f.close()
+ return monitoring_schema
+
+
+def transform_schema_from_json(
+ file_path: str,
+ feature_fields: Optional[List[str]] = None,
+ ground_truth_fields: Optional[List[str]] = None,
+ prediction_fields: Optional[List[str]] = None,
+) -> ModelMonitoringSchema:
+ """Transform the existing dataset to ModelMonitoringSchema as model monitor
+ could accept.
+
+ Args:
+ file_path (str):
+ Required. The dataset file path.
+ feature_fields (List[str]):
+ Optional. The input feature fields for given dataset.
+ By default all features we find would be the input features.
+ ground_truth_fields (List[str]):
+ Optional. The ground truth fields for given dataset.
+ By default all features we find would be the input features.
+ prediction_fields (List[str]):
+ Optional. The prediction output field for given dataset.
+ By default all features we find would be the input features.
+ """
+ with tf.io.gfile.GFile(file_path, "r") as f:
+ input_dataset = pd.read_json(f, lines=True)
+ dict_dataset = dict()
+ for field in input_dataset.columns:
+ dict_dataset[field] = input_dataset.convert_dtypes().dtypes[field]
+ monitoring_schema = _transform_schema_pandas(
+ dict_dataset, feature_fields, ground_truth_fields, prediction_fields
+ )
+ f.close()
+ return monitoring_schema
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0845d44172c087880fb343ee85b2b99d23de329c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/_version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6481b9c47ae7edbb3835e99554f85e4b11358c5b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/_version.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/archive.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/archive.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..224253abcbd2f1726aad04c570b7bd14524ad47d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/archive.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/asyn.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/asyn.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91789b58335ff438d9616ef748247976ffca9e91
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/asyn.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/caching.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/caching.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3392ac1ec61190131f4f34b4a076c1e88fec49d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/caching.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/callbacks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/callbacks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d728e96b3f5d936e584edaa4fca11ee63319dc9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/callbacks.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/compression.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/compression.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef9c8f4a670894b72e44d98764a12d2896081725
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/compression.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..425ad0558d8020a8f32d1b4201ab81b660df8e05
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/config.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/conftest.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/conftest.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a8b443142595793dc3cb1a04b435cfc047867bf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/conftest.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/core.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/core.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c3883ab86dd634c2e09ce733bb704eb1e1499cf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/core.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/dircache.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/dircache.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57addf688dca497667f6eafcea0c85fcd7a4b094
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/dircache.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6b196dd8e16f0738d3849cd2eb7b6b3c01448cb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/exceptions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/fuse.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/fuse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02163a6e36986cb0aa63714df10e10fa74e77282
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/fuse.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/generic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/generic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e79833620c167bdd593f2b97f2c865783523d78
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/generic.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/gui.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/gui.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab519358cd004d42031ace4626f2bb6d89f7d2b2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/gui.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/json.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/json.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4189813567ee6e9330c2fb3d848847eb500bf28
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/json.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/mapping.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/mapping.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c46c5879b2034a842ccbc7301f55543a434cba16
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/mapping.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/parquet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/parquet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8524df8bb68dd3673696f87bbb682c1dcc643826
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/parquet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/registry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/registry.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63787f4a9b8e3c3cc2ad1e4ceeef9aa3374ee2a1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/registry.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/transaction.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/transaction.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25c020efb38f77a826698bac9a19bd8e14b7f3c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/transaction.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3c3f2592a9e11d53964ce86d251286748649cdf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4edcf793605a2fa2e871d1acf370aaace3e648be
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/arrow.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/arrow.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7324b65ba45b923850b797d47b26a15ec040490a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/arrow.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..065b089f603af427aa3f1bf6244353a6ab31b62f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..784bec633b1e92c9fca3c572f63a4a0fa191abe7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f313666aba5dc097e48706ce352c328c93d22b6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cached.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cached.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e43685afc0e545f1878f295b1f93fafb2c21066
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/cached.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dask.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dask.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..417ea90092fa812f3da7321f4181cb9da2f5af82
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dask.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/data.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/data.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d29bfc4be95de667a0a0a6f7b7ff2ef3469757f2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/data.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fddb7fd74f7a0df73162af51822ee5028b6804f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76f79df1080e67427a9a349998b1f7792279d0d5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/ftp.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/ftp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2740e14abb119f59a5a0757f10d58a658706d133
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/ftp.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/gist.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/gist.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40b474ba8e05c09035ea5c82de719bc26026ada6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/gist.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/git.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/git.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ecdd5c8f62a566dff1e89874d660dd011f8ba31c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/git.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/github.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/github.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..982dc7db95649fef565697894bab07bec2b2c7d1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/github.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/http.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/http.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df157ec9e6b9eae0ecce68dd340fdb01ad2ab3d2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/http.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..532752a0d18acbbd25e025e68cc2815470d32cf1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3cc1cc19ff5675fa3dd7d4c1aee24bdb218cf38a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5d7f70e1c215ba3d5522ed9292f25d712a2b71b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/local.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/local.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e54ffddf31c75d6fcba714d9ee65ee62eac0a58
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/local.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/memory.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/memory.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..204e27406f72eef55e3ee939198c768fa6c29bca
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/memory.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/reference.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/reference.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33f4a3c740cfa2f324202bc0987897acad976e84
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/reference.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/sftp.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/sftp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d98d73e782da5ce657e8c82cb98b370771a67c7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/sftp.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/smb.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/smb.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f3b295759a97d2d3de362b2a7f97dda2bdec804
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/smb.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/tar.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/tar.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c37d0e28a0cff8ea1d6f497b07a63f819c57ce51
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/tar.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..958252b5385ac59666f428cb48674cda1950a45c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/zip.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/zip.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf46a7bc784c26182d9655b62dd4b62efd7a7196
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/__pycache__/zip.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/arrow.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/arrow.py
new file mode 100644
index 0000000000000000000000000000000000000000..530df901a7225bab4afb9f08d06540bc18e91aef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/arrow.py
@@ -0,0 +1,304 @@
+import errno
+import io
+import os
+import secrets
+import shutil
+from contextlib import suppress
+from functools import cached_property, wraps
+from urllib.parse import parse_qs
+
+from fsspec.spec import AbstractFileSystem
+from fsspec.utils import (
+ get_package_version_without_import,
+ infer_storage_options,
+ mirror_from,
+ tokenize,
+)
+
+
+def wrap_exceptions(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except OSError as exception:
+ if not exception.args:
+ raise
+
+ message, *args = exception.args
+ if isinstance(message, str) and "does not exist" in message:
+ raise FileNotFoundError(errno.ENOENT, message) from exception
+ else:
+ raise
+
+ return wrapper
+
+
+PYARROW_VERSION = None
+
+
+class ArrowFSWrapper(AbstractFileSystem):
+ """FSSpec-compatible wrapper of pyarrow.fs.FileSystem.
+
+ Parameters
+ ----------
+ fs : pyarrow.fs.FileSystem
+
+ """
+
+ root_marker = "/"
+
+ def __init__(self, fs, **kwargs):
+ global PYARROW_VERSION
+ PYARROW_VERSION = get_package_version_without_import("pyarrow")
+ self.fs = fs
+ super().__init__(**kwargs)
+
+ @property
+ def protocol(self):
+ return self.fs.type_name
+
+ @cached_property
+ def fsid(self):
+ return "hdfs_" + tokenize(self.fs.host, self.fs.port)
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ ops = infer_storage_options(path)
+ path = ops["path"]
+ if path.startswith("//"):
+ # special case for "hdfs://path" (without the triple slash)
+ path = path[1:]
+ return path
+
+ def ls(self, path, detail=False, **kwargs):
+ path = self._strip_protocol(path)
+ from pyarrow.fs import FileSelector
+
+ entries = [
+ self._make_entry(entry)
+ for entry in self.fs.get_file_info(FileSelector(path))
+ ]
+ if detail:
+ return entries
+ else:
+ return [entry["name"] for entry in entries]
+
+ def info(self, path, **kwargs):
+ path = self._strip_protocol(path)
+ [info] = self.fs.get_file_info([path])
+ return self._make_entry(info)
+
+ def exists(self, path):
+ path = self._strip_protocol(path)
+ try:
+ self.info(path)
+ except FileNotFoundError:
+ return False
+ else:
+ return True
+
+ def _make_entry(self, info):
+ from pyarrow.fs import FileType
+
+ if info.type is FileType.Directory:
+ kind = "directory"
+ elif info.type is FileType.File:
+ kind = "file"
+ elif info.type is FileType.NotFound:
+ raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path)
+ else:
+ kind = "other"
+
+ return {
+ "name": info.path,
+ "size": info.size,
+ "type": kind,
+ "mtime": info.mtime,
+ }
+
+ @wrap_exceptions
+ def cp_file(self, path1, path2, **kwargs):
+ path1 = self._strip_protocol(path1).rstrip("/")
+ path2 = self._strip_protocol(path2).rstrip("/")
+
+ with self._open(path1, "rb") as lstream:
+ tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}"
+ try:
+ with self.open(tmp_fname, "wb") as rstream:
+ shutil.copyfileobj(lstream, rstream)
+ self.fs.move(tmp_fname, path2)
+ except BaseException:
+ with suppress(FileNotFoundError):
+ self.fs.delete_file(tmp_fname)
+ raise
+
+ @wrap_exceptions
+ def mv(self, path1, path2, **kwargs):
+ path1 = self._strip_protocol(path1).rstrip("/")
+ path2 = self._strip_protocol(path2).rstrip("/")
+ self.fs.move(path1, path2)
+
+ @wrap_exceptions
+ def rm_file(self, path):
+ path = self._strip_protocol(path)
+ self.fs.delete_file(path)
+
+ @wrap_exceptions
+ def rm(self, path, recursive=False, maxdepth=None):
+ path = self._strip_protocol(path).rstrip("/")
+ if self.isdir(path):
+ if recursive:
+ self.fs.delete_dir(path)
+ else:
+ raise ValueError("Can't delete directories without recursive=False")
+ else:
+ self.fs.delete_file(path)
+
+ @wrap_exceptions
+ def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs):
+ if mode == "rb":
+ if seekable:
+ method = self.fs.open_input_file
+ else:
+ method = self.fs.open_input_stream
+ elif mode == "wb":
+ method = self.fs.open_output_stream
+ elif mode == "ab":
+ method = self.fs.open_append_stream
+ else:
+ raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}")
+
+ _kwargs = {}
+ if mode != "rb" or not seekable:
+ if int(PYARROW_VERSION.split(".")[0]) >= 4:
+ # disable compression auto-detection
+ _kwargs["compression"] = None
+ stream = method(path, **_kwargs)
+
+ return ArrowFile(self, stream, path, mode, block_size, **kwargs)
+
+ @wrap_exceptions
+ def mkdir(self, path, create_parents=True, **kwargs):
+ path = self._strip_protocol(path)
+ if create_parents:
+ self.makedirs(path, exist_ok=True)
+ else:
+ self.fs.create_dir(path, recursive=False)
+
+ @wrap_exceptions
+ def makedirs(self, path, exist_ok=False):
+ path = self._strip_protocol(path)
+ self.fs.create_dir(path, recursive=True)
+
+ @wrap_exceptions
+ def rmdir(self, path):
+ path = self._strip_protocol(path)
+ self.fs.delete_dir(path)
+
+ @wrap_exceptions
+ def modified(self, path):
+ path = self._strip_protocol(path)
+ return self.fs.get_file_info(path).mtime
+
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ kwargs["seekable"] = start not in [None, 0]
+ return super().cat_file(path, start=None, end=None, **kwargs)
+
+ def get_file(self, rpath, lpath, **kwargs):
+ kwargs["seekable"] = False
+ super().get_file(rpath, lpath, **kwargs)
+
+
+@mirror_from(
+ "stream",
+ [
+ "read",
+ "seek",
+ "tell",
+ "write",
+ "readable",
+ "writable",
+ "close",
+ "size",
+ "seekable",
+ ],
+)
+class ArrowFile(io.IOBase):
+ def __init__(self, fs, stream, path, mode, block_size=None, **kwargs):
+ self.path = path
+ self.mode = mode
+
+ self.fs = fs
+ self.stream = stream
+
+ self.blocksize = self.block_size = block_size
+ self.kwargs = kwargs
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return self.close()
+
+
+class HadoopFileSystem(ArrowFSWrapper):
+ """A wrapper on top of the pyarrow.fs.HadoopFileSystem
+ to connect it's interface with fsspec"""
+
+ protocol = "hdfs"
+
+ def __init__(
+ self,
+ host="default",
+ port=0,
+ user=None,
+ kerb_ticket=None,
+ replication=3,
+ extra_conf=None,
+ **kwargs,
+ ):
+ """
+
+ Parameters
+ ----------
+ host: str
+ Hostname, IP or "default" to try to read from Hadoop config
+ port: int
+ Port to connect on, or default from Hadoop config if 0
+ user: str or None
+ If given, connect as this username
+ kerb_ticket: str or None
+ If given, use this ticket for authentication
+ replication: int
+ set replication factor of file for write operations. default value is 3.
+ extra_conf: None or dict
+ Passed on to HadoopFileSystem
+ """
+ from pyarrow.fs import HadoopFileSystem
+
+ fs = HadoopFileSystem(
+ host=host,
+ port=port,
+ user=user,
+ kerb_ticket=kerb_ticket,
+ replication=replication,
+ extra_conf=extra_conf,
+ )
+ super().__init__(fs=fs, **kwargs)
+
+ @staticmethod
+ def _get_kwargs_from_urls(path):
+ ops = infer_storage_options(path)
+ out = {}
+ if ops.get("host", None):
+ out["host"] = ops["host"]
+ if ops.get("username", None):
+ out["user"] = ops["username"]
+ if ops.get("port", None):
+ out["port"] = ops["port"]
+ if ops.get("url_query", None):
+ queries = parse_qs(ops["url_query"])
+ if queries.get("replication", None):
+ out["replication"] = int(queries["replication"][0])
+ return out
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..36db9c1b42e1a057c5346f0bedac3f9ff015c401
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py
@@ -0,0 +1,122 @@
+import asyncio
+import functools
+import inspect
+
+import fsspec
+from fsspec.asyn import AsyncFileSystem, running_async
+
+
+def async_wrapper(func, obj=None, semaphore=None):
+ """
+ Wraps a synchronous function to make it awaitable.
+
+ Parameters
+ ----------
+ func : callable
+ The synchronous function to wrap.
+ obj : object, optional
+ The instance to bind the function to, if applicable.
+ semaphore : asyncio.Semaphore, optional
+ A semaphore to limit concurrent calls.
+
+ Returns
+ -------
+ coroutine
+ An awaitable version of the function.
+ """
+
+ @functools.wraps(func)
+ async def wrapper(*args, **kwargs):
+ if semaphore:
+ async with semaphore:
+ return await asyncio.to_thread(func, *args, **kwargs)
+ return await asyncio.to_thread(func, *args, **kwargs)
+
+ return wrapper
+
+
+class AsyncFileSystemWrapper(AsyncFileSystem):
+ """
+ A wrapper class to convert a synchronous filesystem into an asynchronous one.
+
+ This class takes an existing synchronous filesystem implementation and wraps all
+ its methods to provide an asynchronous interface.
+
+ Parameters
+ ----------
+ sync_fs : AbstractFileSystem
+ The synchronous filesystem instance to wrap.
+ """
+
+ protocol = "asyncwrapper", "async_wrapper"
+ cachable = False
+
+ def __init__(
+ self,
+ fs=None,
+ asynchronous=None,
+ target_protocol=None,
+ target_options=None,
+ semaphore=None,
+ max_concurrent_tasks=None,
+ **kwargs,
+ ):
+ if asynchronous is None:
+ asynchronous = running_async()
+ super().__init__(asynchronous=asynchronous, **kwargs)
+ if fs is not None:
+ self.sync_fs = fs
+ else:
+ self.sync_fs = fsspec.filesystem(target_protocol, **target_options)
+ self.protocol = self.sync_fs.protocol
+ self.semaphore = semaphore
+ self._wrap_all_sync_methods()
+
+ @property
+ def fsid(self):
+ return f"async_{self.sync_fs.fsid}"
+
+ def _wrap_all_sync_methods(self):
+ """
+ Wrap all synchronous methods of the underlying filesystem with asynchronous versions.
+ """
+ excluded_methods = {"open"}
+ for method_name in dir(self.sync_fs):
+ if method_name.startswith("_") or method_name in excluded_methods:
+ continue
+
+ attr = inspect.getattr_static(self.sync_fs, method_name)
+ if isinstance(attr, property):
+ continue
+
+ method = getattr(self.sync_fs, method_name)
+ if callable(method) and not inspect.iscoroutinefunction(method):
+ async_method = async_wrapper(method, obj=self, semaphore=self.semaphore)
+ setattr(self, f"_{method_name}", async_method)
+
+ @classmethod
+ def wrap_class(cls, sync_fs_class):
+ """
+ Create a new class that can be used to instantiate an AsyncFileSystemWrapper
+ with lazy instantiation of the underlying synchronous filesystem.
+
+ Parameters
+ ----------
+ sync_fs_class : type
+ The class of the synchronous filesystem to wrap.
+
+ Returns
+ -------
+ type
+ A new class that wraps the provided synchronous filesystem class.
+ """
+
+ class GeneratedAsyncFileSystemWrapper(cls):
+ def __init__(self, *args, **kwargs):
+ sync_fs = sync_fs_class(*args, **kwargs)
+ super().__init__(sync_fs)
+
+ GeneratedAsyncFileSystemWrapper.__name__ = (
+ f"Async{sync_fs_class.__name__}Wrapper"
+ )
+ return GeneratedAsyncFileSystemWrapper
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e7c7d88afdddf12f77b26bb635bd8bf1e2bd7f1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+import abc
+import hashlib
+
+from fsspec.implementations.local import make_path_posix
+
+
+class AbstractCacheMapper(abc.ABC):
+ """Abstract super-class for mappers from remote URLs to local cached
+ basenames.
+ """
+
+ @abc.abstractmethod
+ def __call__(self, path: str) -> str: ...
+
+ def __eq__(self, other: object) -> bool:
+ # Identity only depends on class. When derived classes have attributes
+ # they will need to be included.
+ return isinstance(other, type(self))
+
+ def __hash__(self) -> int:
+ # Identity only depends on class. When derived classes have attributes
+ # they will need to be included.
+ return hash(type(self))
+
+
+class BasenameCacheMapper(AbstractCacheMapper):
+ """Cache mapper that uses the basename of the remote URL and a fixed number
+ of directory levels above this.
+
+ The default is zero directory levels, meaning different paths with the same
+ basename will have the same cached basename.
+ """
+
+ def __init__(self, directory_levels: int = 0):
+ if directory_levels < 0:
+ raise ValueError(
+ "BasenameCacheMapper requires zero or positive directory_levels"
+ )
+ self.directory_levels = directory_levels
+
+ # Separator for directories when encoded as strings.
+ self._separator = "_@_"
+
+ def __call__(self, path: str) -> str:
+ path = make_path_posix(path)
+ prefix, *bits = path.rsplit("/", self.directory_levels + 1)
+ if bits:
+ return self._separator.join(bits)
+ else:
+ return prefix # No separator found, simple filename
+
+ def __eq__(self, other: object) -> bool:
+ return super().__eq__(other) and self.directory_levels == other.directory_levels
+
+ def __hash__(self) -> int:
+ return super().__hash__() ^ hash(self.directory_levels)
+
+
+class HashCacheMapper(AbstractCacheMapper):
+ """Cache mapper that uses a hash of the remote URL."""
+
+ def __call__(self, path: str) -> str:
+ return hashlib.sha256(path.encode()).hexdigest()
+
+
+def create_cache_mapper(same_names: bool) -> AbstractCacheMapper:
+ """Factory method to create cache mapper for backward compatibility with
+ ``CachingFileSystem`` constructor using ``same_names`` kwarg.
+ """
+ if same_names:
+ return BasenameCacheMapper()
+ else:
+ return HashCacheMapper()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a519158d4aca975dcbcc5978aeb57dab0e53cb0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py
@@ -0,0 +1,233 @@
+from __future__ import annotations
+
+import os
+import pickle
+import time
+from typing import TYPE_CHECKING
+
+from fsspec.utils import atomic_write
+
+try:
+ import ujson as json
+except ImportError:
+ if not TYPE_CHECKING:
+ import json
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+ from typing import Any, Literal
+
+ from typing_extensions import TypeAlias
+
+ from .cached import CachingFileSystem
+
+ Detail: TypeAlias = dict[str, Any]
+
+
+class CacheMetadata:
+ """Cache metadata.
+
+ All reading and writing of cache metadata is performed by this class,
+ accessing the cached files and blocks is not.
+
+ Metadata is stored in a single file per storage directory in JSON format.
+ For backward compatibility, also reads metadata stored in pickle format
+ which is converted to JSON when next saved.
+ """
+
+ def __init__(self, storage: list[str]):
+ """
+
+ Parameters
+ ----------
+ storage: list[str]
+ Directories containing cached files, must be at least one. Metadata
+ is stored in the last of these directories by convention.
+ """
+ if not storage:
+ raise ValueError("CacheMetadata expects at least one storage location")
+
+ self._storage = storage
+ self.cached_files: list[Detail] = [{}]
+
+ # Private attribute to force saving of metadata in pickle format rather than
+ # JSON for use in tests to confirm can read both pickle and JSON formats.
+ self._force_save_pickle = False
+
+ def _load(self, fn: str) -> Detail:
+ """Low-level function to load metadata from specific file"""
+ try:
+ with open(fn, "r") as f:
+ loaded = json.load(f)
+ except ValueError:
+ with open(fn, "rb") as f:
+ loaded = pickle.load(f)
+ for c in loaded.values():
+ if isinstance(c.get("blocks"), list):
+ c["blocks"] = set(c["blocks"])
+ return loaded
+
+ def _save(self, metadata_to_save: Detail, fn: str) -> None:
+ """Low-level function to save metadata to specific file"""
+ if self._force_save_pickle:
+ with atomic_write(fn) as f:
+ pickle.dump(metadata_to_save, f)
+ else:
+ with atomic_write(fn, mode="w") as f:
+ json.dump(metadata_to_save, f)
+
+ def _scan_locations(
+ self, writable_only: bool = False
+ ) -> Iterator[tuple[str, str, bool]]:
+ """Yield locations (filenames) where metadata is stored, and whether
+ writable or not.
+
+ Parameters
+ ----------
+ writable: bool
+ Set to True to only yield writable locations.
+
+ Returns
+ -------
+ Yields (str, str, bool)
+ """
+ n = len(self._storage)
+ for i, storage in enumerate(self._storage):
+ writable = i == n - 1
+ if writable_only and not writable:
+ continue
+ yield os.path.join(storage, "cache"), storage, writable
+
+ def check_file(
+ self, path: str, cfs: CachingFileSystem | None
+ ) -> Literal[False] | tuple[Detail, str]:
+ """If path is in cache return its details, otherwise return ``False``.
+
+ If the optional CachingFileSystem is specified then it is used to
+ perform extra checks to reject possible matches, such as if they are
+ too old.
+ """
+ for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files):
+ if path not in cache:
+ continue
+ detail = cache[path].copy()
+
+ if cfs is not None:
+ if cfs.check_files and detail["uid"] != cfs.fs.ukey(path):
+ # Wrong file as determined by hash of file properties
+ continue
+ if cfs.expiry and time.time() - detail["time"] > cfs.expiry:
+ # Cached file has expired
+ continue
+
+ fn = os.path.join(base, detail["fn"])
+ if os.path.exists(fn):
+ return detail, fn
+ return False
+
+ def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]:
+ """Remove expired metadata from the cache.
+
+ Returns names of files corresponding to expired metadata and a boolean
+ flag indicating whether the writable cache is empty. Caller is
+ responsible for deleting the expired files.
+ """
+ expired_files = []
+ for path, detail in self.cached_files[-1].copy().items():
+ if time.time() - detail["time"] > expiry_time:
+ fn = detail.get("fn", "")
+ if not fn:
+ raise RuntimeError(
+ f"Cache metadata does not contain 'fn' for {path}"
+ )
+ fn = os.path.join(self._storage[-1], fn)
+ expired_files.append(fn)
+ self.cached_files[-1].pop(path)
+
+ if self.cached_files[-1]:
+ cache_path = os.path.join(self._storage[-1], "cache")
+ self._save(self.cached_files[-1], cache_path)
+
+ writable_cache_empty = not self.cached_files[-1]
+ return expired_files, writable_cache_empty
+
+ def load(self) -> None:
+ """Load all metadata from disk and store in ``self.cached_files``"""
+ cached_files = []
+ for fn, _, _ in self._scan_locations():
+ if os.path.exists(fn):
+ # TODO: consolidate blocks here
+ cached_files.append(self._load(fn))
+ else:
+ cached_files.append({})
+ self.cached_files = cached_files or [{}]
+
+ def on_close_cached_file(self, f: Any, path: str) -> None:
+ """Perform side-effect actions on closing a cached file.
+
+ The actual closing of the file is the responsibility of the caller.
+ """
+ # File must be writeble, so in self.cached_files[-1]
+ c = self.cached_files[-1][path]
+ if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size:
+ c["blocks"] = True
+
+ def pop_file(self, path: str) -> str | None:
+ """Remove metadata of cached file.
+
+ If path is in the cache, return the filename of the cached file,
+ otherwise return ``None``. Caller is responsible for deleting the
+ cached file.
+ """
+ details = self.check_file(path, None)
+ if not details:
+ return None
+ _, fn = details
+ if fn.startswith(self._storage[-1]):
+ self.cached_files[-1].pop(path)
+ self.save()
+ else:
+ raise PermissionError(
+ "Can only delete cached file in last, writable cache location"
+ )
+ return fn
+
+ def save(self) -> None:
+ """Save metadata to disk"""
+ for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files):
+ if not writable:
+ continue
+
+ if os.path.exists(fn):
+ cached_files = self._load(fn)
+ for k, c in cached_files.items():
+ if k in cache:
+ if c["blocks"] is True or cache[k]["blocks"] is True:
+ c["blocks"] = True
+ else:
+ # self.cached_files[*][*]["blocks"] must continue to
+ # point to the same set object so that updates
+ # performed by MMapCache are propagated back to
+ # self.cached_files.
+ blocks = cache[k]["blocks"]
+ blocks.update(c["blocks"])
+ c["blocks"] = blocks
+ c["time"] = max(c["time"], cache[k]["time"])
+ c["uid"] = cache[k]["uid"]
+
+ # Files can be added to cache after it was written once
+ for k, c in cache.items():
+ if k not in cached_files:
+ cached_files[k] = c
+ else:
+ cached_files = cache
+ cache = {k: v.copy() for k, v in cached_files.items()}
+ for c in cache.values():
+ if isinstance(c["blocks"], set):
+ c["blocks"] = list(c["blocks"])
+ self._save(cache, fn)
+ self.cached_files[-1] = cached_files
+
+ def update_file(self, path: str, detail: Detail) -> None:
+ """Update metadata for specific file in memory, do not save"""
+ self.cached_files[-1][path] = detail
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cached.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cached.py
new file mode 100644
index 0000000000000000000000000000000000000000..4847c2ef262b688b25508b2861f394426ba2dd73
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/cached.py
@@ -0,0 +1,998 @@
+from __future__ import annotations
+
+import inspect
+import logging
+import os
+import tempfile
+import time
+import weakref
+from shutil import rmtree
+from typing import TYPE_CHECKING, Any, Callable, ClassVar
+
+from fsspec import AbstractFileSystem, filesystem
+from fsspec.callbacks import DEFAULT_CALLBACK
+from fsspec.compression import compr
+from fsspec.core import BaseCache, MMapCache
+from fsspec.exceptions import BlocksizeMismatchError
+from fsspec.implementations.cache_mapper import create_cache_mapper
+from fsspec.implementations.cache_metadata import CacheMetadata
+from fsspec.implementations.local import LocalFileSystem
+from fsspec.spec import AbstractBufferedFile
+from fsspec.transaction import Transaction
+from fsspec.utils import infer_compression
+
+if TYPE_CHECKING:
+ from fsspec.implementations.cache_mapper import AbstractCacheMapper
+
+logger = logging.getLogger("fsspec.cached")
+
+
+class WriteCachedTransaction(Transaction):
+ def complete(self, commit=True):
+ rpaths = [f.path for f in self.files]
+ lpaths = [f.fn for f in self.files]
+ if commit:
+ self.fs.put(lpaths, rpaths)
+ self.files.clear()
+ self.fs._intrans = False
+ self.fs._transaction = None
+ self.fs = None # break cycle
+
+
+class CachingFileSystem(AbstractFileSystem):
+ """Locally caching filesystem, layer over any other FS
+
+ This class implements chunk-wise local storage of remote files, for quick
+ access after the initial download. The files are stored in a given
+ directory with hashes of URLs for the filenames. If no directory is given,
+ a temporary one is used, which should be cleaned up by the OS after the
+ process ends. The files themselves are sparse (as implemented in
+ :class:`~fsspec.caching.MMapCache`), so only the data which is accessed
+ takes up space.
+
+ Restrictions:
+
+ - the block-size must be the same for each access of a given file, unless
+ all blocks of the file have already been read
+ - caching can only be applied to file-systems which produce files
+ derived from fsspec.spec.AbstractBufferedFile ; LocalFileSystem is also
+ allowed, for testing
+ """
+
+ protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached")
+
+ def __init__(
+ self,
+ target_protocol=None,
+ cache_storage="TMP",
+ cache_check=10,
+ check_files=False,
+ expiry_time=604800,
+ target_options=None,
+ fs=None,
+ same_names: bool | None = None,
+ compression=None,
+ cache_mapper: AbstractCacheMapper | None = None,
+ **kwargs,
+ ):
+ """
+
+ Parameters
+ ----------
+ target_protocol: str (optional)
+ Target filesystem protocol. Provide either this or ``fs``.
+ cache_storage: str or list(str)
+ Location to store files. If "TMP", this is a temporary directory,
+ and will be cleaned up by the OS when this process ends (or later).
+ If a list, each location will be tried in the order given, but
+ only the last will be considered writable.
+ cache_check: int
+ Number of seconds between reload of cache metadata
+ check_files: bool
+ Whether to explicitly see if the UID of the remote file matches
+ the stored one before using. Warning: some file systems such as
+ HTTP cannot reliably give a unique hash of the contents of some
+ path, so be sure to set this option to False.
+ expiry_time: int
+ The time in seconds after which a local copy is considered useless.
+ Set to falsy to prevent expiry. The default is equivalent to one
+ week.
+ target_options: dict or None
+ Passed to the instantiation of the FS, if fs is None.
+ fs: filesystem instance
+ The target filesystem to run against. Provide this or ``protocol``.
+ same_names: bool (optional)
+ By default, target URLs are hashed using a ``HashCacheMapper`` so
+ that files from different backends with the same basename do not
+ conflict. If this argument is ``true``, a ``BasenameCacheMapper``
+ is used instead. Other cache mapper options are available by using
+ the ``cache_mapper`` keyword argument. Only one of this and
+ ``cache_mapper`` should be specified.
+ compression: str (optional)
+ To decompress on download. Can be 'infer' (guess from the URL name),
+ one of the entries in ``fsspec.compression.compr``, or None for no
+ decompression.
+ cache_mapper: AbstractCacheMapper (optional)
+ The object use to map from original filenames to cached filenames.
+ Only one of this and ``same_names`` should be specified.
+ """
+ super().__init__(**kwargs)
+ if fs is None and target_protocol is None:
+ raise ValueError(
+ "Please provide filesystem instance(fs) or target_protocol"
+ )
+ if not (fs is None) ^ (target_protocol is None):
+ raise ValueError(
+ "Both filesystems (fs) and target_protocol may not be both given."
+ )
+ if cache_storage == "TMP":
+ tempdir = tempfile.mkdtemp()
+ storage = [tempdir]
+ weakref.finalize(self, self._remove_tempdir, tempdir)
+ else:
+ if isinstance(cache_storage, str):
+ storage = [cache_storage]
+ else:
+ storage = cache_storage
+ os.makedirs(storage[-1], exist_ok=True)
+ self.storage = storage
+ self.kwargs = target_options or {}
+ self.cache_check = cache_check
+ self.check_files = check_files
+ self.expiry = expiry_time
+ self.compression = compression
+
+ # Size of cache in bytes. If None then the size is unknown and will be
+ # recalculated the next time cache_size() is called. On writes to the
+ # cache this is reset to None.
+ self._cache_size = None
+
+ if same_names is not None and cache_mapper is not None:
+ raise ValueError(
+ "Cannot specify both same_names and cache_mapper in "
+ "CachingFileSystem.__init__"
+ )
+ if cache_mapper is not None:
+ self._mapper = cache_mapper
+ else:
+ self._mapper = create_cache_mapper(
+ same_names if same_names is not None else False
+ )
+
+ self.target_protocol = (
+ target_protocol
+ if isinstance(target_protocol, str)
+ else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0])
+ )
+ self._metadata = CacheMetadata(self.storage)
+ self.load_cache()
+ self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs)
+
+ def _strip_protocol(path):
+ # acts as a method, since each instance has a difference target
+ return self.fs._strip_protocol(type(self)._strip_protocol(path))
+
+ self._strip_protocol: Callable = _strip_protocol
+
+ @staticmethod
+ def _remove_tempdir(tempdir):
+ try:
+ rmtree(tempdir)
+ except Exception:
+ pass
+
+ def _mkcache(self):
+ os.makedirs(self.storage[-1], exist_ok=True)
+
+ def cache_size(self):
+ """Return size of cache in bytes.
+
+ If more than one cache directory is in use, only the size of the last
+ one (the writable cache directory) is returned.
+ """
+ if self._cache_size is None:
+ cache_dir = self.storage[-1]
+ self._cache_size = filesystem("file").du(cache_dir, withdirs=True)
+ return self._cache_size
+
+ def load_cache(self):
+ """Read set of stored blocks from file"""
+ self._metadata.load()
+ self._mkcache()
+ self.last_cache = time.time()
+
+ def save_cache(self):
+ """Save set of stored blocks from file"""
+ self._mkcache()
+ self._metadata.save()
+ self.last_cache = time.time()
+ self._cache_size = None
+
+ def _check_cache(self):
+ """Reload caches if time elapsed or any disappeared"""
+ self._mkcache()
+ if not self.cache_check:
+ # explicitly told not to bother checking
+ return
+ timecond = time.time() - self.last_cache > self.cache_check
+ existcond = all(os.path.exists(storage) for storage in self.storage)
+ if timecond or not existcond:
+ self.load_cache()
+
+ def _check_file(self, path):
+ """Is path in cache and still valid"""
+ path = self._strip_protocol(path)
+ self._check_cache()
+ return self._metadata.check_file(path, self)
+
+ def clear_cache(self):
+ """Remove all files and metadata from the cache
+
+ In the case of multiple cache locations, this clears only the last one,
+ which is assumed to be the read/write one.
+ """
+ rmtree(self.storage[-1])
+ self.load_cache()
+ self._cache_size = None
+
+ def clear_expired_cache(self, expiry_time=None):
+ """Remove all expired files and metadata from the cache
+
+ In the case of multiple cache locations, this clears only the last one,
+ which is assumed to be the read/write one.
+
+ Parameters
+ ----------
+ expiry_time: int
+ The time in seconds after which a local copy is considered useless.
+ If not defined the default is equivalent to the attribute from the
+ file caching instantiation.
+ """
+
+ if not expiry_time:
+ expiry_time = self.expiry
+
+ self._check_cache()
+
+ expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time)
+ for fn in expired_files:
+ if os.path.exists(fn):
+ os.remove(fn)
+
+ if writable_cache_empty:
+ rmtree(self.storage[-1])
+ self.load_cache()
+
+ self._cache_size = None
+
+ def pop_from_cache(self, path):
+ """Remove cached version of given file
+
+ Deletes local copy of the given (remote) path. If it is found in a cache
+ location which is not the last, it is assumed to be read-only, and
+ raises PermissionError
+ """
+ path = self._strip_protocol(path)
+ fn = self._metadata.pop_file(path)
+ if fn is not None:
+ os.remove(fn)
+ self._cache_size = None
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ cache_options=None,
+ **kwargs,
+ ):
+ """Wrap the target _open
+
+ If the whole file exists in the cache, just open it locally and
+ return that.
+
+ Otherwise, open the file on the target FS, and make it have a mmap
+ cache pointing to the location which we determine, in our cache.
+ The ``blocks`` instance is shared, so as the mmap cache instance
+ updates, so does the entry in our ``cached_files`` attribute.
+ We monkey-patch this file, so that when it closes, we call
+ ``close_and_update`` to save the state of the blocks.
+ """
+ path = self._strip_protocol(path)
+
+ path = self.fs._strip_protocol(path)
+ if "r" not in mode:
+ return self.fs._open(
+ path,
+ mode=mode,
+ block_size=block_size,
+ autocommit=autocommit,
+ cache_options=cache_options,
+ **kwargs,
+ )
+ detail = self._check_file(path)
+ if detail:
+ # file is in cache
+ detail, fn = detail
+ hash, blocks = detail["fn"], detail["blocks"]
+ if blocks is True:
+ # stored file is complete
+ logger.debug("Opening local copy of %s", path)
+ return open(fn, mode)
+ # TODO: action where partial file exists in read-only cache
+ logger.debug("Opening partially cached copy of %s", path)
+ else:
+ hash = self._mapper(path)
+ fn = os.path.join(self.storage[-1], hash)
+ blocks = set()
+ detail = {
+ "original": path,
+ "fn": hash,
+ "blocks": blocks,
+ "time": time.time(),
+ "uid": self.fs.ukey(path),
+ }
+ self._metadata.update_file(path, detail)
+ logger.debug("Creating local sparse file for %s", path)
+
+ # explicitly submitting the size to the open call will avoid extra
+ # operations when opening. This is particularly relevant
+ # for any file that is read over a network, e.g. S3.
+ size = detail.get("size")
+
+ # call target filesystems open
+ self._mkcache()
+ f = self.fs._open(
+ path,
+ mode=mode,
+ block_size=block_size,
+ autocommit=autocommit,
+ cache_options=cache_options,
+ cache_type="none",
+ size=size,
+ **kwargs,
+ )
+
+ # set size if not already set
+ if size is None:
+ detail["size"] = f.size
+ self._metadata.update_file(path, detail)
+
+ if self.compression:
+ comp = (
+ infer_compression(path)
+ if self.compression == "infer"
+ else self.compression
+ )
+ f = compr[comp](f, mode="rb")
+ if "blocksize" in detail:
+ if detail["blocksize"] != f.blocksize:
+ raise BlocksizeMismatchError(
+ f"Cached file must be reopened with same block"
+ f" size as original (old: {detail['blocksize']},"
+ f" new {f.blocksize})"
+ )
+ else:
+ detail["blocksize"] = f.blocksize
+
+ def _fetch_ranges(ranges):
+ return self.fs.cat_ranges(
+ [path] * len(ranges),
+ [r[0] for r in ranges],
+ [r[1] for r in ranges],
+ **kwargs,
+ )
+
+ multi_fetcher = None if self.compression else _fetch_ranges
+ f.cache = MMapCache(
+ f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher
+ )
+ close = f.close
+ f.close = lambda: self.close_and_update(f, close)
+ self.save_cache()
+ return f
+
+ def _parent(self, path):
+ return self.fs._parent(path)
+
+ def hash_name(self, path: str, *args: Any) -> str:
+ # Kept for backward compatibility with downstream libraries.
+ # Ignores extra arguments, previously same_name boolean.
+ return self._mapper(path)
+
+ def close_and_update(self, f, close):
+ """Called when a file is closing, so store the set of blocks"""
+ if f.closed:
+ return
+ path = self._strip_protocol(f.path)
+ self._metadata.on_close_cached_file(f, path)
+ try:
+ logger.debug("going to save")
+ self.save_cache()
+ logger.debug("saved")
+ except OSError:
+ logger.debug("Cache saving failed while closing file")
+ except NameError:
+ logger.debug("Cache save failed due to interpreter shutdown")
+ close()
+ f.closed = True
+
+ def ls(self, path, detail=True):
+ return self.fs.ls(path, detail)
+
+ def __getattribute__(self, item):
+ if item in {
+ "load_cache",
+ "_open",
+ "save_cache",
+ "close_and_update",
+ "__init__",
+ "__getattribute__",
+ "__reduce__",
+ "_make_local_details",
+ "open",
+ "cat",
+ "cat_file",
+ "_cat_file",
+ "cat_ranges",
+ "_cat_ranges",
+ "get",
+ "read_block",
+ "tail",
+ "head",
+ "info",
+ "ls",
+ "exists",
+ "isfile",
+ "isdir",
+ "_check_file",
+ "_check_cache",
+ "_mkcache",
+ "clear_cache",
+ "clear_expired_cache",
+ "pop_from_cache",
+ "local_file",
+ "_paths_from_path",
+ "get_mapper",
+ "open_many",
+ "commit_many",
+ "hash_name",
+ "__hash__",
+ "__eq__",
+ "to_json",
+ "to_dict",
+ "cache_size",
+ "pipe_file",
+ "pipe",
+ "start_transaction",
+ "end_transaction",
+ }:
+ # all the methods defined in this class. Note `open` here, since
+ # it calls `_open`, but is actually in superclass
+ return lambda *args, **kw: getattr(type(self), item).__get__(self)(
+ *args, **kw
+ )
+ if item in ["__reduce_ex__"]:
+ raise AttributeError
+ if item in ["transaction"]:
+ # property
+ return type(self).transaction.__get__(self)
+ if item in {"_cache", "transaction_type", "protocol"}:
+ # class attributes
+ return getattr(type(self), item)
+ if item == "__class__":
+ return type(self)
+ d = object.__getattribute__(self, "__dict__")
+ fs = d.get("fs", None) # fs is not immediately defined
+ if item in d:
+ return d[item]
+ elif fs is not None:
+ if item in fs.__dict__:
+ # attribute of instance
+ return fs.__dict__[item]
+ # attributed belonging to the target filesystem
+ cls = type(fs)
+ m = getattr(cls, item)
+ if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and (
+ not hasattr(m, "__self__") or m.__self__ is None
+ ):
+ # instance method
+ return m.__get__(fs, cls)
+ return m # class method or attribute
+ else:
+ # attributes of the superclass, while target is being set up
+ return super().__getattribute__(item)
+
+ def __eq__(self, other):
+ """Test for equality."""
+ if self is other:
+ return True
+ if not isinstance(other, type(self)):
+ return False
+ return (
+ self.storage == other.storage
+ and self.kwargs == other.kwargs
+ and self.cache_check == other.cache_check
+ and self.check_files == other.check_files
+ and self.expiry == other.expiry
+ and self.compression == other.compression
+ and self._mapper == other._mapper
+ and self.target_protocol == other.target_protocol
+ )
+
+ def __hash__(self):
+ """Calculate hash."""
+ return (
+ hash(tuple(self.storage))
+ ^ hash(str(self.kwargs))
+ ^ hash(self.cache_check)
+ ^ hash(self.check_files)
+ ^ hash(self.expiry)
+ ^ hash(self.compression)
+ ^ hash(self._mapper)
+ ^ hash(self.target_protocol)
+ )
+
+
+class WholeFileCacheFileSystem(CachingFileSystem):
+ """Caches whole remote files on first access
+
+ This class is intended as a layer over any other file system, and
+ will make a local copy of each file accessed, so that all subsequent
+ reads are local. This is similar to ``CachingFileSystem``, but without
+ the block-wise functionality and so can work even when sparse files
+ are not allowed. See its docstring for definition of the init
+ arguments.
+
+ The class still needs access to the remote store for listing files,
+ and may refresh cached files.
+ """
+
+ protocol = "filecache"
+ local_file = True
+
+ def open_many(self, open_files, **kwargs):
+ paths = [of.path for of in open_files]
+ if "r" in open_files.mode:
+ self._mkcache()
+ else:
+ return [
+ LocalTempFile(
+ self.fs,
+ path,
+ mode=open_files.mode,
+ fn=os.path.join(self.storage[-1], self._mapper(path)),
+ **kwargs,
+ )
+ for path in paths
+ ]
+
+ if self.compression:
+ raise NotImplementedError
+ details = [self._check_file(sp) for sp in paths]
+ downpath = [p for p, d in zip(paths, details) if not d]
+ downfn0 = [
+ os.path.join(self.storage[-1], self._mapper(p))
+ for p, d in zip(paths, details)
+ ] # keep these path names for opening later
+ downfn = [fn for fn, d in zip(downfn0, details) if not d]
+ if downpath:
+ # skip if all files are already cached and up to date
+ self.fs.get(downpath, downfn)
+
+ # update metadata - only happens when downloads are successful
+ newdetail = [
+ {
+ "original": path,
+ "fn": self._mapper(path),
+ "blocks": True,
+ "time": time.time(),
+ "uid": self.fs.ukey(path),
+ }
+ for path in downpath
+ ]
+ for path, detail in zip(downpath, newdetail):
+ self._metadata.update_file(path, detail)
+ self.save_cache()
+
+ def firstpart(fn):
+ # helper to adapt both whole-file and simple-cache
+ return fn[1] if isinstance(fn, tuple) else fn
+
+ return [
+ open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode)
+ for fn0, fn1 in zip(details, downfn0)
+ ]
+
+ def commit_many(self, open_files):
+ self.fs.put([f.fn for f in open_files], [f.path for f in open_files])
+ [f.close() for f in open_files]
+ for f in open_files:
+ # in case autocommit is off, and so close did not already delete
+ try:
+ os.remove(f.name)
+ except FileNotFoundError:
+ pass
+ self._cache_size = None
+
+ def _make_local_details(self, path):
+ hash = self._mapper(path)
+ fn = os.path.join(self.storage[-1], hash)
+ detail = {
+ "original": path,
+ "fn": hash,
+ "blocks": True,
+ "time": time.time(),
+ "uid": self.fs.ukey(path),
+ }
+ self._metadata.update_file(path, detail)
+ logger.debug("Copying %s to local cache", path)
+ return fn
+
+ def cat(
+ self,
+ path,
+ recursive=False,
+ on_error="raise",
+ callback=DEFAULT_CALLBACK,
+ **kwargs,
+ ):
+ paths = self.expand_path(
+ path, recursive=recursive, maxdepth=kwargs.get("maxdepth")
+ )
+ getpaths = []
+ storepaths = []
+ fns = []
+ out = {}
+ for p in paths.copy():
+ try:
+ detail = self._check_file(p)
+ if not detail:
+ fn = self._make_local_details(p)
+ getpaths.append(p)
+ storepaths.append(fn)
+ else:
+ detail, fn = detail if isinstance(detail, tuple) else (None, detail)
+ fns.append(fn)
+ except Exception as e:
+ if on_error == "raise":
+ raise
+ if on_error == "return":
+ out[p] = e
+ paths.remove(p)
+
+ if getpaths:
+ self.fs.get(getpaths, storepaths)
+ self.save_cache()
+
+ callback.set_size(len(paths))
+ for p, fn in zip(paths, fns):
+ with open(fn, "rb") as f:
+ out[p] = f.read()
+ callback.relative_update(1)
+ if isinstance(path, str) and len(paths) == 1 and recursive is False:
+ out = out[paths[0]]
+ return out
+
+ def _open(self, path, mode="rb", **kwargs):
+ path = self._strip_protocol(path)
+ if "r" not in mode:
+ hash = self._mapper(path)
+ fn = os.path.join(self.storage[-1], hash)
+ user_specified_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ # those kwargs were added by open(), we don't want them
+ if k not in ["autocommit", "block_size", "cache_options"]
+ }
+ return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs)
+ detail = self._check_file(path)
+ if detail:
+ detail, fn = detail
+ _, blocks = detail["fn"], detail["blocks"]
+ if blocks is True:
+ logger.debug("Opening local copy of %s", path)
+
+ # In order to support downstream filesystems to be able to
+ # infer the compression from the original filename, like
+ # the `TarFileSystem`, let's extend the `io.BufferedReader`
+ # fileobject protocol by adding a dedicated attribute
+ # `original`.
+ f = open(fn, mode)
+ f.original = detail.get("original")
+ return f
+ else:
+ raise ValueError(
+ f"Attempt to open partially cached file {path}"
+ f" as a wholly cached file"
+ )
+ else:
+ fn = self._make_local_details(path)
+ kwargs["mode"] = mode
+
+ # call target filesystems open
+ self._mkcache()
+ if self.compression:
+ with self.fs._open(path, **kwargs) as f, open(fn, "wb") as f2:
+ if isinstance(f, AbstractBufferedFile):
+ # want no type of caching if just downloading whole thing
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
+ comp = (
+ infer_compression(path)
+ if self.compression == "infer"
+ else self.compression
+ )
+ f = compr[comp](f, mode="rb")
+ data = True
+ while data:
+ block = getattr(f, "blocksize", 5 * 2**20)
+ data = f.read(block)
+ f2.write(data)
+ else:
+ self.fs.get_file(path, fn)
+ self.save_cache()
+ return self._open(path, mode)
+
+
+class SimpleCacheFileSystem(WholeFileCacheFileSystem):
+ """Caches whole remote files on first access
+
+ This class is intended as a layer over any other file system, and
+ will make a local copy of each file accessed, so that all subsequent
+ reads are local. This implementation only copies whole files, and
+ does not keep any metadata about the download time or file details.
+ It is therefore safer to use in multi-threaded/concurrent situations.
+
+ This is the only of the caching filesystems that supports write: you will
+ be given a real local open file, and upon close and commit, it will be
+ uploaded to the target filesystem; the writability or the target URL is
+ not checked until that time.
+
+ """
+
+ protocol = "simplecache"
+ local_file = True
+ transaction_type = WriteCachedTransaction
+
+ def __init__(self, **kwargs):
+ kw = kwargs.copy()
+ for key in ["cache_check", "expiry_time", "check_files"]:
+ kw[key] = False
+ super().__init__(**kw)
+ for storage in self.storage:
+ if not os.path.exists(storage):
+ os.makedirs(storage, exist_ok=True)
+
+ def _check_file(self, path):
+ self._check_cache()
+ sha = self._mapper(path)
+ for storage in self.storage:
+ fn = os.path.join(storage, sha)
+ if os.path.exists(fn):
+ return fn
+
+ def save_cache(self):
+ pass
+
+ def load_cache(self):
+ pass
+
+ def pipe_file(self, path, value=None, **kwargs):
+ if self._intrans:
+ with self.open(path, "wb") as f:
+ f.write(value)
+ else:
+ super().pipe_file(path, value)
+
+ def ls(self, path, detail=True, **kwargs):
+ path = self._strip_protocol(path)
+ details = []
+ try:
+ details = self.fs.ls(
+ path, detail=True, **kwargs
+ ).copy() # don't edit original!
+ except FileNotFoundError as e:
+ ex = e
+ else:
+ ex = None
+ if self._intrans:
+ path1 = path.rstrip("/") + "/"
+ for f in self.transaction.files:
+ if f.path == path:
+ details.append(
+ {"name": path, "size": f.size or f.tell(), "type": "file"}
+ )
+ elif f.path.startswith(path1):
+ if f.path.count("/") == path1.count("/"):
+ details.append(
+ {"name": f.path, "size": f.size or f.tell(), "type": "file"}
+ )
+ else:
+ dname = "/".join(f.path.split("/")[: path1.count("/") + 1])
+ details.append({"name": dname, "size": 0, "type": "directory"})
+ if ex is not None and not details:
+ raise ex
+ if detail:
+ return details
+ return sorted(_["name"] for _ in details)
+
+ def info(self, path, **kwargs):
+ path = self._strip_protocol(path)
+ if self._intrans:
+ f = [_ for _ in self.transaction.files if _.path == path]
+ if f:
+ size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell()
+ return {"name": path, "size": size, "type": "file"}
+ f = any(_.path.startswith(path + "/") for _ in self.transaction.files)
+ if f:
+ return {"name": path, "size": 0, "type": "directory"}
+ return self.fs.info(path, **kwargs)
+
+ def pipe(self, path, value=None, **kwargs):
+ if isinstance(path, str):
+ self.pipe_file(self._strip_protocol(path), value, **kwargs)
+ elif isinstance(path, dict):
+ for k, v in path.items():
+ self.pipe_file(self._strip_protocol(k), v, **kwargs)
+ else:
+ raise ValueError("path must be str or dict")
+
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
+ logger.debug("async cat_file %s", path)
+ path = self._strip_protocol(path)
+ sha = self._mapper(path)
+ fn = self._check_file(path)
+
+ if not fn:
+ fn = os.path.join(self.storage[-1], sha)
+ await self.fs._get_file(path, fn, **kwargs)
+
+ with open(fn, "rb") as f: # noqa ASYNC230
+ if start:
+ f.seek(start)
+ size = -1 if end is None else end - f.tell()
+ return f.read(size)
+
+ async def _cat_ranges(
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
+ ):
+ logger.debug("async cat ranges %s", paths)
+ lpaths = []
+ rset = set()
+ download = []
+ rpaths = []
+ for p in paths:
+ fn = self._check_file(p)
+ if fn is None and p not in rset:
+ sha = self._mapper(p)
+ fn = os.path.join(self.storage[-1], sha)
+ download.append(fn)
+ rset.add(p)
+ rpaths.append(p)
+ lpaths.append(fn)
+ if download:
+ await self.fs._get(rpaths, download, on_error=on_error)
+
+ return LocalFileSystem().cat_ranges(
+ lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
+ )
+
+ def cat_ranges(
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
+ ):
+ logger.debug("cat ranges %s", paths)
+ lpaths = [self._check_file(p) for p in paths]
+ rpaths = [p for l, p in zip(lpaths, paths) if l is False]
+ lpaths = [l for l, p in zip(lpaths, paths) if l is False]
+ self.fs.get(rpaths, lpaths)
+ paths = [self._check_file(p) for p in paths]
+ return LocalFileSystem().cat_ranges(
+ paths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
+ )
+
+ def _open(self, path, mode="rb", **kwargs):
+ path = self._strip_protocol(path)
+ sha = self._mapper(path)
+
+ if "r" not in mode:
+ fn = os.path.join(self.storage[-1], sha)
+ user_specified_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ if k not in ["autocommit", "block_size", "cache_options"]
+ } # those were added by open()
+ return LocalTempFile(
+ self,
+ path,
+ mode=mode,
+ autocommit=not self._intrans,
+ fn=fn,
+ **user_specified_kwargs,
+ )
+ fn = self._check_file(path)
+ if fn:
+ return open(fn, mode)
+
+ fn = os.path.join(self.storage[-1], sha)
+ logger.debug("Copying %s to local cache", path)
+ kwargs["mode"] = mode
+
+ self._mkcache()
+ self._cache_size = None
+ if self.compression:
+ with self.fs._open(path, **kwargs) as f, open(fn, "wb") as f2:
+ if isinstance(f, AbstractBufferedFile):
+ # want no type of caching if just downloading whole thing
+ f.cache = BaseCache(0, f.cache.fetcher, f.size)
+ comp = (
+ infer_compression(path)
+ if self.compression == "infer"
+ else self.compression
+ )
+ f = compr[comp](f, mode="rb")
+ data = True
+ while data:
+ block = getattr(f, "blocksize", 5 * 2**20)
+ data = f.read(block)
+ f2.write(data)
+ else:
+ self.fs.get_file(path, fn)
+ return self._open(path, mode)
+
+
+class LocalTempFile:
+ """A temporary local file, which will be uploaded on commit"""
+
+ def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs):
+ self.fn = fn
+ self.fh = open(fn, mode)
+ self.mode = mode
+ if seek:
+ self.fh.seek(seek)
+ self.path = path
+ self.size = None
+ self.fs = fs
+ self.closed = False
+ self.autocommit = autocommit
+ self.kwargs = kwargs
+
+ def __reduce__(self):
+ # always open in r+b to allow continuing writing at a location
+ return (
+ LocalTempFile,
+ (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()),
+ )
+
+ def __enter__(self):
+ return self.fh
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.close()
+
+ def close(self):
+ # self.size = self.fh.tell()
+ if self.closed:
+ return
+ self.fh.close()
+ self.closed = True
+ if self.autocommit:
+ self.commit()
+
+ def discard(self):
+ self.fh.close()
+ os.remove(self.fn)
+
+ def commit(self):
+ self.fs.put(self.fn, self.path, **self.kwargs)
+ # we do not delete the local copy, it's still in the cache.
+
+ @property
+ def name(self):
+ return self.fn
+
+ def __repr__(self) -> str:
+ return f"LocalTempFile: {self.path}"
+
+ def __getattr__(self, item):
+ return getattr(self.fh, item)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dask.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dask.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e1276463db6866665e6a0fe114efc247971b57e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dask.py
@@ -0,0 +1,152 @@
+import dask
+from distributed.client import Client, _get_global_client
+from distributed.worker import Worker
+
+from fsspec import filesystem
+from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
+from fsspec.utils import infer_storage_options
+
+
+def _get_client(client):
+ if client is None:
+ return _get_global_client()
+ elif isinstance(client, Client):
+ return client
+ else:
+ # e.g., connection string
+ return Client(client)
+
+
+def _in_worker():
+ return bool(Worker._instances)
+
+
+class DaskWorkerFileSystem(AbstractFileSystem):
+ """View files accessible to a worker as any other remote file-system
+
+ When instances are run on the worker, uses the real filesystem. When
+ run on the client, they call the worker to provide information or data.
+
+ **Warning** this implementation is experimental, and read-only for now.
+ """
+
+ def __init__(
+ self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs
+ ):
+ super().__init__(**kwargs)
+ if not (fs is None) ^ (target_protocol is None):
+ raise ValueError(
+ "Please provide one of filesystem instance (fs) or"
+ " target_protocol, not both"
+ )
+ self.target_protocol = target_protocol
+ self.target_options = target_options
+ self.worker = None
+ self.client = client
+ self.fs = fs
+ self._determine_worker()
+
+ @staticmethod
+ def _get_kwargs_from_urls(path):
+ so = infer_storage_options(path)
+ if "host" in so and "port" in so:
+ return {"client": f"{so['host']}:{so['port']}"}
+ else:
+ return {}
+
+ def _determine_worker(self):
+ if _in_worker():
+ self.worker = True
+ if self.fs is None:
+ self.fs = filesystem(
+ self.target_protocol, **(self.target_options or {})
+ )
+ else:
+ self.worker = False
+ self.client = _get_client(self.client)
+ self.rfs = dask.delayed(self)
+
+ def mkdir(self, *args, **kwargs):
+ if self.worker:
+ self.fs.mkdir(*args, **kwargs)
+ else:
+ self.rfs.mkdir(*args, **kwargs).compute()
+
+ def rm(self, *args, **kwargs):
+ if self.worker:
+ self.fs.rm(*args, **kwargs)
+ else:
+ self.rfs.rm(*args, **kwargs).compute()
+
+ def copy(self, *args, **kwargs):
+ if self.worker:
+ self.fs.copy(*args, **kwargs)
+ else:
+ self.rfs.copy(*args, **kwargs).compute()
+
+ def mv(self, *args, **kwargs):
+ if self.worker:
+ self.fs.mv(*args, **kwargs)
+ else:
+ self.rfs.mv(*args, **kwargs).compute()
+
+ def ls(self, *args, **kwargs):
+ if self.worker:
+ return self.fs.ls(*args, **kwargs)
+ else:
+ return self.rfs.ls(*args, **kwargs).compute()
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ cache_options=None,
+ **kwargs,
+ ):
+ if self.worker:
+ return self.fs._open(
+ path,
+ mode=mode,
+ block_size=block_size,
+ autocommit=autocommit,
+ cache_options=cache_options,
+ **kwargs,
+ )
+ else:
+ return DaskFile(
+ fs=self,
+ path=path,
+ mode=mode,
+ block_size=block_size,
+ autocommit=autocommit,
+ cache_options=cache_options,
+ **kwargs,
+ )
+
+ def fetch_range(self, path, mode, start, end):
+ if self.worker:
+ with self._open(path, mode) as f:
+ f.seek(start)
+ return f.read(end - start)
+ else:
+ return self.rfs.fetch_range(path, mode, start, end).compute()
+
+
+class DaskFile(AbstractBufferedFile):
+ def __init__(self, mode="rb", **kwargs):
+ if mode != "rb":
+ raise ValueError('Remote dask files can only be opened in "rb" mode')
+ super().__init__(**kwargs)
+
+ def _upload_chunk(self, final=False):
+ pass
+
+ def _initiate_upload(self):
+ """Create remote file/upload"""
+ pass
+
+ def _fetch_range(self, start, end):
+ """Get the specified set of bytes from remote"""
+ return self.fs.fetch_range(self.path, self.mode, start, end)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/data.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/data.py
new file mode 100644
index 0000000000000000000000000000000000000000..519032305bed633f2ba8a6148076433caf81710b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/data.py
@@ -0,0 +1,58 @@
+import base64
+import io
+from typing import Optional
+from urllib.parse import unquote
+
+from fsspec import AbstractFileSystem
+
+
+class DataFileSystem(AbstractFileSystem):
+ """A handy decoder for data-URLs
+
+ Example
+ -------
+ >>> with fsspec.open("data:,Hello%2C%20World%21") as f:
+ ... print(f.read())
+ b"Hello, World!"
+
+ See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs
+ """
+
+ protocol = "data"
+
+ def __init__(self, **kwargs):
+ """No parameters for this filesystem"""
+ super().__init__(**kwargs)
+
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ pref, data = path.split(",", 1)
+ if pref.endswith("base64"):
+ return base64.b64decode(data)[start:end]
+ return unquote(data).encode()[start:end]
+
+ def info(self, path, **kwargs):
+ pref, name = path.split(",", 1)
+ data = self.cat_file(path)
+ mime = pref.split(":", 1)[1].split(";", 1)[0]
+ return {"name": name, "size": len(data), "type": "file", "mimetype": mime}
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ cache_options=None,
+ **kwargs,
+ ):
+ if "r" not in mode:
+ raise ValueError("Read only filesystem")
+ return io.BytesIO(self.cat_file(path))
+
+ @staticmethod
+ def encode(data: bytes, mime: Optional[str] = None):
+ """Format the given data into data-URL syntax
+
+ This version always base64 encodes, even when the data is ascii/url-safe.
+ """
+ return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dbfs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dbfs.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a7fc93d7389c894ecb5fc6267ce20abe4087068
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dbfs.py
@@ -0,0 +1,496 @@
+from __future__ import annotations
+
+import base64
+import urllib
+
+import requests
+from requests.adapters import HTTPAdapter, Retry
+from typing_extensions import override
+
+from fsspec import AbstractFileSystem
+from fsspec.spec import AbstractBufferedFile
+
+
+class DatabricksException(Exception):
+ """
+ Helper class for exceptions raised in this module.
+ """
+
+ def __init__(self, error_code, message, details=None):
+ """Create a new DatabricksException"""
+ super().__init__(message)
+
+ self.error_code = error_code
+ self.message = message
+ self.details = details
+
+
+class DatabricksFileSystem(AbstractFileSystem):
+ """
+ Get access to the Databricks filesystem implementation over HTTP.
+ Can be used inside and outside of a databricks cluster.
+ """
+
+ def __init__(self, instance, token, **kwargs):
+ """
+ Create a new DatabricksFileSystem.
+
+ Parameters
+ ----------
+ instance: str
+ The instance URL of the databricks cluster.
+ For example for an Azure databricks cluster, this
+ has the form adb-..azuredatabricks.net.
+ token: str
+ Your personal token. Find out more
+ here: https://docs.databricks.com/dev-tools/api/latest/authentication.html
+ """
+ self.instance = instance
+ self.token = token
+ self.session = requests.Session()
+ self.retries = Retry(
+ total=10,
+ backoff_factor=0.05,
+ status_forcelist=[408, 429, 500, 502, 503, 504],
+ )
+
+ self.session.mount("https://", HTTPAdapter(max_retries=self.retries))
+ self.session.headers.update({"Authorization": f"Bearer {self.token}"})
+
+ super().__init__(**kwargs)
+
+ @override
+ def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None:
+ """Check cache for listing
+
+ Returns listing, if found (may be empty list for a directory that
+ exists but contains nothing), None if not in cache.
+ """
+ self.dircache.pop(path.rstrip("/"), None)
+
+ parent = self._parent(path)
+ if parent in self.dircache:
+ for entry in self.dircache[parent]:
+ if entry["name"] == path.rstrip("/"):
+ if entry["type"] != "directory":
+ return [entry]
+ return []
+ raise FileNotFoundError(path)
+
+ def ls(self, path, detail=True, **kwargs):
+ """
+ List the contents of the given path.
+
+ Parameters
+ ----------
+ path: str
+ Absolute path
+ detail: bool
+ Return not only the list of filenames,
+ but also additional information on file sizes
+ and types.
+ """
+ try:
+ out = self._ls_from_cache(path)
+ except FileNotFoundError:
+ # This happens if the `path`'s parent was cached, but `path` is not
+ # there. This suggests that `path` is new since the parent was
+ # cached. Attempt to invalidate parent's cache before continuing.
+ self.dircache.pop(self._parent(path), None)
+ out = None
+
+ if not out:
+ try:
+ r = self._send_to_api(
+ method="get", endpoint="list", json={"path": path}
+ )
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
+ raise FileNotFoundError(e.message) from e
+
+ raise
+ files = r.get("files", [])
+ out = [
+ {
+ "name": o["path"],
+ "type": "directory" if o["is_dir"] else "file",
+ "size": o["file_size"],
+ }
+ for o in files
+ ]
+ self.dircache[path] = out
+
+ if detail:
+ return out
+ return [o["name"] for o in out]
+
+ def makedirs(self, path, exist_ok=True):
+ """
+ Create a given absolute path and all of its parents.
+
+ Parameters
+ ----------
+ path: str
+ Absolute path to create
+ exist_ok: bool
+ If false, checks if the folder
+ exists before creating it (and raises an
+ Exception if this is the case)
+ """
+ if not exist_ok:
+ try:
+ # If the following succeeds, the path is already present
+ self._send_to_api(
+ method="get", endpoint="get-status", json={"path": path}
+ )
+ raise FileExistsError(f"Path {path} already exists")
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
+ pass
+
+ try:
+ self._send_to_api(method="post", endpoint="mkdirs", json={"path": path})
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_ALREADY_EXISTS":
+ raise FileExistsError(e.message) from e
+
+ raise
+ self.invalidate_cache(self._parent(path))
+
+ def mkdir(self, path, create_parents=True, **kwargs):
+ """
+ Create a given absolute path and all of its parents.
+
+ Parameters
+ ----------
+ path: str
+ Absolute path to create
+ create_parents: bool
+ Whether to create all parents or not.
+ "False" is not implemented so far.
+ """
+ if not create_parents:
+ raise NotImplementedError
+
+ self.mkdirs(path, **kwargs)
+
+ def rm(self, path, recursive=False, **kwargs):
+ """
+ Remove the file or folder at the given absolute path.
+
+ Parameters
+ ----------
+ path: str
+ Absolute path what to remove
+ recursive: bool
+ Recursively delete all files in a folder.
+ """
+ try:
+ self._send_to_api(
+ method="post",
+ endpoint="delete",
+ json={"path": path, "recursive": recursive},
+ )
+ except DatabricksException as e:
+ # This is not really an exception, it just means
+ # not everything was deleted so far
+ if e.error_code == "PARTIAL_DELETE":
+ self.rm(path=path, recursive=recursive)
+ elif e.error_code == "IO_ERROR":
+ # Using the same exception as the os module would use here
+ raise OSError(e.message) from e
+
+ raise
+ self.invalidate_cache(self._parent(path))
+
+ def mv(
+ self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs
+ ):
+ """
+ Move a source to a destination path.
+
+ A note from the original [databricks API manual]
+ (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move).
+
+ When moving a large number of files the API call will time out after
+ approximately 60s, potentially resulting in partially moved data.
+ Therefore, for operations that move more than 10k files, we strongly
+ discourage using the DBFS REST API.
+
+ Parameters
+ ----------
+ source_path: str
+ From where to move (absolute path)
+ destination_path: str
+ To where to move (absolute path)
+ recursive: bool
+ Not implemented to far.
+ maxdepth:
+ Not implemented to far.
+ """
+ if recursive:
+ raise NotImplementedError
+ if maxdepth:
+ raise NotImplementedError
+
+ try:
+ self._send_to_api(
+ method="post",
+ endpoint="move",
+ json={"source_path": source_path, "destination_path": destination_path},
+ )
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
+ raise FileNotFoundError(e.message) from e
+ elif e.error_code == "RESOURCE_ALREADY_EXISTS":
+ raise FileExistsError(e.message) from e
+
+ raise
+ self.invalidate_cache(self._parent(source_path))
+ self.invalidate_cache(self._parent(destination_path))
+
+ def _open(self, path, mode="rb", block_size="default", **kwargs):
+ """
+ Overwrite the base class method to make sure to create a DBFile.
+ All arguments are copied from the base method.
+
+ Only the default blocksize is allowed.
+ """
+ return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs)
+
+ def _send_to_api(self, method, endpoint, json):
+ """
+ Send the given json to the DBFS API
+ using a get or post request (specified by the argument `method`).
+
+ Parameters
+ ----------
+ method: str
+ Which http method to use for communication; "get" or "post".
+ endpoint: str
+ Where to send the request to (last part of the API URL)
+ json: dict
+ Dictionary of information to send
+ """
+ if method == "post":
+ session_call = self.session.post
+ elif method == "get":
+ session_call = self.session.get
+ else:
+ raise ValueError(f"Do not understand method {method}")
+
+ url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint)
+
+ r = session_call(url, json=json)
+
+ # The DBFS API will return a json, also in case of an exception.
+ # We want to preserve this information as good as possible.
+ try:
+ r.raise_for_status()
+ except requests.HTTPError as e:
+ # try to extract json error message
+ # if that fails, fall back to the original exception
+ try:
+ exception_json = e.response.json()
+ except Exception:
+ raise e from None
+
+ raise DatabricksException(**exception_json) from e
+
+ return r.json()
+
+ def _create_handle(self, path, overwrite=True):
+ """
+ Internal function to create a handle, which can be used to
+ write blocks of a file to DBFS.
+ A handle has a unique identifier which needs to be passed
+ whenever written during this transaction.
+ The handle is active for 10 minutes - after that a new
+ write transaction needs to be created.
+ Make sure to close the handle after you are finished.
+
+ Parameters
+ ----------
+ path: str
+ Absolute path for this file.
+ overwrite: bool
+ If a file already exist at this location, either overwrite
+ it or raise an exception.
+ """
+ try:
+ r = self._send_to_api(
+ method="post",
+ endpoint="create",
+ json={"path": path, "overwrite": overwrite},
+ )
+ return r["handle"]
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_ALREADY_EXISTS":
+ raise FileExistsError(e.message) from e
+
+ raise
+
+ def _close_handle(self, handle):
+ """
+ Close a handle, which was opened by :func:`_create_handle`.
+
+ Parameters
+ ----------
+ handle: str
+ Which handle to close.
+ """
+ try:
+ self._send_to_api(method="post", endpoint="close", json={"handle": handle})
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
+ raise FileNotFoundError(e.message) from e
+
+ raise
+
+ def _add_data(self, handle, data):
+ """
+ Upload data to an already opened file handle
+ (opened by :func:`_create_handle`).
+ The maximal allowed data size is 1MB after
+ conversion to base64.
+ Remember to close the handle when you are finished.
+
+ Parameters
+ ----------
+ handle: str
+ Which handle to upload data to.
+ data: bytes
+ Block of data to add to the handle.
+ """
+ data = base64.b64encode(data).decode()
+ try:
+ self._send_to_api(
+ method="post",
+ endpoint="add-block",
+ json={"handle": handle, "data": data},
+ )
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
+ raise FileNotFoundError(e.message) from e
+ elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED":
+ raise ValueError(e.message) from e
+
+ raise
+
+ def _get_data(self, path, start, end):
+ """
+ Download data in bytes from a given absolute path in a block
+ from [start, start+length].
+ The maximum number of allowed bytes to read is 1MB.
+
+ Parameters
+ ----------
+ path: str
+ Absolute path to download data from
+ start: int
+ Start position of the block
+ end: int
+ End position of the block
+ """
+ try:
+ r = self._send_to_api(
+ method="get",
+ endpoint="read",
+ json={"path": path, "offset": start, "length": end - start},
+ )
+ return base64.b64decode(r["data"])
+ except DatabricksException as e:
+ if e.error_code == "RESOURCE_DOES_NOT_EXIST":
+ raise FileNotFoundError(e.message) from e
+ elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]:
+ raise ValueError(e.message) from e
+
+ raise
+
+ def invalidate_cache(self, path=None):
+ if path is None:
+ self.dircache.clear()
+ else:
+ self.dircache.pop(path, None)
+ super().invalidate_cache(path)
+
+
+class DatabricksFile(AbstractBufferedFile):
+ """
+ Helper class for files referenced in the DatabricksFileSystem.
+ """
+
+ DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size
+
+ def __init__(
+ self,
+ fs,
+ path,
+ mode="rb",
+ block_size="default",
+ autocommit=True,
+ cache_type="readahead",
+ cache_options=None,
+ **kwargs,
+ ):
+ """
+ Create a new instance of the DatabricksFile.
+
+ The blocksize needs to be the default one.
+ """
+ if block_size is None or block_size == "default":
+ block_size = self.DEFAULT_BLOCK_SIZE
+
+ assert block_size == self.DEFAULT_BLOCK_SIZE, (
+ f"Only the default block size is allowed, not {block_size}"
+ )
+
+ super().__init__(
+ fs,
+ path,
+ mode=mode,
+ block_size=block_size,
+ autocommit=autocommit,
+ cache_type=cache_type,
+ cache_options=cache_options or {},
+ **kwargs,
+ )
+
+ def _initiate_upload(self):
+ """Internal function to start a file upload"""
+ self.handle = self.fs._create_handle(self.path)
+
+ def _upload_chunk(self, final=False):
+ """Internal function to add a chunk of data to a started upload"""
+ self.buffer.seek(0)
+ data = self.buffer.getvalue()
+
+ data_chunks = [
+ data[start:end] for start, end in self._to_sized_blocks(len(data))
+ ]
+
+ for data_chunk in data_chunks:
+ self.fs._add_data(handle=self.handle, data=data_chunk)
+
+ if final:
+ self.fs._close_handle(handle=self.handle)
+ return True
+
+ def _fetch_range(self, start, end):
+ """Internal function to download a block of data"""
+ return_buffer = b""
+ length = end - start
+ for chunk_start, chunk_end in self._to_sized_blocks(length, start):
+ return_buffer += self.fs._get_data(
+ path=self.path, start=chunk_start, end=chunk_end
+ )
+
+ return return_buffer
+
+ def _to_sized_blocks(self, length, start=0):
+ """Helper function to split a range from 0 to total_length into blocksizes"""
+ end = start + length
+ for data_chunk in range(start, end, self.blocksize):
+ data_start = data_chunk
+ data_end = min(end, data_chunk + self.blocksize)
+ yield data_start, data_end
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dirfs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dirfs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0623b82fc61ed4780fdbc1d69680f2b96f2b9f3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/dirfs.py
@@ -0,0 +1,388 @@
+from .. import filesystem
+from ..asyn import AsyncFileSystem
+
+
+class DirFileSystem(AsyncFileSystem):
+ """Directory prefix filesystem
+
+ The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with
+ is relative to the `path`. After performing the necessary paths operation it
+ delegates everything to the wrapped filesystem.
+ """
+
+ protocol = "dir"
+
+ def __init__(
+ self,
+ path=None,
+ fs=None,
+ fo=None,
+ target_protocol=None,
+ target_options=None,
+ **storage_options,
+ ):
+ """
+ Parameters
+ ----------
+ path: str
+ Path to the directory.
+ fs: AbstractFileSystem
+ An instantiated filesystem to wrap.
+ target_protocol, target_options:
+ if fs is none, construct it from these
+ fo: str
+ Alternate for path; do not provide both
+ """
+ super().__init__(**storage_options)
+ if fs is None:
+ fs = filesystem(protocol=target_protocol, **(target_options or {}))
+ path = path or fo
+
+ if self.asynchronous and not fs.async_impl:
+ raise ValueError("can't use asynchronous with non-async fs")
+
+ if fs.async_impl and self.asynchronous != fs.asynchronous:
+ raise ValueError("both dirfs and fs should be in the same sync/async mode")
+
+ self.path = fs._strip_protocol(path)
+ self.fs = fs
+
+ def _join(self, path):
+ if isinstance(path, str):
+ if not self.path:
+ return path
+ if not path:
+ return self.path
+ return self.fs.sep.join((self.path, self._strip_protocol(path)))
+ if isinstance(path, dict):
+ return {self._join(_path): value for _path, value in path.items()}
+ return [self._join(_path) for _path in path]
+
+ def _relpath(self, path):
+ if isinstance(path, str):
+ if not self.path:
+ return path
+ # We need to account for S3FileSystem returning paths that do not
+ # start with a '/'
+ if path == self.path or (
+ self.path.startswith(self.fs.sep) and path == self.path[1:]
+ ):
+ return ""
+ prefix = self.path + self.fs.sep
+ if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep):
+ prefix = prefix[1:]
+ assert path.startswith(prefix)
+ return path[len(prefix) :]
+ return [self._relpath(_path) for _path in path]
+
+ # Wrappers below
+
+ @property
+ def sep(self):
+ return self.fs.sep
+
+ async def set_session(self, *args, **kwargs):
+ return await self.fs.set_session(*args, **kwargs)
+
+ async def _rm_file(self, path, **kwargs):
+ return await self.fs._rm_file(self._join(path), **kwargs)
+
+ def rm_file(self, path, **kwargs):
+ return self.fs.rm_file(self._join(path), **kwargs)
+
+ async def _rm(self, path, *args, **kwargs):
+ return await self.fs._rm(self._join(path), *args, **kwargs)
+
+ def rm(self, path, *args, **kwargs):
+ return self.fs.rm(self._join(path), *args, **kwargs)
+
+ async def _cp_file(self, path1, path2, **kwargs):
+ return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs)
+
+ def cp_file(self, path1, path2, **kwargs):
+ return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs)
+
+ async def _copy(
+ self,
+ path1,
+ path2,
+ *args,
+ **kwargs,
+ ):
+ return await self.fs._copy(
+ self._join(path1),
+ self._join(path2),
+ *args,
+ **kwargs,
+ )
+
+ def copy(self, path1, path2, *args, **kwargs):
+ return self.fs.copy(
+ self._join(path1),
+ self._join(path2),
+ *args,
+ **kwargs,
+ )
+
+ async def _pipe(self, path, *args, **kwargs):
+ return await self.fs._pipe(self._join(path), *args, **kwargs)
+
+ def pipe(self, path, *args, **kwargs):
+ return self.fs.pipe(self._join(path), *args, **kwargs)
+
+ async def _pipe_file(self, path, *args, **kwargs):
+ return await self.fs._pipe_file(self._join(path), *args, **kwargs)
+
+ def pipe_file(self, path, *args, **kwargs):
+ return self.fs.pipe_file(self._join(path), *args, **kwargs)
+
+ async def _cat_file(self, path, *args, **kwargs):
+ return await self.fs._cat_file(self._join(path), *args, **kwargs)
+
+ def cat_file(self, path, *args, **kwargs):
+ return self.fs.cat_file(self._join(path), *args, **kwargs)
+
+ async def _cat(self, path, *args, **kwargs):
+ ret = await self.fs._cat(
+ self._join(path),
+ *args,
+ **kwargs,
+ )
+
+ if isinstance(ret, dict):
+ return {self._relpath(key): value for key, value in ret.items()}
+
+ return ret
+
+ def cat(self, path, *args, **kwargs):
+ ret = self.fs.cat(
+ self._join(path),
+ *args,
+ **kwargs,
+ )
+
+ if isinstance(ret, dict):
+ return {self._relpath(key): value for key, value in ret.items()}
+
+ return ret
+
+ async def _put_file(self, lpath, rpath, **kwargs):
+ return await self.fs._put_file(lpath, self._join(rpath), **kwargs)
+
+ def put_file(self, lpath, rpath, **kwargs):
+ return self.fs.put_file(lpath, self._join(rpath), **kwargs)
+
+ async def _put(
+ self,
+ lpath,
+ rpath,
+ *args,
+ **kwargs,
+ ):
+ return await self.fs._put(
+ lpath,
+ self._join(rpath),
+ *args,
+ **kwargs,
+ )
+
+ def put(self, lpath, rpath, *args, **kwargs):
+ return self.fs.put(
+ lpath,
+ self._join(rpath),
+ *args,
+ **kwargs,
+ )
+
+ async def _get_file(self, rpath, lpath, **kwargs):
+ return await self.fs._get_file(self._join(rpath), lpath, **kwargs)
+
+ def get_file(self, rpath, lpath, **kwargs):
+ return self.fs.get_file(self._join(rpath), lpath, **kwargs)
+
+ async def _get(self, rpath, *args, **kwargs):
+ return await self.fs._get(self._join(rpath), *args, **kwargs)
+
+ def get(self, rpath, *args, **kwargs):
+ return self.fs.get(self._join(rpath), *args, **kwargs)
+
+ async def _isfile(self, path):
+ return await self.fs._isfile(self._join(path))
+
+ def isfile(self, path):
+ return self.fs.isfile(self._join(path))
+
+ async def _isdir(self, path):
+ return await self.fs._isdir(self._join(path))
+
+ def isdir(self, path):
+ return self.fs.isdir(self._join(path))
+
+ async def _size(self, path):
+ return await self.fs._size(self._join(path))
+
+ def size(self, path):
+ return self.fs.size(self._join(path))
+
+ async def _exists(self, path):
+ return await self.fs._exists(self._join(path))
+
+ def exists(self, path):
+ return self.fs.exists(self._join(path))
+
+ async def _info(self, path, **kwargs):
+ info = await self.fs._info(self._join(path), **kwargs)
+ info = info.copy()
+ info["name"] = self._relpath(info["name"])
+ return info
+
+ def info(self, path, **kwargs):
+ info = self.fs.info(self._join(path), **kwargs)
+ info = info.copy()
+ info["name"] = self._relpath(info["name"])
+ return info
+
+ async def _ls(self, path, detail=True, **kwargs):
+ ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy()
+ if detail:
+ out = []
+ for entry in ret:
+ entry = entry.copy()
+ entry["name"] = self._relpath(entry["name"])
+ out.append(entry)
+ return out
+
+ return self._relpath(ret)
+
+ def ls(self, path, detail=True, **kwargs):
+ ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy()
+ if detail:
+ out = []
+ for entry in ret:
+ entry = entry.copy()
+ entry["name"] = self._relpath(entry["name"])
+ out.append(entry)
+ return out
+
+ return self._relpath(ret)
+
+ async def _walk(self, path, *args, **kwargs):
+ async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs):
+ yield self._relpath(root), dirs, files
+
+ def walk(self, path, *args, **kwargs):
+ for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs):
+ yield self._relpath(root), dirs, files
+
+ async def _glob(self, path, **kwargs):
+ detail = kwargs.get("detail", False)
+ ret = await self.fs._glob(self._join(path), **kwargs)
+ if detail:
+ return {self._relpath(path): info for path, info in ret.items()}
+ return self._relpath(ret)
+
+ def glob(self, path, **kwargs):
+ detail = kwargs.get("detail", False)
+ ret = self.fs.glob(self._join(path), **kwargs)
+ if detail:
+ return {self._relpath(path): info for path, info in ret.items()}
+ return self._relpath(ret)
+
+ async def _du(self, path, *args, **kwargs):
+ total = kwargs.get("total", True)
+ ret = await self.fs._du(self._join(path), *args, **kwargs)
+ if total:
+ return ret
+
+ return {self._relpath(path): size for path, size in ret.items()}
+
+ def du(self, path, *args, **kwargs):
+ total = kwargs.get("total", True)
+ ret = self.fs.du(self._join(path), *args, **kwargs)
+ if total:
+ return ret
+
+ return {self._relpath(path): size for path, size in ret.items()}
+
+ async def _find(self, path, *args, **kwargs):
+ detail = kwargs.get("detail", False)
+ ret = await self.fs._find(self._join(path), *args, **kwargs)
+ if detail:
+ return {self._relpath(path): info for path, info in ret.items()}
+ return self._relpath(ret)
+
+ def find(self, path, *args, **kwargs):
+ detail = kwargs.get("detail", False)
+ ret = self.fs.find(self._join(path), *args, **kwargs)
+ if detail:
+ return {self._relpath(path): info for path, info in ret.items()}
+ return self._relpath(ret)
+
+ async def _expand_path(self, path, *args, **kwargs):
+ return self._relpath(
+ await self.fs._expand_path(self._join(path), *args, **kwargs)
+ )
+
+ def expand_path(self, path, *args, **kwargs):
+ return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs))
+
+ async def _mkdir(self, path, *args, **kwargs):
+ return await self.fs._mkdir(self._join(path), *args, **kwargs)
+
+ def mkdir(self, path, *args, **kwargs):
+ return self.fs.mkdir(self._join(path), *args, **kwargs)
+
+ async def _makedirs(self, path, *args, **kwargs):
+ return await self.fs._makedirs(self._join(path), *args, **kwargs)
+
+ def makedirs(self, path, *args, **kwargs):
+ return self.fs.makedirs(self._join(path), *args, **kwargs)
+
+ def rmdir(self, path):
+ return self.fs.rmdir(self._join(path))
+
+ def mv(self, path1, path2, **kwargs):
+ return self.fs.mv(
+ self._join(path1),
+ self._join(path2),
+ **kwargs,
+ )
+
+ def touch(self, path, **kwargs):
+ return self.fs.touch(self._join(path), **kwargs)
+
+ def created(self, path):
+ return self.fs.created(self._join(path))
+
+ def modified(self, path):
+ return self.fs.modified(self._join(path))
+
+ def sign(self, path, *args, **kwargs):
+ return self.fs.sign(self._join(path), *args, **kwargs)
+
+ def __repr__(self):
+ return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})"
+
+ def open(
+ self,
+ path,
+ *args,
+ **kwargs,
+ ):
+ return self.fs.open(
+ self._join(path),
+ *args,
+ **kwargs,
+ )
+
+ async def open_async(
+ self,
+ path,
+ *args,
+ **kwargs,
+ ):
+ return await self.fs.open_async(
+ self._join(path),
+ *args,
+ **kwargs,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/ftp.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/ftp.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3db22b04a00ddf12582253ec19b2938c794c1da
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/ftp.py
@@ -0,0 +1,387 @@
+import os
+import uuid
+from ftplib import FTP, FTP_TLS, Error, error_perm
+from typing import Any
+
+from ..spec import AbstractBufferedFile, AbstractFileSystem
+from ..utils import infer_storage_options, isfilelike
+
+
+class FTPFileSystem(AbstractFileSystem):
+ """A filesystem over classic FTP"""
+
+ root_marker = "/"
+ cachable = False
+ protocol = "ftp"
+
+ def __init__(
+ self,
+ host,
+ port=21,
+ username=None,
+ password=None,
+ acct=None,
+ block_size=None,
+ tempdir=None,
+ timeout=30,
+ encoding="utf-8",
+ tls=False,
+ **kwargs,
+ ):
+ """
+ You can use _get_kwargs_from_urls to get some kwargs from
+ a reasonable FTP url.
+
+ Authentication will be anonymous if username/password are not
+ given.
+
+ Parameters
+ ----------
+ host: str
+ The remote server name/ip to connect to
+ port: int
+ Port to connect with
+ username: str or None
+ If authenticating, the user's identifier
+ password: str of None
+ User's password on the server, if using
+ acct: str or None
+ Some servers also need an "account" string for auth
+ block_size: int or None
+ If given, the read-ahead or write buffer size.
+ tempdir: str
+ Directory on remote to put temporary files when in a transaction
+ timeout: int
+ Timeout of the ftp connection in seconds
+ encoding: str
+ Encoding to use for directories and filenames in FTP connection
+ tls: bool
+ Use FTP-TLS, by default False
+ """
+ super().__init__(**kwargs)
+ self.host = host
+ self.port = port
+ self.tempdir = tempdir or "/tmp"
+ self.cred = username or "", password or "", acct or ""
+ self.timeout = timeout
+ self.encoding = encoding
+ if block_size is not None:
+ self.blocksize = block_size
+ else:
+ self.blocksize = 2**16
+ self.tls = tls
+ self._connect()
+ if self.tls:
+ self.ftp.prot_p()
+
+ def _connect(self):
+ if self.tls:
+ ftp_cls = FTP_TLS
+ else:
+ ftp_cls = FTP
+ self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding)
+ self.ftp.connect(self.host, self.port)
+ self.ftp.login(*self.cred)
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/")
+
+ @staticmethod
+ def _get_kwargs_from_urls(urlpath):
+ out = infer_storage_options(urlpath)
+ out.pop("path", None)
+ out.pop("protocol", None)
+ return out
+
+ def ls(self, path, detail=True, **kwargs):
+ path = self._strip_protocol(path)
+ out = []
+ if path not in self.dircache:
+ try:
+ try:
+ out = [
+ (fn, details)
+ for (fn, details) in self.ftp.mlsd(path)
+ if fn not in [".", ".."]
+ and details["type"] not in ["pdir", "cdir"]
+ ]
+ except error_perm:
+ out = _mlsd2(self.ftp, path) # Not platform independent
+ for fn, details in out:
+ details["name"] = "/".join(
+ ["" if path == "/" else path, fn.lstrip("/")]
+ )
+ if details["type"] == "file":
+ details["size"] = int(details["size"])
+ else:
+ details["size"] = 0
+ if details["type"] == "dir":
+ details["type"] = "directory"
+ self.dircache[path] = out
+ except Error:
+ try:
+ info = self.info(path)
+ if info["type"] == "file":
+ out = [(path, info)]
+ except (Error, IndexError) as exc:
+ raise FileNotFoundError(path) from exc
+ files = self.dircache.get(path, out)
+ if not detail:
+ return sorted([fn for fn, details in files])
+ return [details for fn, details in files]
+
+ def info(self, path, **kwargs):
+ # implement with direct method
+ path = self._strip_protocol(path)
+ if path == "/":
+ # special case, since this dir has no real entry
+ return {"name": "/", "size": 0, "type": "directory"}
+ files = self.ls(self._parent(path).lstrip("/"), True)
+ try:
+ out = next(f for f in files if f["name"] == path)
+ except StopIteration as exc:
+ raise FileNotFoundError(path) from exc
+ return out
+
+ def get_file(self, rpath, lpath, **kwargs):
+ if self.isdir(rpath):
+ if not os.path.exists(lpath):
+ os.mkdir(lpath)
+ return
+ if isfilelike(lpath):
+ outfile = lpath
+ else:
+ outfile = open(lpath, "wb")
+
+ def cb(x):
+ outfile.write(x)
+
+ self.ftp.retrbinary(
+ f"RETR {rpath}",
+ blocksize=self.blocksize,
+ callback=cb,
+ )
+ if not isfilelike(lpath):
+ outfile.close()
+
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ if end is not None:
+ return super().cat_file(path, start, end, **kwargs)
+ out = []
+
+ def cb(x):
+ out.append(x)
+
+ try:
+ self.ftp.retrbinary(
+ f"RETR {path}",
+ blocksize=self.blocksize,
+ rest=start,
+ callback=cb,
+ )
+ except (Error, error_perm) as orig_exc:
+ raise FileNotFoundError(path) from orig_exc
+ return b"".join(out)
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ cache_options=None,
+ autocommit=True,
+ **kwargs,
+ ):
+ path = self._strip_protocol(path)
+ block_size = block_size or self.blocksize
+ return FTPFile(
+ self,
+ path,
+ mode=mode,
+ block_size=block_size,
+ tempdir=self.tempdir,
+ autocommit=autocommit,
+ cache_options=cache_options,
+ )
+
+ def _rm(self, path):
+ path = self._strip_protocol(path)
+ self.ftp.delete(path)
+ self.invalidate_cache(self._parent(path))
+
+ def rm(self, path, recursive=False, maxdepth=None):
+ paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
+ for p in reversed(paths):
+ if self.isfile(p):
+ self.rm_file(p)
+ else:
+ self.rmdir(p)
+
+ def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None:
+ path = self._strip_protocol(path)
+ parent = self._parent(path)
+ if parent != self.root_marker and not self.exists(parent) and create_parents:
+ self.mkdir(parent, create_parents=create_parents)
+
+ self.ftp.mkd(path)
+ self.invalidate_cache(self._parent(path))
+
+ def makedirs(self, path: str, exist_ok: bool = False) -> None:
+ path = self._strip_protocol(path)
+ if self.exists(path):
+ # NB: "/" does not "exist" as it has no directory entry
+ if not exist_ok:
+ raise FileExistsError(f"{path} exists without `exist_ok`")
+ # exists_ok=True -> no-op
+ else:
+ self.mkdir(path, create_parents=True)
+
+ def rmdir(self, path):
+ path = self._strip_protocol(path)
+ self.ftp.rmd(path)
+ self.invalidate_cache(self._parent(path))
+
+ def mv(self, path1, path2, **kwargs):
+ path1 = self._strip_protocol(path1)
+ path2 = self._strip_protocol(path2)
+ self.ftp.rename(path1, path2)
+ self.invalidate_cache(self._parent(path1))
+ self.invalidate_cache(self._parent(path2))
+
+ def __del__(self):
+ self.ftp.close()
+
+ def invalidate_cache(self, path=None):
+ if path is None:
+ self.dircache.clear()
+ else:
+ self.dircache.pop(path, None)
+ super().invalidate_cache(path)
+
+
+class TransferDone(Exception):
+ """Internal exception to break out of transfer"""
+
+ pass
+
+
+class FTPFile(AbstractBufferedFile):
+ """Interact with a remote FTP file with read/write buffering"""
+
+ def __init__(
+ self,
+ fs,
+ path,
+ mode="rb",
+ block_size="default",
+ autocommit=True,
+ cache_type="readahead",
+ cache_options=None,
+ **kwargs,
+ ):
+ super().__init__(
+ fs,
+ path,
+ mode=mode,
+ block_size=block_size,
+ autocommit=autocommit,
+ cache_type=cache_type,
+ cache_options=cache_options,
+ **kwargs,
+ )
+ if not autocommit:
+ self.target = self.path
+ self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())])
+
+ def commit(self):
+ self.fs.mv(self.path, self.target)
+
+ def discard(self):
+ self.fs.rm(self.path)
+
+ def _fetch_range(self, start, end):
+ """Get bytes between given byte limits
+
+ Implemented by raising an exception in the fetch callback when the
+ number of bytes received reaches the requested amount.
+
+ Will fail if the server does not respect the REST command on
+ retrieve requests.
+ """
+ out = []
+ total = [0]
+
+ def callback(x):
+ total[0] += len(x)
+ if total[0] > end - start:
+ out.append(x[: (end - start) - total[0]])
+ if end < self.size:
+ raise TransferDone
+ else:
+ out.append(x)
+
+ if total[0] == end - start and end < self.size:
+ raise TransferDone
+
+ try:
+ self.fs.ftp.retrbinary(
+ f"RETR {self.path}",
+ blocksize=self.blocksize,
+ rest=start,
+ callback=callback,
+ )
+ except TransferDone:
+ try:
+ # stop transfer, we got enough bytes for this block
+ self.fs.ftp.abort()
+ self.fs.ftp.getmultiline()
+ except Error:
+ self.fs._connect()
+
+ return b"".join(out)
+
+ def _upload_chunk(self, final=False):
+ self.buffer.seek(0)
+ self.fs.ftp.storbinary(
+ f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset
+ )
+ return True
+
+
+def _mlsd2(ftp, path="."):
+ """
+ Fall back to using `dir` instead of `mlsd` if not supported.
+
+ This parses a Linux style `ls -l` response to `dir`, but the response may
+ be platform dependent.
+
+ Parameters
+ ----------
+ ftp: ftplib.FTP
+ path: str
+ Expects to be given path, but defaults to ".".
+ """
+ lines = []
+ minfo = []
+ ftp.dir(path, lines.append)
+ for line in lines:
+ split_line = line.split()
+ if len(split_line) < 9:
+ continue
+ this = (
+ split_line[-1],
+ {
+ "modify": " ".join(split_line[5:8]),
+ "unix.owner": split_line[2],
+ "unix.group": split_line[3],
+ "unix.mode": split_line[0],
+ "size": split_line[4],
+ },
+ )
+ if this[1]["unix.mode"][0] == "d":
+ this[1]["type"] = "dir"
+ else:
+ this[1]["type"] = "file"
+ minfo.append(this)
+ return minfo
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/gist.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/gist.py
new file mode 100644
index 0000000000000000000000000000000000000000..74117b544b02108fd2a7be06c716df477481ed47
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/gist.py
@@ -0,0 +1,232 @@
+import requests
+
+from ..spec import AbstractFileSystem
+from ..utils import infer_storage_options
+from .memory import MemoryFile
+
+
+class GistFileSystem(AbstractFileSystem):
+ """
+ Interface to files in a single GitHub Gist.
+
+ Provides read-only access to a gist's files. Gists do not contain
+ subdirectories, so file listing is straightforward.
+
+ Parameters
+ ----------
+ gist_id : str
+ The ID of the gist you want to access (the long hex value from the URL).
+ filenames : list[str] (optional)
+ If provided, only make a file system representing these files, and do not fetch
+ the list of all files for this gist.
+ sha : str (optional)
+ If provided, fetch a particular revision of the gist. If omitted,
+ the latest revision is used.
+ username : str (optional)
+ GitHub username for authentication (required if token is given).
+ token : str (optional)
+ GitHub personal access token (required if username is given).
+ timeout : (float, float) or float, optional
+ Connect and read timeouts for requests (default 60s each).
+ kwargs : dict
+ Stored on `self.request_kw` and passed to `requests.get` when fetching Gist
+ metadata or reading ("opening") a file.
+ """
+
+ protocol = "gist"
+ gist_url = "https://api.github.com/gists/{gist_id}"
+ gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}"
+
+ def __init__(
+ self,
+ gist_id,
+ filenames=None,
+ sha=None,
+ username=None,
+ token=None,
+ timeout=None,
+ **kwargs,
+ ):
+ super().__init__()
+ self.gist_id = gist_id
+ self.filenames = filenames
+ self.sha = sha # revision of the gist (optional)
+ if (username is None) ^ (token is None):
+ # Both or neither must be set
+ if username or token:
+ raise ValueError("Auth requires both username and token, or neither.")
+ self.username = username
+ self.token = token
+ self.request_kw = kwargs
+ # Default timeouts to 60s connect/read if none provided
+ self.timeout = timeout if timeout is not None else (60, 60)
+
+ # We use a single-level "directory" cache, because a gist is essentially flat
+ self.dircache[""] = self._fetch_file_list()
+
+ @property
+ def kw(self):
+ """Auth parameters passed to 'requests' if we have username/token."""
+ if self.username is not None and self.token is not None:
+ return {"auth": (self.username, self.token), **self.request_kw}
+ return self.request_kw
+
+ def _fetch_gist_metadata(self):
+ """
+ Fetch the JSON metadata for this gist (possibly for a specific revision).
+ """
+ if self.sha:
+ url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha)
+ else:
+ url = self.gist_url.format(gist_id=self.gist_id)
+
+ r = requests.get(url, timeout=self.timeout, **self.kw)
+ if r.status_code == 404:
+ raise FileNotFoundError(
+ f"Gist not found: {self.gist_id}@{self.sha or 'latest'}"
+ )
+ r.raise_for_status()
+ return r.json()
+
+ def _fetch_file_list(self):
+ """
+ Returns a list of dicts describing each file in the gist. These get stored
+ in self.dircache[""].
+ """
+ meta = self._fetch_gist_metadata()
+ if self.filenames:
+ available_files = meta.get("files", {})
+ files = {}
+ for fn in self.filenames:
+ if fn not in available_files:
+ raise FileNotFoundError(fn)
+ files[fn] = available_files[fn]
+ else:
+ files = meta.get("files", {})
+
+ out = []
+ for fname, finfo in files.items():
+ if finfo is None:
+ # Occasionally GitHub returns a file entry with null if it was deleted
+ continue
+ # Build a directory entry
+ out.append(
+ {
+ "name": fname, # file's name
+ "type": "file", # gists have no subdirectories
+ "size": finfo.get("size", 0), # file size in bytes
+ "raw_url": finfo.get("raw_url"),
+ }
+ )
+ return out
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ """
+ Remove 'gist://' from the path, if present.
+ """
+ # The default infer_storage_options can handle gist://username:token@id/file
+ # or gist://id/file, but let's ensure we handle a normal usage too.
+ # We'll just strip the protocol prefix if it exists.
+ path = infer_storage_options(path).get("path", path)
+ return path.lstrip("/")
+
+ @staticmethod
+ def _get_kwargs_from_urls(path):
+ """
+ Parse 'gist://' style URLs into GistFileSystem constructor kwargs.
+ For example:
+ gist://:TOKEN@/file.txt
+ gist://username:TOKEN@/file.txt
+ """
+ so = infer_storage_options(path)
+ out = {}
+ if "username" in so and so["username"]:
+ out["username"] = so["username"]
+ if "password" in so and so["password"]:
+ out["token"] = so["password"]
+ if "host" in so and so["host"]:
+ # We interpret 'host' as the gist ID
+ out["gist_id"] = so["host"]
+
+ # Extract SHA and filename from path
+ if "path" in so and so["path"]:
+ path_parts = so["path"].rsplit("/", 2)[-2:]
+ if len(path_parts) == 2:
+ if path_parts[0]: # SHA present
+ out["sha"] = path_parts[0]
+ if path_parts[1]: # filename also present
+ out["filenames"] = [path_parts[1]]
+
+ return out
+
+ def ls(self, path="", detail=False, **kwargs):
+ """
+ List files in the gist. Gists are single-level, so any 'path' is basically
+ the filename, or empty for all files.
+
+ Parameters
+ ----------
+ path : str, optional
+ The filename to list. If empty, returns all files in the gist.
+ detail : bool, default False
+ If True, return a list of dicts; if False, return a list of filenames.
+ """
+ path = self._strip_protocol(path or "")
+ # If path is empty, return all
+ if path == "":
+ results = self.dircache[""]
+ else:
+ # We want just the single file with this name
+ all_files = self.dircache[""]
+ results = [f for f in all_files if f["name"] == path]
+ if not results:
+ raise FileNotFoundError(path)
+ if detail:
+ return results
+ else:
+ return sorted(f["name"] for f in results)
+
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
+ """
+ Read a single file from the gist.
+ """
+ if mode != "rb":
+ raise NotImplementedError("GitHub Gist FS is read-only (no write).")
+
+ path = self._strip_protocol(path)
+ # Find the file entry in our dircache
+ matches = [f for f in self.dircache[""] if f["name"] == path]
+ if not matches:
+ raise FileNotFoundError(path)
+ finfo = matches[0]
+
+ raw_url = finfo.get("raw_url")
+ if not raw_url:
+ raise FileNotFoundError(f"No raw_url for file: {path}")
+
+ r = requests.get(raw_url, timeout=self.timeout, **self.kw)
+ if r.status_code == 404:
+ raise FileNotFoundError(path)
+ r.raise_for_status()
+ return MemoryFile(path, None, r.content)
+
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
+ """
+ Return {path: contents} for the given file or files. If 'recursive' is True,
+ and path is empty, returns all files in the gist.
+ """
+ paths = self.expand_path(path, recursive=recursive)
+ out = {}
+ for p in paths:
+ try:
+ with self.open(p, "rb") as f:
+ out[p] = f.read()
+ except FileNotFoundError as e:
+ if on_error == "raise":
+ raise e
+ elif on_error == "omit":
+ pass # skip
+ else:
+ out[p] = e
+ return out
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/git.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/git.py
new file mode 100644
index 0000000000000000000000000000000000000000..808d293a1c991ea87d19a2129f3e56d9b813daaa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/git.py
@@ -0,0 +1,114 @@
+import os
+
+import pygit2
+
+from fsspec.spec import AbstractFileSystem
+
+from .memory import MemoryFile
+
+
+class GitFileSystem(AbstractFileSystem):
+ """Browse the files of a local git repo at any hash/tag/branch
+
+ (experimental backend)
+ """
+
+ root_marker = ""
+ cachable = True
+
+ def __init__(self, path=None, fo=None, ref=None, **kwargs):
+ """
+
+ Parameters
+ ----------
+ path: str (optional)
+ Local location of the repo (uses current directory if not given).
+ May be deprecated in favour of ``fo``. When used with a higher
+ level function such as fsspec.open(), may be of the form
+ "git://[path-to-repo[:]][ref@]path/to/file" (but the actual
+ file path should not contain "@" or ":").
+ fo: str (optional)
+ Same as ``path``, but passed as part of a chained URL. This one
+ takes precedence if both are given.
+ ref: str (optional)
+ Reference to work with, could be a hash, tag or branch name. Defaults
+ to current working tree. Note that ``ls`` and ``open`` also take hash,
+ so this becomes the default for those operations
+ kwargs
+ """
+ super().__init__(**kwargs)
+ self.repo = pygit2.Repository(fo or path or os.getcwd())
+ self.ref = ref or "master"
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ path = super()._strip_protocol(path).lstrip("/")
+ if ":" in path:
+ path = path.split(":", 1)[1]
+ if "@" in path:
+ path = path.split("@", 1)[1]
+ return path.lstrip("/")
+
+ def _path_to_object(self, path, ref):
+ comm, ref = self.repo.resolve_refish(ref or self.ref)
+ parts = path.split("/")
+ tree = comm.tree
+ for part in parts:
+ if part and isinstance(tree, pygit2.Tree):
+ if part not in tree:
+ raise FileNotFoundError(path)
+ tree = tree[part]
+ return tree
+
+ @staticmethod
+ def _get_kwargs_from_urls(path):
+ path = path.removeprefix("git://")
+ out = {}
+ if ":" in path:
+ out["path"], path = path.split(":", 1)
+ if "@" in path:
+ out["ref"], path = path.split("@", 1)
+ return out
+
+ @staticmethod
+ def _object_to_info(obj, path=None):
+ # obj.name and obj.filemode are None for the root tree!
+ is_dir = isinstance(obj, pygit2.Tree)
+ return {
+ "type": "directory" if is_dir else "file",
+ "name": (
+ "/".join([path, obj.name or ""]).lstrip("/") if path else obj.name
+ ),
+ "hex": str(obj.id),
+ "mode": "100644" if obj.filemode is None else f"{obj.filemode:o}",
+ "size": 0 if is_dir else obj.size,
+ }
+
+ def ls(self, path, detail=True, ref=None, **kwargs):
+ tree = self._path_to_object(self._strip_protocol(path), ref)
+ return [
+ GitFileSystem._object_to_info(obj, path)
+ if detail
+ else GitFileSystem._object_to_info(obj, path)["name"]
+ for obj in (tree if isinstance(tree, pygit2.Tree) else [tree])
+ ]
+
+ def info(self, path, ref=None, **kwargs):
+ tree = self._path_to_object(self._strip_protocol(path), ref)
+ return GitFileSystem._object_to_info(tree, path)
+
+ def ukey(self, path, ref=None):
+ return self.info(path, ref=ref)["hex"]
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ cache_options=None,
+ ref=None,
+ **kwargs,
+ ):
+ obj = self._path_to_object(path, ref or self.ref)
+ return MemoryFile(data=obj.data)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/github.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/github.py
new file mode 100644
index 0000000000000000000000000000000000000000..3630f6db54413e2c396f6cc1b6b10cd379200043
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/github.py
@@ -0,0 +1,333 @@
+import base64
+import re
+
+import requests
+
+from ..spec import AbstractFileSystem
+from ..utils import infer_storage_options
+from .memory import MemoryFile
+
+
+class GithubFileSystem(AbstractFileSystem):
+ """Interface to files in github
+
+ An instance of this class provides the files residing within a remote github
+ repository. You may specify a point in the repos history, by SHA, branch
+ or tag (default is current master).
+
+ For files less than 1 MB in size, file content is returned directly in a
+ MemoryFile. For larger files, or for files tracked by git-lfs, file content
+ is returned as an HTTPFile wrapping the ``download_url`` provided by the
+ GitHub API.
+
+ When using fsspec.open, allows URIs of the form:
+
+ - "github://path/file", in which case you must specify org, repo and
+ may specify sha in the extra args
+ - 'github://org:repo@/precip/catalog.yml', where the org and repo are
+ part of the URI
+ - 'github://org:repo@sha/precip/catalog.yml', where the sha is also included
+
+ ``sha`` can be the full or abbreviated hex of the commit you want to fetch
+ from, or a branch or tag name (so long as it doesn't contain special characters
+ like "/", "?", which would have to be HTTP-encoded).
+
+ For authorised access, you must provide username and token, which can be made
+ at https://github.com/settings/tokens
+ """
+
+ url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}"
+ content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}"
+ protocol = "github"
+ timeout = (60, 60) # connect, read timeouts
+
+ def __init__(
+ self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs
+ ):
+ super().__init__(**kwargs)
+ self.org = org
+ self.repo = repo
+ if (username is None) ^ (token is None):
+ raise ValueError("Auth required both username and token")
+ self.username = username
+ self.token = token
+ if timeout is not None:
+ self.timeout = timeout
+ if sha is None:
+ # look up default branch (not necessarily "master")
+ u = "https://api.github.com/repos/{org}/{repo}"
+ r = requests.get(
+ u.format(org=org, repo=repo), timeout=self.timeout, **self.kw
+ )
+ r.raise_for_status()
+ sha = r.json()["default_branch"]
+
+ self.root = sha
+ self.ls("")
+ try:
+ from .http import HTTPFileSystem
+
+ self.http_fs = HTTPFileSystem(**kwargs)
+ except ImportError:
+ self.http_fs = None
+
+ @property
+ def kw(self):
+ if self.username:
+ return {"auth": (self.username, self.token)}
+ return {}
+
+ @classmethod
+ def repos(cls, org_or_user, is_org=True):
+ """List repo names for given org or user
+
+ This may become the top level of the FS
+
+ Parameters
+ ----------
+ org_or_user: str
+ Name of the github org or user to query
+ is_org: bool (default True)
+ Whether the name is an organisation (True) or user (False)
+
+ Returns
+ -------
+ List of string
+ """
+ r = requests.get(
+ f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos",
+ timeout=cls.timeout,
+ )
+ r.raise_for_status()
+ return [repo["name"] for repo in r.json()]
+
+ @property
+ def tags(self):
+ """Names of tags in the repo"""
+ r = requests.get(
+ f"https://api.github.com/repos/{self.org}/{self.repo}/tags",
+ timeout=self.timeout,
+ **self.kw,
+ )
+ r.raise_for_status()
+ return [t["name"] for t in r.json()]
+
+ @property
+ def branches(self):
+ """Names of branches in the repo"""
+ r = requests.get(
+ f"https://api.github.com/repos/{self.org}/{self.repo}/branches",
+ timeout=self.timeout,
+ **self.kw,
+ )
+ r.raise_for_status()
+ return [t["name"] for t in r.json()]
+
+ @property
+ def refs(self):
+ """Named references, tags and branches"""
+ return {"tags": self.tags, "branches": self.branches}
+
+ def ls(self, path, detail=False, sha=None, _sha=None, **kwargs):
+ """List files at given path
+
+ Parameters
+ ----------
+ path: str
+ Location to list, relative to repo root
+ detail: bool
+ If True, returns list of dicts, one per file; if False, returns
+ list of full filenames only
+ sha: str (optional)
+ List at the given point in the repo history, branch or tag name or commit
+ SHA
+ _sha: str (optional)
+ List this specific tree object (used internally to descend into trees)
+ """
+ path = self._strip_protocol(path)
+ if path == "":
+ _sha = sha or self.root
+ if _sha is None:
+ parts = path.rstrip("/").split("/")
+ so_far = ""
+ _sha = sha or self.root
+ for part in parts:
+ out = self.ls(so_far, True, sha=sha, _sha=_sha)
+ so_far += "/" + part if so_far else part
+ out = [o for o in out if o["name"] == so_far]
+ if not out:
+ raise FileNotFoundError(path)
+ out = out[0]
+ if out["type"] == "file":
+ if detail:
+ return [out]
+ else:
+ return path
+ _sha = out["sha"]
+ if path not in self.dircache or sha not in [self.root, None]:
+ r = requests.get(
+ self.url.format(org=self.org, repo=self.repo, sha=_sha),
+ timeout=self.timeout,
+ **self.kw,
+ )
+ if r.status_code == 404:
+ raise FileNotFoundError(path)
+ r.raise_for_status()
+ types = {"blob": "file", "tree": "directory"}
+ out = [
+ {
+ "name": path + "/" + f["path"] if path else f["path"],
+ "mode": f["mode"],
+ "type": types[f["type"]],
+ "size": f.get("size", 0),
+ "sha": f["sha"],
+ }
+ for f in r.json()["tree"]
+ if f["type"] in types
+ ]
+ if sha in [self.root, None]:
+ self.dircache[path] = out
+ else:
+ out = self.dircache[path]
+ if detail:
+ return out
+ else:
+ return sorted([f["name"] for f in out])
+
+ def invalidate_cache(self, path=None):
+ self.dircache.clear()
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ opts = infer_storage_options(path)
+ if "username" not in opts:
+ return super()._strip_protocol(path)
+ return opts["path"].lstrip("/")
+
+ @staticmethod
+ def _get_kwargs_from_urls(path):
+ opts = infer_storage_options(path)
+ if "username" not in opts:
+ return {}
+ out = {"org": opts["username"], "repo": opts["password"]}
+ if opts["host"]:
+ out["sha"] = opts["host"]
+ return out
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ cache_options=None,
+ sha=None,
+ **kwargs,
+ ):
+ if mode != "rb":
+ raise NotImplementedError
+
+ # construct a url to hit the GitHub API's repo contents API
+ url = self.content_url.format(
+ org=self.org, repo=self.repo, path=path, sha=sha or self.root
+ )
+
+ # make a request to this API, and parse the response as JSON
+ r = requests.get(url, timeout=self.timeout, **self.kw)
+ if r.status_code == 404:
+ raise FileNotFoundError(path)
+ r.raise_for_status()
+ content_json = r.json()
+
+ # if the response's content key is not empty, try to parse it as base64
+ if content_json["content"]:
+ content = base64.b64decode(content_json["content"])
+
+ # as long as the content does not start with the string
+ # "version https://git-lfs.github.com/"
+ # then it is probably not a git-lfs pointer and we can just return
+ # the content directly
+ if not content.startswith(b"version https://git-lfs.github.com/"):
+ return MemoryFile(None, None, content)
+
+ # we land here if the content was not present in the first response
+ # (regular file over 1MB or git-lfs tracked file)
+ # in this case, we get let the HTTPFileSystem handle the download
+ if self.http_fs is None:
+ raise ImportError(
+ "Please install fsspec[http] to access github files >1 MB "
+ "or git-lfs tracked files."
+ )
+ return self.http_fs.open(
+ content_json["download_url"],
+ mode=mode,
+ block_size=block_size,
+ cache_options=cache_options,
+ **kwargs,
+ )
+
+ def rm(self, path, recursive=False, maxdepth=None, message=None):
+ path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
+ for p in reversed(path):
+ self.rm_file(p, message=message)
+
+ def rm_file(self, path, message=None, **kwargs):
+ """
+ Remove a file from a specified branch using a given commit message.
+
+ Since Github DELETE operation requires a branch name, and we can't reliably
+ determine whether the provided SHA refers to a branch, tag, or commit, we
+ assume it's a branch. If it's not, the user will encounter an error when
+ attempting to retrieve the file SHA or delete the file.
+
+ Parameters
+ ----------
+ path: str
+ The file's location relative to the repository root.
+ message: str, optional
+ The commit message for the deletion.
+ """
+
+ if not self.username:
+ raise ValueError("Authentication required")
+
+ path = self._strip_protocol(path)
+
+ # Attempt to get SHA from cache or Github API
+ sha = self._get_sha_from_cache(path)
+ if not sha:
+ url = self.content_url.format(
+ org=self.org, repo=self.repo, path=path.lstrip("/"), sha=self.root
+ )
+ r = requests.get(url, timeout=self.timeout, **self.kw)
+ if r.status_code == 404:
+ raise FileNotFoundError(path)
+ r.raise_for_status()
+ sha = r.json()["sha"]
+
+ # Delete the file
+ delete_url = self.content_url.format(
+ org=self.org, repo=self.repo, path=path, sha=self.root
+ )
+ branch = self.root
+ data = {
+ "message": message or f"Delete {path}",
+ "sha": sha,
+ **({"branch": branch} if branch else {}),
+ }
+
+ r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw)
+ error_message = r.json().get("message", "")
+ if re.search(r"Branch .+ not found", error_message):
+ error = "Remove only works when the filesystem is initialised from a branch or default (None)"
+ raise ValueError(error)
+ r.raise_for_status()
+
+ self.invalidate_cache(path)
+
+ def _get_sha_from_cache(self, path):
+ for entries in self.dircache.values():
+ for entry in entries:
+ entry_path = entry.get("name")
+ if entry_path and entry_path == path and "sha" in entry:
+ return entry["sha"]
+ return None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/http.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/http.py
new file mode 100644
index 0000000000000000000000000000000000000000..093fa29bea8f0296bf003a4fa1f25b99fc219831
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/http.py
@@ -0,0 +1,890 @@
+import asyncio
+import io
+import logging
+import re
+import weakref
+from copy import copy
+from urllib.parse import urlparse
+
+import aiohttp
+import yarl
+
+from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper
+from fsspec.callbacks import DEFAULT_CALLBACK
+from fsspec.exceptions import FSTimeoutError
+from fsspec.spec import AbstractBufferedFile
+from fsspec.utils import (
+ DEFAULT_BLOCK_SIZE,
+ glob_translate,
+ isfilelike,
+ nullcontext,
+ tokenize,
+)
+
+from ..caching import AllBytes
+
+# https://stackoverflow.com/a/15926317/3821154
+ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""")
+ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
+logger = logging.getLogger("fsspec.http")
+
+
+async def get_client(**kwargs):
+ return aiohttp.ClientSession(**kwargs)
+
+
+class HTTPFileSystem(AsyncFileSystem):
+ """
+ Simple File-System for fetching data via HTTP(S)
+
+ ``ls()`` is implemented by loading the parent page and doing a regex
+ match on the result. If simple_link=True, anything of the form
+ "http(s)://server.com/stuff?thing=other"; otherwise only links within
+ HTML href tags will be used.
+ """
+
+ sep = "/"
+
+ def __init__(
+ self,
+ simple_links=True,
+ block_size=None,
+ same_scheme=True,
+ size_policy=None,
+ cache_type="bytes",
+ cache_options=None,
+ asynchronous=False,
+ loop=None,
+ client_kwargs=None,
+ get_client=get_client,
+ encoded=False,
+ **storage_options,
+ ):
+ """
+ NB: if this is called async, you must await set_client
+
+ Parameters
+ ----------
+ block_size: int
+ Blocks to read bytes; if 0, will default to raw requests file-like
+ objects instead of HTTPFile instances
+ simple_links: bool
+ If True, will consider both HTML tags and anything that looks
+ like a URL; if False, will consider only the former.
+ same_scheme: True
+ When doing ls/glob, if this is True, only consider paths that have
+ http/https matching the input URLs.
+ size_policy: this argument is deprecated
+ client_kwargs: dict
+ Passed to aiohttp.ClientSession, see
+ https://docs.aiohttp.org/en/stable/client_reference.html
+ For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
+ get_client: Callable[..., aiohttp.ClientSession]
+ A callable, which takes keyword arguments and constructs
+ an aiohttp.ClientSession. Its state will be managed by
+ the HTTPFileSystem class.
+ storage_options: key-value
+ Any other parameters passed on to requests
+ cache_type, cache_options: defaults used in open()
+ """
+ super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options)
+ self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
+ self.simple_links = simple_links
+ self.same_schema = same_scheme
+ self.cache_type = cache_type
+ self.cache_options = cache_options
+ self.client_kwargs = client_kwargs or {}
+ self.get_client = get_client
+ self.encoded = encoded
+ self.kwargs = storage_options
+ self._session = None
+
+ # Clean caching-related parameters from `storage_options`
+ # before propagating them as `request_options` through `self.kwargs`.
+ # TODO: Maybe rename `self.kwargs` to `self.request_options` to make
+ # it clearer.
+ request_options = copy(storage_options)
+ self.use_listings_cache = request_options.pop("use_listings_cache", False)
+ request_options.pop("listings_expiry_time", None)
+ request_options.pop("max_paths", None)
+ request_options.pop("skip_instance_cache", None)
+ self.kwargs = request_options
+
+ @property
+ def fsid(self):
+ return "http"
+
+ def encode_url(self, url):
+ return yarl.URL(url, encoded=self.encoded)
+
+ @staticmethod
+ def close_session(loop, session):
+ if loop is not None and loop.is_running():
+ try:
+ sync(loop, session.close, timeout=0.1)
+ return
+ except (TimeoutError, FSTimeoutError, NotImplementedError):
+ pass
+ connector = getattr(session, "_connector", None)
+ if connector is not None:
+ # close after loop is dead
+ connector._close()
+
+ async def set_session(self):
+ if self._session is None:
+ self._session = await self.get_client(loop=self.loop, **self.client_kwargs)
+ if not self.asynchronous:
+ weakref.finalize(self, self.close_session, self.loop, self._session)
+ return self._session
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ """For HTTP, we always want to keep the full URL"""
+ return path
+
+ @classmethod
+ def _parent(cls, path):
+ # override, since _strip_protocol is different for URLs
+ par = super()._parent(path)
+ if len(par) > 7: # "http://..."
+ return par
+ return ""
+
+ async def _ls_real(self, url, detail=True, **kwargs):
+ # ignoring URL-encoded arguments
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ logger.debug(url)
+ session = await self.set_session()
+ async with session.get(self.encode_url(url), **self.kwargs) as r:
+ self._raise_not_found_for_status(r, url)
+
+ if "Content-Type" in r.headers:
+ mimetype = r.headers["Content-Type"].partition(";")[0]
+ else:
+ mimetype = None
+
+ if mimetype in ("text/html", None):
+ try:
+ text = await r.text(errors="ignore")
+ if self.simple_links:
+ links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
+ else:
+ links = [u[2] for u in ex.findall(text)]
+ except UnicodeDecodeError:
+ links = [] # binary, not HTML
+ else:
+ links = []
+
+ out = set()
+ parts = urlparse(url)
+ for l in links:
+ if isinstance(l, tuple):
+ l = l[1]
+ if l.startswith("/") and len(l) > 1:
+ # absolute URL on this server
+ l = f"{parts.scheme}://{parts.netloc}{l}"
+ if l.startswith("http"):
+ if self.same_schema and l.startswith(url.rstrip("/") + "/"):
+ out.add(l)
+ elif l.replace("https", "http").startswith(
+ url.replace("https", "http").rstrip("/") + "/"
+ ):
+ # allowed to cross http <-> https
+ out.add(l)
+ else:
+ if l not in ["..", "../"]:
+ # Ignore FTP-like "parent"
+ out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
+ if not out and url.endswith("/"):
+ out = await self._ls_real(url.rstrip("/"), detail=False)
+ if detail:
+ return [
+ {
+ "name": u,
+ "size": None,
+ "type": "directory" if u.endswith("/") else "file",
+ }
+ for u in out
+ ]
+ else:
+ return sorted(out)
+
+ async def _ls(self, url, detail=True, **kwargs):
+ if self.use_listings_cache and url in self.dircache:
+ out = self.dircache[url]
+ else:
+ out = await self._ls_real(url, detail=detail, **kwargs)
+ self.dircache[url] = out
+ return out
+
+ ls = sync_wrapper(_ls)
+
+ def _raise_not_found_for_status(self, response, url):
+ """
+ Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
+ """
+ if response.status == 404:
+ raise FileNotFoundError(url)
+ response.raise_for_status()
+
+ async def _cat_file(self, url, start=None, end=None, **kwargs):
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ logger.debug(url)
+
+ if start is not None or end is not None:
+ if start == end:
+ return b""
+ headers = kw.pop("headers", {}).copy()
+
+ headers["Range"] = await self._process_limits(url, start, end)
+ kw["headers"] = headers
+ session = await self.set_session()
+ async with session.get(self.encode_url(url), **kw) as r:
+ out = await r.read()
+ self._raise_not_found_for_status(r, url)
+ return out
+
+ async def _get_file(
+ self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs
+ ):
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ logger.debug(rpath)
+ session = await self.set_session()
+ async with session.get(self.encode_url(rpath), **kw) as r:
+ try:
+ size = int(r.headers["content-length"])
+ except (ValueError, KeyError):
+ size = None
+
+ callback.set_size(size)
+ self._raise_not_found_for_status(r, rpath)
+ if isfilelike(lpath):
+ outfile = lpath
+ else:
+ outfile = open(lpath, "wb") # noqa: ASYNC230
+
+ try:
+ chunk = True
+ while chunk:
+ chunk = await r.content.read(chunk_size)
+ outfile.write(chunk)
+ callback.relative_update(len(chunk))
+ finally:
+ if not isfilelike(lpath):
+ outfile.close()
+
+ async def _put_file(
+ self,
+ lpath,
+ rpath,
+ chunk_size=5 * 2**20,
+ callback=DEFAULT_CALLBACK,
+ method="post",
+ mode="overwrite",
+ **kwargs,
+ ):
+ if mode != "overwrite":
+ raise NotImplementedError("Exclusive write")
+
+ async def gen_chunks():
+ # Support passing arbitrary file-like objects
+ # and use them instead of streams.
+ if isinstance(lpath, io.IOBase):
+ context = nullcontext(lpath)
+ use_seek = False # might not support seeking
+ else:
+ context = open(lpath, "rb") # noqa: ASYNC230
+ use_seek = True
+
+ with context as f:
+ if use_seek:
+ callback.set_size(f.seek(0, 2))
+ f.seek(0)
+ else:
+ callback.set_size(getattr(f, "size", None))
+
+ chunk = f.read(chunk_size)
+ while chunk:
+ yield chunk
+ callback.relative_update(len(chunk))
+ chunk = f.read(chunk_size)
+
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ session = await self.set_session()
+
+ method = method.lower()
+ if method not in ("post", "put"):
+ raise ValueError(
+ f"method has to be either 'post' or 'put', not: {method!r}"
+ )
+
+ meth = getattr(session, method)
+ async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp:
+ self._raise_not_found_for_status(resp, rpath)
+
+ async def _exists(self, path, **kwargs):
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ try:
+ logger.debug(path)
+ session = await self.set_session()
+ r = await session.get(self.encode_url(path), **kw)
+ async with r:
+ return r.status < 400
+ except aiohttp.ClientError:
+ return False
+
+ async def _isfile(self, path, **kwargs):
+ return await self._exists(path, **kwargs)
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=None, # XXX: This differs from the base class.
+ cache_type=None,
+ cache_options=None,
+ size=None,
+ **kwargs,
+ ):
+ """Make a file-like object
+
+ Parameters
+ ----------
+ path: str
+ Full URL with protocol
+ mode: string
+ must be "rb"
+ block_size: int or None
+ Bytes to download in one request; use instance value if None. If
+ zero, will return a streaming Requests file-like instance.
+ kwargs: key-value
+ Any other parameters, passed to requests calls
+ """
+ if mode != "rb":
+ raise NotImplementedError
+ block_size = block_size if block_size is not None else self.block_size
+ kw = self.kwargs.copy()
+ kw["asynchronous"] = self.asynchronous
+ kw.update(kwargs)
+ info = {}
+ size = size or info.update(self.info(path, **kwargs)) or info["size"]
+ session = sync(self.loop, self.set_session)
+ if block_size and size and info.get("partial", True):
+ return HTTPFile(
+ self,
+ path,
+ session=session,
+ block_size=block_size,
+ mode=mode,
+ size=size,
+ cache_type=cache_type or self.cache_type,
+ cache_options=cache_options or self.cache_options,
+ loop=self.loop,
+ **kw,
+ )
+ else:
+ return HTTPStreamFile(
+ self,
+ path,
+ mode=mode,
+ loop=self.loop,
+ session=session,
+ **kw,
+ )
+
+ async def open_async(self, path, mode="rb", size=None, **kwargs):
+ session = await self.set_session()
+ if size is None:
+ try:
+ size = (await self._info(path, **kwargs))["size"]
+ except FileNotFoundError:
+ pass
+ return AsyncStreamFile(
+ self,
+ path,
+ loop=self.loop,
+ session=session,
+ size=size,
+ **kwargs,
+ )
+
+ def ukey(self, url):
+ """Unique identifier; assume HTTP files are static, unchanging"""
+ return tokenize(url, self.kwargs, self.protocol)
+
+ async def _info(self, url, **kwargs):
+ """Get info of URL
+
+ Tries to access location via HEAD, and then GET methods, but does
+ not fetch the data.
+
+ It is possible that the server does not supply any size information, in
+ which case size will be given as None (and certain operations on the
+ corresponding file will not work).
+ """
+ info = {}
+ session = await self.set_session()
+
+ for policy in ["head", "get"]:
+ try:
+ info.update(
+ await _file_info(
+ self.encode_url(url),
+ size_policy=policy,
+ session=session,
+ **self.kwargs,
+ **kwargs,
+ )
+ )
+ if info.get("size") is not None:
+ break
+ except Exception as exc:
+ if policy == "get":
+ # If get failed, then raise a FileNotFoundError
+ raise FileNotFoundError(url) from exc
+ logger.debug("", exc_info=exc)
+
+ return {"name": url, "size": None, **info, "type": "file"}
+
+ async def _glob(self, path, maxdepth=None, **kwargs):
+ """
+ Find files by glob-matching.
+
+ This implementation is idntical to the one in AbstractFileSystem,
+ but "?" is not considered as a character for globbing, because it is
+ so common in URLs, often identifying the "query" part.
+ """
+ if maxdepth is not None and maxdepth < 1:
+ raise ValueError("maxdepth must be at least 1")
+ import re
+
+ ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash
+ path = self._strip_protocol(path)
+ append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*"))
+ idx_star = path.find("*") if path.find("*") >= 0 else len(path)
+ idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
+
+ min_idx = min(idx_star, idx_brace)
+
+ detail = kwargs.pop("detail", False)
+
+ if not has_magic(path):
+ if await self._exists(path, **kwargs):
+ if not detail:
+ return [path]
+ else:
+ return {path: await self._info(path, **kwargs)}
+ else:
+ if not detail:
+ return [] # glob of non-existent returns empty
+ else:
+ return {}
+ elif "/" in path[:min_idx]:
+ min_idx = path[:min_idx].rindex("/")
+ root = path[: min_idx + 1]
+ depth = path[min_idx + 1 :].count("/") + 1
+ else:
+ root = ""
+ depth = path[min_idx + 1 :].count("/") + 1
+
+ if "**" in path:
+ if maxdepth is not None:
+ idx_double_stars = path.find("**")
+ depth_double_stars = path[idx_double_stars:].count("/") + 1
+ depth = depth - depth_double_stars + maxdepth
+ else:
+ depth = None
+
+ allpaths = await self._find(
+ root, maxdepth=depth, withdirs=True, detail=True, **kwargs
+ )
+
+ pattern = glob_translate(path + ("/" if ends_with_slash else ""))
+ pattern = re.compile(pattern)
+
+ out = {
+ (
+ p.rstrip("/")
+ if not append_slash_to_dirname
+ and info["type"] == "directory"
+ and p.endswith("/")
+ else p
+ ): info
+ for p, info in sorted(allpaths.items())
+ if pattern.match(p.rstrip("/"))
+ }
+
+ if detail:
+ return out
+ else:
+ return list(out)
+
+ async def _isdir(self, path):
+ # override, since all URLs are (also) files
+ try:
+ return bool(await self._ls(path))
+ except (FileNotFoundError, ValueError):
+ return False
+
+ async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
+ """
+ Write bytes to a remote file over HTTP.
+
+ Parameters
+ ----------
+ path : str
+ Target URL where the data should be written
+ value : bytes
+ Data to be written
+ mode : str
+ How to write to the file - 'overwrite' or 'append'
+ **kwargs : dict
+ Additional parameters to pass to the HTTP request
+ """
+ url = self._strip_protocol(path)
+ headers = kwargs.pop("headers", {})
+ headers["Content-Length"] = str(len(value))
+
+ session = await self.set_session()
+
+ async with session.put(url, data=value, headers=headers, **kwargs) as r:
+ r.raise_for_status()
+
+
+class HTTPFile(AbstractBufferedFile):
+ """
+ A file-like object pointing to a remote HTTP(S) resource
+
+ Supports only reading, with read-ahead of a predetermined block-size.
+
+ In the case that the server does not supply the filesize, only reading of
+ the complete file in one go is supported.
+
+ Parameters
+ ----------
+ url: str
+ Full URL of the remote resource, including the protocol
+ session: aiohttp.ClientSession or None
+ All calls will be made within this session, to avoid restarting
+ connections where the server allows this
+ block_size: int or None
+ The amount of read-ahead to do, in bytes. Default is 5MB, or the value
+ configured for the FileSystem creating this file
+ size: None or int
+ If given, this is the size of the file in bytes, and we don't attempt
+ to call the server to find the value.
+ kwargs: all other key-values are passed to requests calls.
+ """
+
+ def __init__(
+ self,
+ fs,
+ url,
+ session=None,
+ block_size=None,
+ mode="rb",
+ cache_type="bytes",
+ cache_options=None,
+ size=None,
+ loop=None,
+ asynchronous=False,
+ **kwargs,
+ ):
+ if mode != "rb":
+ raise NotImplementedError("File mode not supported")
+ self.asynchronous = asynchronous
+ self.loop = loop
+ self.url = url
+ self.session = session
+ self.details = {"name": url, "size": size, "type": "file"}
+ super().__init__(
+ fs=fs,
+ path=url,
+ mode=mode,
+ block_size=block_size,
+ cache_type=cache_type,
+ cache_options=cache_options,
+ **kwargs,
+ )
+
+ def read(self, length=-1):
+ """Read bytes from file
+
+ Parameters
+ ----------
+ length: int
+ Read up to this many bytes. If negative, read all content to end of
+ file. If the server has not supplied the filesize, attempting to
+ read only part of the data will raise a ValueError.
+ """
+ if (
+ (length < 0 and self.loc == 0) # explicit read all
+ # but not when the size is known and fits into a block anyways
+ and not (self.size is not None and self.size <= self.blocksize)
+ ):
+ self._fetch_all()
+ if self.size is None:
+ if length < 0:
+ self._fetch_all()
+ else:
+ length = min(self.size - self.loc, length)
+ return super().read(length)
+
+ async def async_fetch_all(self):
+ """Read whole file in one shot, without caching
+
+ This is only called when position is still at zero,
+ and read() is called without a byte-count.
+ """
+ logger.debug(f"Fetch all for {self}")
+ if not isinstance(self.cache, AllBytes):
+ r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs)
+ async with r:
+ r.raise_for_status()
+ out = await r.read()
+ self.cache = AllBytes(
+ size=len(out), fetcher=None, blocksize=None, data=out
+ )
+ self.size = len(out)
+
+ _fetch_all = sync_wrapper(async_fetch_all)
+
+ def _parse_content_range(self, headers):
+ """Parse the Content-Range header"""
+ s = headers.get("Content-Range", "")
+ m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s)
+ if not m:
+ return None, None, None
+
+ if m[1] == "*":
+ start = end = None
+ else:
+ start, end = [int(x) for x in m[1].split("-")]
+ total = None if m[2] == "*" else int(m[2])
+ return start, end, total
+
+ async def async_fetch_range(self, start, end):
+ """Download a block of data
+
+ The expectation is that the server returns only the requested bytes,
+ with HTTP code 206. If this is not the case, we first check the headers,
+ and then stream the output - if the data size is bigger than we
+ requested, an exception is raised.
+ """
+ logger.debug(f"Fetch range for {self}: {start}-{end}")
+ kwargs = self.kwargs.copy()
+ headers = kwargs.pop("headers", {}).copy()
+ headers["Range"] = f"bytes={start}-{end - 1}"
+ logger.debug(f"{self.url} : {headers['Range']}")
+ r = await self.session.get(
+ self.fs.encode_url(self.url), headers=headers, **kwargs
+ )
+ async with r:
+ if r.status == 416:
+ # range request outside file
+ return b""
+ r.raise_for_status()
+
+ # If the server has handled the range request, it should reply
+ # with status 206 (partial content). But we'll guess that a suitable
+ # Content-Range header or a Content-Length no more than the
+ # requested range also mean we have got the desired range.
+ response_is_range = (
+ r.status == 206
+ or self._parse_content_range(r.headers)[0] == start
+ or int(r.headers.get("Content-Length", end + 1)) <= end - start
+ )
+
+ if response_is_range:
+ # partial content, as expected
+ out = await r.read()
+ elif start > 0:
+ raise ValueError(
+ "The HTTP server doesn't appear to support range requests. "
+ "Only reading this file from the beginning is supported. "
+ "Open with block_size=0 for a streaming file interface."
+ )
+ else:
+ # Response is not a range, but we want the start of the file,
+ # so we can read the required amount anyway.
+ cl = 0
+ out = []
+ while True:
+ chunk = await r.content.read(2**20)
+ # data size unknown, let's read until we have enough
+ if chunk:
+ out.append(chunk)
+ cl += len(chunk)
+ if cl > end - start:
+ break
+ else:
+ break
+ out = b"".join(out)[: end - start]
+ return out
+
+ _fetch_range = sync_wrapper(async_fetch_range)
+
+
+magic_check = re.compile("([*[])")
+
+
+def has_magic(s):
+ match = magic_check.search(s)
+ return match is not None
+
+
+class HTTPStreamFile(AbstractBufferedFile):
+ def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs):
+ self.asynchronous = kwargs.pop("asynchronous", False)
+ self.url = url
+ self.loop = loop
+ self.session = session
+ if mode != "rb":
+ raise ValueError
+ self.details = {"name": url, "size": None}
+ super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs)
+
+ async def cor():
+ r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__()
+ self.fs._raise_not_found_for_status(r, url)
+ return r
+
+ self.r = sync(self.loop, cor)
+ self.loop = fs.loop
+
+ def seek(self, loc, whence=0):
+ if loc == 0 and whence == 1:
+ return
+ if loc == self.loc and whence == 0:
+ return
+ raise ValueError("Cannot seek streaming HTTP file")
+
+ async def _read(self, num=-1):
+ out = await self.r.content.read(num)
+ self.loc += len(out)
+ return out
+
+ read = sync_wrapper(_read)
+
+ async def _close(self):
+ self.r.close()
+
+ def close(self):
+ asyncio.run_coroutine_threadsafe(self._close(), self.loop)
+ super().close()
+
+
+class AsyncStreamFile(AbstractAsyncStreamedFile):
+ def __init__(
+ self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs
+ ):
+ self.url = url
+ self.session = session
+ self.r = None
+ if mode != "rb":
+ raise ValueError
+ self.details = {"name": url, "size": None}
+ self.kwargs = kwargs
+ super().__init__(fs=fs, path=url, mode=mode, cache_type="none")
+ self.size = size
+
+ async def read(self, num=-1):
+ if self.r is None:
+ r = await self.session.get(
+ self.fs.encode_url(self.url), **self.kwargs
+ ).__aenter__()
+ self.fs._raise_not_found_for_status(r, self.url)
+ self.r = r
+ out = await self.r.content.read(num)
+ self.loc += len(out)
+ return out
+
+ async def close(self):
+ if self.r is not None:
+ self.r.close()
+ self.r = None
+ await super().close()
+
+
+async def get_range(session, url, start, end, file=None, **kwargs):
+ # explicit get a range when we know it must be safe
+ kwargs = kwargs.copy()
+ headers = kwargs.pop("headers", {}).copy()
+ headers["Range"] = f"bytes={start}-{end - 1}"
+ r = await session.get(url, headers=headers, **kwargs)
+ r.raise_for_status()
+ async with r:
+ out = await r.read()
+ if file:
+ with open(file, "r+b") as f: # noqa: ASYNC230
+ f.seek(start)
+ f.write(out)
+ else:
+ return out
+
+
+async def _file_info(url, session, size_policy="head", **kwargs):
+ """Call HEAD on the server to get details about the file (size/checksum etc.)
+
+ Default operation is to explicitly allow redirects and use encoding
+ 'identity' (no compression) to get the true size of the target.
+ """
+ logger.debug("Retrieve file size for %s", url)
+ kwargs = kwargs.copy()
+ ar = kwargs.pop("allow_redirects", True)
+ head = kwargs.get("headers", {}).copy()
+ head["Accept-Encoding"] = "identity"
+ kwargs["headers"] = head
+
+ info = {}
+ if size_policy == "head":
+ r = await session.head(url, allow_redirects=ar, **kwargs)
+ elif size_policy == "get":
+ r = await session.get(url, allow_redirects=ar, **kwargs)
+ else:
+ raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
+ async with r:
+ r.raise_for_status()
+
+ if "Content-Length" in r.headers:
+ # Some servers may choose to ignore Accept-Encoding and return
+ # compressed content, in which case the returned size is unreliable.
+ if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [
+ "identity",
+ "",
+ ]:
+ info["size"] = int(r.headers["Content-Length"])
+ elif "Content-Range" in r.headers:
+ info["size"] = int(r.headers["Content-Range"].split("/")[1])
+
+ if "Content-Type" in r.headers:
+ info["mimetype"] = r.headers["Content-Type"].partition(";")[0]
+
+ if r.headers.get("Accept-Ranges") == "none":
+ # Some servers may explicitly discourage partial content requests, but
+ # the lack of "Accept-Ranges" does not always indicate they would fail
+ info["partial"] = False
+
+ info["url"] = str(r.url)
+
+ for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]:
+ if r.headers.get(checksum_field):
+ info[checksum_field] = r.headers[checksum_field]
+
+ return info
+
+
+async def _file_size(url, session=None, *args, **kwargs):
+ if session is None:
+ session = await get_client()
+ info = await _file_info(url, session=session, *args, **kwargs)
+ return info.get("size")
+
+
+file_size = sync_wrapper(_file_size)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/http_sync.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/http_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..08799f20acde91b19dcdb4fbb02313bc64f9257a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/http_sync.py
@@ -0,0 +1,931 @@
+"""This file is largely copied from http.py"""
+
+import io
+import logging
+import re
+import urllib.error
+import urllib.parse
+from copy import copy
+from json import dumps, loads
+from urllib.parse import urlparse
+
+try:
+ import yarl
+except (ImportError, ModuleNotFoundError, OSError):
+ yarl = False
+
+from fsspec.callbacks import _DEFAULT_CALLBACK
+from fsspec.registry import register_implementation
+from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
+from fsspec.utils import DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, tokenize
+
+from ..caching import AllBytes
+
+# https://stackoverflow.com/a/15926317/3821154
+ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""")
+ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
+logger = logging.getLogger("fsspec.http")
+
+
+class JsHttpException(urllib.error.HTTPError): ...
+
+
+class StreamIO(io.BytesIO):
+ # fake class, so you can set attributes on it
+ # will eventually actually stream
+ ...
+
+
+class ResponseProxy:
+ """Looks like a requests response"""
+
+ def __init__(self, req, stream=False):
+ self.request = req
+ self.stream = stream
+ self._data = None
+ self._headers = None
+
+ @property
+ def raw(self):
+ if self._data is None:
+ b = self.request.response.to_bytes()
+ if self.stream:
+ self._data = StreamIO(b)
+ else:
+ self._data = b
+ return self._data
+
+ def close(self):
+ if hasattr(self, "_data"):
+ del self._data
+
+ @property
+ def headers(self):
+ if self._headers is None:
+ self._headers = dict(
+ [
+ _.split(": ")
+ for _ in self.request.getAllResponseHeaders().strip().split("\r\n")
+ ]
+ )
+ return self._headers
+
+ @property
+ def status_code(self):
+ return int(self.request.status)
+
+ def raise_for_status(self):
+ if not self.ok:
+ raise JsHttpException(
+ self.url, self.status_code, self.reason, self.headers, None
+ )
+
+ def iter_content(self, chunksize, *_, **__):
+ while True:
+ out = self.raw.read(chunksize)
+ if out:
+ yield out
+ else:
+ break
+
+ @property
+ def reason(self):
+ return self.request.statusText
+
+ @property
+ def ok(self):
+ return self.status_code < 400
+
+ @property
+ def url(self):
+ return self.request.response.responseURL
+
+ @property
+ def text(self):
+ # TODO: encoding from headers
+ return self.content.decode()
+
+ @property
+ def content(self):
+ self.stream = False
+ return self.raw
+
+ def json(self):
+ return loads(self.text)
+
+
+class RequestsSessionShim:
+ def __init__(self):
+ self.headers = {}
+
+ def request(
+ self,
+ method,
+ url,
+ params=None,
+ data=None,
+ headers=None,
+ cookies=None,
+ files=None,
+ auth=None,
+ timeout=None,
+ allow_redirects=None,
+ proxies=None,
+ hooks=None,
+ stream=None,
+ verify=None,
+ cert=None,
+ json=None,
+ ):
+ from js import Blob, XMLHttpRequest
+
+ logger.debug("JS request: %s %s", method, url)
+
+ if cert or verify or proxies or files or cookies or hooks:
+ raise NotImplementedError
+ if data and json:
+ raise ValueError("Use json= or data=, not both")
+ req = XMLHttpRequest.new()
+ extra = auth if auth else ()
+ if params:
+ url = f"{url}?{urllib.parse.urlencode(params)}"
+ req.open(method, url, False, *extra)
+ if timeout:
+ req.timeout = timeout
+ if headers:
+ for k, v in headers.items():
+ req.setRequestHeader(k, v)
+
+ req.setRequestHeader("Accept", "application/octet-stream")
+ req.responseType = "arraybuffer"
+ if json:
+ blob = Blob.new([dumps(data)], {type: "application/json"})
+ req.send(blob)
+ elif data:
+ if isinstance(data, io.IOBase):
+ data = data.read()
+ blob = Blob.new([data], {type: "application/octet-stream"})
+ req.send(blob)
+ else:
+ req.send(None)
+ return ResponseProxy(req, stream=stream)
+
+ def get(self, url, **kwargs):
+ return self.request("GET", url, **kwargs)
+
+ def head(self, url, **kwargs):
+ return self.request("HEAD", url, **kwargs)
+
+ def post(self, url, **kwargs):
+ return self.request("POST}", url, **kwargs)
+
+ def put(self, url, **kwargs):
+ return self.request("PUT", url, **kwargs)
+
+ def patch(self, url, **kwargs):
+ return self.request("PATCH", url, **kwargs)
+
+ def delete(self, url, **kwargs):
+ return self.request("DELETE", url, **kwargs)
+
+
+class HTTPFileSystem(AbstractFileSystem):
+ """
+ Simple File-System for fetching data via HTTP(S)
+
+ This is the BLOCKING version of the normal HTTPFileSystem. It uses
+ requests in normal python and the JS runtime in pyodide.
+
+ ***This implementation is extremely experimental, do not use unless
+ you are testing pyodide/pyscript integration***
+ """
+
+ protocol = ("http", "https", "sync-http", "sync-https")
+ sep = "/"
+
+ def __init__(
+ self,
+ simple_links=True,
+ block_size=None,
+ same_scheme=True,
+ cache_type="readahead",
+ cache_options=None,
+ client_kwargs=None,
+ encoded=False,
+ **storage_options,
+ ):
+ """
+
+ Parameters
+ ----------
+ block_size: int
+ Blocks to read bytes; if 0, will default to raw requests file-like
+ objects instead of HTTPFile instances
+ simple_links: bool
+ If True, will consider both HTML tags and anything that looks
+ like a URL; if False, will consider only the former.
+ same_scheme: True
+ When doing ls/glob, if this is True, only consider paths that have
+ http/https matching the input URLs.
+ size_policy: this argument is deprecated
+ client_kwargs: dict
+ Passed to aiohttp.ClientSession, see
+ https://docs.aiohttp.org/en/stable/client_reference.html
+ For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
+ storage_options: key-value
+ Any other parameters passed on to requests
+ cache_type, cache_options: defaults used in open
+ """
+ super().__init__(self, **storage_options)
+ self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
+ self.simple_links = simple_links
+ self.same_schema = same_scheme
+ self.cache_type = cache_type
+ self.cache_options = cache_options
+ self.client_kwargs = client_kwargs or {}
+ self.encoded = encoded
+ self.kwargs = storage_options
+
+ try:
+ import js # noqa: F401
+
+ logger.debug("Starting JS session")
+ self.session = RequestsSessionShim()
+ self.js = True
+ except Exception as e:
+ import requests
+
+ logger.debug("Starting cpython session because of: %s", e)
+ self.session = requests.Session(**(client_kwargs or {}))
+ self.js = False
+
+ request_options = copy(storage_options)
+ self.use_listings_cache = request_options.pop("use_listings_cache", False)
+ request_options.pop("listings_expiry_time", None)
+ request_options.pop("max_paths", None)
+ request_options.pop("skip_instance_cache", None)
+ self.kwargs = request_options
+
+ @property
+ def fsid(self):
+ return "sync-http"
+
+ def encode_url(self, url):
+ if yarl:
+ return yarl.URL(url, encoded=self.encoded)
+ return url
+
+ @classmethod
+ def _strip_protocol(cls, path: str) -> str:
+ """For HTTP, we always want to keep the full URL"""
+ path = path.replace("sync-http://", "http://").replace(
+ "sync-https://", "https://"
+ )
+ return path
+
+ @classmethod
+ def _parent(cls, path):
+ # override, since _strip_protocol is different for URLs
+ par = super()._parent(path)
+ if len(par) > 7: # "http://..."
+ return par
+ return ""
+
+ def _ls_real(self, url, detail=True, **kwargs):
+ # ignoring URL-encoded arguments
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ logger.debug(url)
+ r = self.session.get(self.encode_url(url), **self.kwargs)
+ self._raise_not_found_for_status(r, url)
+ text = r.text
+ if self.simple_links:
+ links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
+ else:
+ links = [u[2] for u in ex.findall(text)]
+ out = set()
+ parts = urlparse(url)
+ for l in links:
+ if isinstance(l, tuple):
+ l = l[1]
+ if l.startswith("/") and len(l) > 1:
+ # absolute URL on this server
+ l = parts.scheme + "://" + parts.netloc + l
+ if l.startswith("http"):
+ if self.same_schema and l.startswith(url.rstrip("/") + "/"):
+ out.add(l)
+ elif l.replace("https", "http").startswith(
+ url.replace("https", "http").rstrip("/") + "/"
+ ):
+ # allowed to cross http <-> https
+ out.add(l)
+ else:
+ if l not in ["..", "../"]:
+ # Ignore FTP-like "parent"
+ out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
+ if not out and url.endswith("/"):
+ out = self._ls_real(url.rstrip("/"), detail=False)
+ if detail:
+ return [
+ {
+ "name": u,
+ "size": None,
+ "type": "directory" if u.endswith("/") else "file",
+ }
+ for u in out
+ ]
+ else:
+ return sorted(out)
+
+ def ls(self, url, detail=True, **kwargs):
+ if self.use_listings_cache and url in self.dircache:
+ out = self.dircache[url]
+ else:
+ out = self._ls_real(url, detail=detail, **kwargs)
+ self.dircache[url] = out
+ return out
+
+ def _raise_not_found_for_status(self, response, url):
+ """
+ Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
+ """
+ if response.status_code == 404:
+ raise FileNotFoundError(url)
+ response.raise_for_status()
+
+ def cat_file(self, url, start=None, end=None, **kwargs):
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ logger.debug(url)
+
+ if start is not None or end is not None:
+ if start == end:
+ return b""
+ headers = kw.pop("headers", {}).copy()
+
+ headers["Range"] = self._process_limits(url, start, end)
+ kw["headers"] = headers
+ r = self.session.get(self.encode_url(url), **kw)
+ self._raise_not_found_for_status(r, url)
+ return r.content
+
+ def get_file(
+ self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs
+ ):
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ logger.debug(rpath)
+ r = self.session.get(self.encode_url(rpath), **kw)
+ try:
+ size = int(
+ r.headers.get("content-length", None)
+ or r.headers.get("Content-Length", None)
+ )
+ except (ValueError, KeyError, TypeError):
+ size = None
+
+ callback.set_size(size)
+ self._raise_not_found_for_status(r, rpath)
+ if not isfilelike(lpath):
+ lpath = open(lpath, "wb")
+ for chunk in r.iter_content(chunk_size, decode_unicode=False):
+ lpath.write(chunk)
+ callback.relative_update(len(chunk))
+
+ def put_file(
+ self,
+ lpath,
+ rpath,
+ chunk_size=5 * 2**20,
+ callback=_DEFAULT_CALLBACK,
+ method="post",
+ **kwargs,
+ ):
+ def gen_chunks():
+ # Support passing arbitrary file-like objects
+ # and use them instead of streams.
+ if isinstance(lpath, io.IOBase):
+ context = nullcontext(lpath)
+ use_seek = False # might not support seeking
+ else:
+ context = open(lpath, "rb")
+ use_seek = True
+
+ with context as f:
+ if use_seek:
+ callback.set_size(f.seek(0, 2))
+ f.seek(0)
+ else:
+ callback.set_size(getattr(f, "size", None))
+
+ chunk = f.read(chunk_size)
+ while chunk:
+ yield chunk
+ callback.relative_update(len(chunk))
+ chunk = f.read(chunk_size)
+
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+
+ method = method.lower()
+ if method not in ("post", "put"):
+ raise ValueError(
+ f"method has to be either 'post' or 'put', not: {method!r}"
+ )
+
+ meth = getattr(self.session, method)
+ resp = meth(rpath, data=gen_chunks(), **kw)
+ self._raise_not_found_for_status(resp, rpath)
+
+ def _process_limits(self, url, start, end):
+ """Helper for "Range"-based _cat_file"""
+ size = None
+ suff = False
+ if start is not None and start < 0:
+ # if start is negative and end None, end is the "suffix length"
+ if end is None:
+ end = -start
+ start = ""
+ suff = True
+ else:
+ size = size or self.info(url)["size"]
+ start = size + start
+ elif start is None:
+ start = 0
+ if not suff:
+ if end is not None and end < 0:
+ if start is not None:
+ size = size or self.info(url)["size"]
+ end = size + end
+ elif end is None:
+ end = ""
+ if isinstance(end, int):
+ end -= 1 # bytes range is inclusive
+ return f"bytes={start}-{end}"
+
+ def exists(self, path, **kwargs):
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ try:
+ logger.debug(path)
+ r = self.session.get(self.encode_url(path), **kw)
+ return r.status_code < 400
+ except Exception:
+ return False
+
+ def isfile(self, path, **kwargs):
+ return self.exists(path, **kwargs)
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=None, # XXX: This differs from the base class.
+ cache_type=None,
+ cache_options=None,
+ size=None,
+ **kwargs,
+ ):
+ """Make a file-like object
+
+ Parameters
+ ----------
+ path: str
+ Full URL with protocol
+ mode: string
+ must be "rb"
+ block_size: int or None
+ Bytes to download in one request; use instance value if None. If
+ zero, will return a streaming Requests file-like instance.
+ kwargs: key-value
+ Any other parameters, passed to requests calls
+ """
+ if mode != "rb":
+ raise NotImplementedError
+ block_size = block_size if block_size is not None else self.block_size
+ kw = self.kwargs.copy()
+ kw.update(kwargs)
+ size = size or self.info(path, **kwargs)["size"]
+ if block_size and size:
+ return HTTPFile(
+ self,
+ path,
+ session=self.session,
+ block_size=block_size,
+ mode=mode,
+ size=size,
+ cache_type=cache_type or self.cache_type,
+ cache_options=cache_options or self.cache_options,
+ **kw,
+ )
+ else:
+ return HTTPStreamFile(
+ self,
+ path,
+ mode=mode,
+ session=self.session,
+ **kw,
+ )
+
+ def ukey(self, url):
+ """Unique identifier; assume HTTP files are static, unchanging"""
+ return tokenize(url, self.kwargs, self.protocol)
+
+ def info(self, url, **kwargs):
+ """Get info of URL
+
+ Tries to access location via HEAD, and then GET methods, but does
+ not fetch the data.
+
+ It is possible that the server does not supply any size information, in
+ which case size will be given as None (and certain operations on the
+ corresponding file will not work).
+ """
+ info = {}
+ for policy in ["head", "get"]:
+ try:
+ info.update(
+ _file_info(
+ self.encode_url(url),
+ size_policy=policy,
+ session=self.session,
+ **self.kwargs,
+ **kwargs,
+ )
+ )
+ if info.get("size") is not None:
+ break
+ except Exception as exc:
+ if policy == "get":
+ # If get failed, then raise a FileNotFoundError
+ raise FileNotFoundError(url) from exc
+ logger.debug(str(exc))
+
+ return {"name": url, "size": None, **info, "type": "file"}
+
+ def glob(self, path, maxdepth=None, **kwargs):
+ """
+ Find files by glob-matching.
+
+ This implementation is idntical to the one in AbstractFileSystem,
+ but "?" is not considered as a character for globbing, because it is
+ so common in URLs, often identifying the "query" part.
+ """
+ import re
+
+ ends = path.endswith("/")
+ path = self._strip_protocol(path)
+ indstar = path.find("*") if path.find("*") >= 0 else len(path)
+ indbrace = path.find("[") if path.find("[") >= 0 else len(path)
+
+ ind = min(indstar, indbrace)
+
+ detail = kwargs.pop("detail", False)
+
+ if not has_magic(path):
+ root = path
+ depth = 1
+ if ends:
+ path += "/*"
+ elif self.exists(path):
+ if not detail:
+ return [path]
+ else:
+ return {path: self.info(path)}
+ else:
+ if not detail:
+ return [] # glob of non-existent returns empty
+ else:
+ return {}
+ elif "/" in path[:ind]:
+ ind2 = path[:ind].rindex("/")
+ root = path[: ind2 + 1]
+ depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1
+ else:
+ root = ""
+ depth = None if "**" in path else path[ind + 1 :].count("/") + 1
+
+ allpaths = self.find(
+ root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs
+ )
+ # Escape characters special to python regex, leaving our supported
+ # special characters in place.
+ # See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
+ # for shell globbing details.
+ pattern = (
+ "^"
+ + (
+ path.replace("\\", r"\\")
+ .replace(".", r"\.")
+ .replace("+", r"\+")
+ .replace("//", "/")
+ .replace("(", r"\(")
+ .replace(")", r"\)")
+ .replace("|", r"\|")
+ .replace("^", r"\^")
+ .replace("$", r"\$")
+ .replace("{", r"\{")
+ .replace("}", r"\}")
+ .rstrip("/")
+ )
+ + "$"
+ )
+ pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern)
+ pattern = re.sub("[*]", "[^/]*", pattern)
+ pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*"))
+ out = {
+ p: allpaths[p]
+ for p in sorted(allpaths)
+ if pattern.match(p.replace("//", "/").rstrip("/"))
+ }
+ if detail:
+ return out
+ else:
+ return list(out)
+
+ def isdir(self, path):
+ # override, since all URLs are (also) files
+ try:
+ return bool(self.ls(path))
+ except (FileNotFoundError, ValueError):
+ return False
+
+
+class HTTPFile(AbstractBufferedFile):
+ """
+ A file-like object pointing to a remove HTTP(S) resource
+
+ Supports only reading, with read-ahead of a predermined block-size.
+
+ In the case that the server does not supply the filesize, only reading of
+ the complete file in one go is supported.
+
+ Parameters
+ ----------
+ url: str
+ Full URL of the remote resource, including the protocol
+ session: requests.Session or None
+ All calls will be made within this session, to avoid restarting
+ connections where the server allows this
+ block_size: int or None
+ The amount of read-ahead to do, in bytes. Default is 5MB, or the value
+ configured for the FileSystem creating this file
+ size: None or int
+ If given, this is the size of the file in bytes, and we don't attempt
+ to call the server to find the value.
+ kwargs: all other key-values are passed to requests calls.
+ """
+
+ def __init__(
+ self,
+ fs,
+ url,
+ session=None,
+ block_size=None,
+ mode="rb",
+ cache_type="bytes",
+ cache_options=None,
+ size=None,
+ **kwargs,
+ ):
+ if mode != "rb":
+ raise NotImplementedError("File mode not supported")
+ self.url = url
+ self.session = session
+ self.details = {"name": url, "size": size, "type": "file"}
+ super().__init__(
+ fs=fs,
+ path=url,
+ mode=mode,
+ block_size=block_size,
+ cache_type=cache_type,
+ cache_options=cache_options,
+ **kwargs,
+ )
+
+ def read(self, length=-1):
+ """Read bytes from file
+
+ Parameters
+ ----------
+ length: int
+ Read up to this many bytes. If negative, read all content to end of
+ file. If the server has not supplied the filesize, attempting to
+ read only part of the data will raise a ValueError.
+ """
+ if (
+ (length < 0 and self.loc == 0) # explicit read all
+ # but not when the size is known and fits into a block anyways
+ and not (self.size is not None and self.size <= self.blocksize)
+ ):
+ self._fetch_all()
+ if self.size is None:
+ if length < 0:
+ self._fetch_all()
+ else:
+ length = min(self.size - self.loc, length)
+ return super().read(length)
+
+ def _fetch_all(self):
+ """Read whole file in one shot, without caching
+
+ This is only called when position is still at zero,
+ and read() is called without a byte-count.
+ """
+ logger.debug(f"Fetch all for {self}")
+ if not isinstance(self.cache, AllBytes):
+ r = self.session.get(self.fs.encode_url(self.url), **self.kwargs)
+ r.raise_for_status()
+ out = r.content
+ self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out)
+ self.size = len(out)
+
+ def _parse_content_range(self, headers):
+ """Parse the Content-Range header"""
+ s = headers.get("Content-Range", "")
+ m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s)
+ if not m:
+ return None, None, None
+
+ if m[1] == "*":
+ start = end = None
+ else:
+ start, end = [int(x) for x in m[1].split("-")]
+ total = None if m[2] == "*" else int(m[2])
+ return start, end, total
+
+ def _fetch_range(self, start, end):
+ """Download a block of data
+
+ The expectation is that the server returns only the requested bytes,
+ with HTTP code 206. If this is not the case, we first check the headers,
+ and then stream the output - if the data size is bigger than we
+ requested, an exception is raised.
+ """
+ logger.debug(f"Fetch range for {self}: {start}-{end}")
+ kwargs = self.kwargs.copy()
+ headers = kwargs.pop("headers", {}).copy()
+ headers["Range"] = f"bytes={start}-{end - 1}"
+ logger.debug("%s : %s", self.url, headers["Range"])
+ r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs)
+ if r.status_code == 416:
+ # range request outside file
+ return b""
+ r.raise_for_status()
+
+ # If the server has handled the range request, it should reply
+ # with status 206 (partial content). But we'll guess that a suitable
+ # Content-Range header or a Content-Length no more than the
+ # requested range also mean we have got the desired range.
+ cl = r.headers.get("Content-Length", r.headers.get("content-length", end + 1))
+ response_is_range = (
+ r.status_code == 206
+ or self._parse_content_range(r.headers)[0] == start
+ or int(cl) <= end - start
+ )
+
+ if response_is_range:
+ # partial content, as expected
+ out = r.content
+ elif start > 0:
+ raise ValueError(
+ "The HTTP server doesn't appear to support range requests. "
+ "Only reading this file from the beginning is supported. "
+ "Open with block_size=0 for a streaming file interface."
+ )
+ else:
+ # Response is not a range, but we want the start of the file,
+ # so we can read the required amount anyway.
+ cl = 0
+ out = []
+ for chunk in r.iter_content(2**20, False):
+ out.append(chunk)
+ cl += len(chunk)
+ out = b"".join(out)[: end - start]
+ return out
+
+
+magic_check = re.compile("([*[])")
+
+
+def has_magic(s):
+ match = magic_check.search(s)
+ return match is not None
+
+
+class HTTPStreamFile(AbstractBufferedFile):
+ def __init__(self, fs, url, mode="rb", session=None, **kwargs):
+ self.url = url
+ self.session = session
+ if mode != "rb":
+ raise ValueError
+ self.details = {"name": url, "size": None}
+ super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs)
+
+ r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs)
+ self.fs._raise_not_found_for_status(r, url)
+ self.it = r.iter_content(1024, False)
+ self.leftover = b""
+
+ self.r = r
+
+ def seek(self, *args, **kwargs):
+ raise ValueError("Cannot seek streaming HTTP file")
+
+ def read(self, num=-1):
+ bufs = [self.leftover]
+ leng = len(self.leftover)
+ while leng < num or num < 0:
+ try:
+ out = self.it.__next__()
+ except StopIteration:
+ break
+ if out:
+ bufs.append(out)
+ else:
+ break
+ leng += len(out)
+ out = b"".join(bufs)
+ if num >= 0:
+ self.leftover = out[num:]
+ out = out[:num]
+ else:
+ self.leftover = b""
+ self.loc += len(out)
+ return out
+
+ def close(self):
+ self.r.close()
+ self.closed = True
+
+
+def get_range(session, url, start, end, **kwargs):
+ # explicit get a range when we know it must be safe
+ kwargs = kwargs.copy()
+ headers = kwargs.pop("headers", {}).copy()
+ headers["Range"] = f"bytes={start}-{end - 1}"
+ r = session.get(url, headers=headers, **kwargs)
+ r.raise_for_status()
+ return r.content
+
+
+def _file_info(url, session, size_policy="head", **kwargs):
+ """Call HEAD on the server to get details about the file (size/checksum etc.)
+
+ Default operation is to explicitly allow redirects and use encoding
+ 'identity' (no compression) to get the true size of the target.
+ """
+ logger.debug("Retrieve file size for %s", url)
+ kwargs = kwargs.copy()
+ ar = kwargs.pop("allow_redirects", True)
+ head = kwargs.get("headers", {}).copy()
+ # TODO: not allowed in JS
+ # head["Accept-Encoding"] = "identity"
+ kwargs["headers"] = head
+
+ info = {}
+ if size_policy == "head":
+ r = session.head(url, allow_redirects=ar, **kwargs)
+ elif size_policy == "get":
+ r = session.get(url, allow_redirects=ar, **kwargs)
+ else:
+ raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
+ r.raise_for_status()
+
+ # TODO:
+ # recognise lack of 'Accept-Ranges',
+ # or 'Accept-Ranges': 'none' (not 'bytes')
+ # to mean streaming only, no random access => return None
+ if "Content-Length" in r.headers:
+ info["size"] = int(r.headers["Content-Length"])
+ elif "Content-Range" in r.headers:
+ info["size"] = int(r.headers["Content-Range"].split("/")[1])
+ elif "content-length" in r.headers:
+ info["size"] = int(r.headers["content-length"])
+ elif "content-range" in r.headers:
+ info["size"] = int(r.headers["content-range"].split("/")[1])
+
+ for checksum_field in ["ETag", "Content-MD5", "Digest"]:
+ if r.headers.get(checksum_field):
+ info[checksum_field] = r.headers[checksum_field]
+
+ return info
+
+
+# importing this is enough to register it
+def register():
+ register_implementation("http", HTTPFileSystem, clobber=True)
+ register_implementation("https", HTTPFileSystem, clobber=True)
+ register_implementation("sync-http", HTTPFileSystem, clobber=True)
+ register_implementation("sync-https", HTTPFileSystem, clobber=True)
+
+
+register()
+
+
+def unregister():
+ from fsspec.implementations.http import HTTPFileSystem
+
+ register_implementation("http", HTTPFileSystem, clobber=True)
+ register_implementation("https", HTTPFileSystem, clobber=True)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/jupyter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/jupyter.py
new file mode 100644
index 0000000000000000000000000000000000000000..2839f4c1feea56dddd54bdc00f0b884c8461d29e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/jupyter.py
@@ -0,0 +1,124 @@
+import base64
+import io
+import re
+
+import requests
+
+import fsspec
+
+
+class JupyterFileSystem(fsspec.AbstractFileSystem):
+ """View of the files as seen by a Jupyter server (notebook or lab)"""
+
+ protocol = ("jupyter", "jlab")
+
+ def __init__(self, url, tok=None, **kwargs):
+ """
+
+ Parameters
+ ----------
+ url : str
+ Base URL of the server, like "http://127.0.0.1:8888". May include
+ token in the string, which is given by the process when starting up
+ tok : str
+ If the token is obtained separately, can be given here
+ kwargs
+ """
+ if "?" in url:
+ if tok is None:
+ try:
+ tok = re.findall("token=([a-z0-9]+)", url)[0]
+ except IndexError as e:
+ raise ValueError("Could not determine token") from e
+ url = url.split("?", 1)[0]
+ self.url = url.rstrip("/") + "/api/contents"
+ self.session = requests.Session()
+ if tok:
+ self.session.headers["Authorization"] = f"token {tok}"
+
+ super().__init__(**kwargs)
+
+ def ls(self, path, detail=True, **kwargs):
+ path = self._strip_protocol(path)
+ r = self.session.get(f"{self.url}/{path}")
+ if r.status_code == 404:
+ return FileNotFoundError(path)
+ r.raise_for_status()
+ out = r.json()
+
+ if out["type"] == "directory":
+ out = out["content"]
+ else:
+ out = [out]
+ for o in out:
+ o["name"] = o.pop("path")
+ o.pop("content")
+ if o["type"] == "notebook":
+ o["type"] = "file"
+ if detail:
+ return out
+ return [o["name"] for o in out]
+
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ path = self._strip_protocol(path)
+ r = self.session.get(f"{self.url}/{path}")
+ if r.status_code == 404:
+ return FileNotFoundError(path)
+ r.raise_for_status()
+ out = r.json()
+ if out["format"] == "text":
+ # data should be binary
+ b = out["content"].encode()
+ else:
+ b = base64.b64decode(out["content"])
+ return b[start:end]
+
+ def pipe_file(self, path, value, **_):
+ path = self._strip_protocol(path)
+ json = {
+ "name": path.rsplit("/", 1)[-1],
+ "path": path,
+ "size": len(value),
+ "content": base64.b64encode(value).decode(),
+ "format": "base64",
+ "type": "file",
+ }
+ self.session.put(f"{self.url}/{path}", json=json)
+
+ def mkdir(self, path, create_parents=True, **kwargs):
+ path = self._strip_protocol(path)
+ if create_parents and "/" in path:
+ self.mkdir(path.rsplit("/", 1)[0], True)
+ json = {
+ "name": path.rsplit("/", 1)[-1],
+ "path": path,
+ "size": None,
+ "content": None,
+ "type": "directory",
+ }
+ self.session.put(f"{self.url}/{path}", json=json)
+
+ def _rm(self, path):
+ path = self._strip_protocol(path)
+ self.session.delete(f"{self.url}/{path}")
+
+ def _open(self, path, mode="rb", **kwargs):
+ path = self._strip_protocol(path)
+ if mode == "rb":
+ data = self.cat_file(path)
+ return io.BytesIO(data)
+ else:
+ return SimpleFileWriter(self, path, mode="wb")
+
+
+class SimpleFileWriter(fsspec.spec.AbstractBufferedFile):
+ def _upload_chunk(self, final=False):
+ """Never uploads a chunk until file is done
+
+ Not suitable for large files
+ """
+ if final is False:
+ return False
+ self.buffer.seek(0)
+ data = self.buffer.read()
+ self.fs.pipe_file(self.path, data)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/libarchive.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/libarchive.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb6f145352e1989e0477e259be02d8d7f4d729e2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/libarchive.py
@@ -0,0 +1,213 @@
+from contextlib import contextmanager
+from ctypes import (
+ CFUNCTYPE,
+ POINTER,
+ c_int,
+ c_longlong,
+ c_void_p,
+ cast,
+ create_string_buffer,
+)
+
+import libarchive
+import libarchive.ffi as ffi
+
+from fsspec import open_files
+from fsspec.archive import AbstractArchiveFileSystem
+from fsspec.implementations.memory import MemoryFile
+from fsspec.utils import DEFAULT_BLOCK_SIZE
+
+# Libarchive requires seekable files or memory only for certain archive
+# types. However, since we read the directory first to cache the contents
+# and also allow random access to any file, the file-like object needs
+# to be seekable no matter what.
+
+# Seek call-backs (not provided in the libarchive python wrapper)
+SEEK_CALLBACK = CFUNCTYPE(c_longlong, c_int, c_void_p, c_longlong, c_int)
+read_set_seek_callback = ffi.ffi(
+ "read_set_seek_callback", [ffi.c_archive_p, SEEK_CALLBACK], c_int, ffi.check_int
+)
+new_api = hasattr(ffi, "NO_OPEN_CB")
+
+
+@contextmanager
+def custom_reader(file, format_name="all", filter_name="all", block_size=ffi.page_size):
+ """Read an archive from a seekable file-like object.
+
+ The `file` object must support the standard `readinto` and 'seek' methods.
+ """
+ buf = create_string_buffer(block_size)
+ buf_p = cast(buf, c_void_p)
+
+ def read_func(archive_p, context, ptrptr):
+ # readinto the buffer, returns number of bytes read
+ length = file.readinto(buf)
+ # write the address of the buffer into the pointer
+ ptrptr = cast(ptrptr, POINTER(c_void_p))
+ ptrptr[0] = buf_p
+ # tell libarchive how much data was written into the buffer
+ return length
+
+ def seek_func(archive_p, context, offset, whence):
+ file.seek(offset, whence)
+ # tell libarchvie the current position
+ return file.tell()
+
+ read_cb = ffi.READ_CALLBACK(read_func)
+ seek_cb = SEEK_CALLBACK(seek_func)
+
+ if new_api:
+ open_cb = ffi.NO_OPEN_CB
+ close_cb = ffi.NO_CLOSE_CB
+ else:
+ open_cb = libarchive.read.OPEN_CALLBACK(ffi.VOID_CB)
+ close_cb = libarchive.read.CLOSE_CALLBACK(ffi.VOID_CB)
+
+ with libarchive.read.new_archive_read(format_name, filter_name) as archive_p:
+ read_set_seek_callback(archive_p, seek_cb)
+ ffi.read_open(archive_p, None, open_cb, read_cb, close_cb)
+ yield libarchive.read.ArchiveRead(archive_p)
+
+
+class LibArchiveFileSystem(AbstractArchiveFileSystem):
+ """Compressed archives as a file-system (read-only)
+
+ Supports the following formats:
+ tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar
+ Microsoft CAB, 7-Zip, WARC
+
+ See the libarchive documentation for further restrictions.
+ https://www.libarchive.org/
+
+ Keeps file object open while instance lives. It only works in seekable
+ file-like objects. In case the filesystem does not support this kind of
+ file object, it is recommended to cache locally.
+
+ This class is pickleable, but not necessarily thread-safe (depends on the
+ platform). See libarchive documentation for details.
+ """
+
+ root_marker = ""
+ protocol = "libarchive"
+ cachable = False
+
+ def __init__(
+ self,
+ fo="",
+ mode="r",
+ target_protocol=None,
+ target_options=None,
+ block_size=DEFAULT_BLOCK_SIZE,
+ **kwargs,
+ ):
+ """
+ Parameters
+ ----------
+ fo: str or file-like
+ Contains ZIP, and must exist. If a str, will fetch file using
+ :meth:`~fsspec.open_files`, which must return one file exactly.
+ mode: str
+ Currently, only 'r' accepted
+ target_protocol: str (optional)
+ If ``fo`` is a string, this value can be used to override the
+ FS protocol inferred from a URL
+ target_options: dict (optional)
+ Kwargs passed when instantiating the target FS, if ``fo`` is
+ a string.
+ """
+ super().__init__(self, **kwargs)
+ if mode != "r":
+ raise ValueError("Only read from archive files accepted")
+ if isinstance(fo, str):
+ files = open_files(fo, protocol=target_protocol, **(target_options or {}))
+ if len(files) != 1:
+ raise ValueError(
+ f'Path "{fo}" did not resolve to exactly one file: "{files}"'
+ )
+ fo = files[0]
+ self.of = fo
+ self.fo = fo.__enter__() # the whole instance is a context
+ self.block_size = block_size
+ self.dir_cache = None
+
+ @contextmanager
+ def _open_archive(self):
+ self.fo.seek(0)
+ with custom_reader(self.fo, block_size=self.block_size) as arc:
+ yield arc
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ # file paths are always relative to the archive root
+ return super()._strip_protocol(path).lstrip("/")
+
+ def _get_dirs(self):
+ fields = {
+ "name": "pathname",
+ "size": "size",
+ "created": "ctime",
+ "mode": "mode",
+ "uid": "uid",
+ "gid": "gid",
+ "mtime": "mtime",
+ }
+
+ if self.dir_cache is not None:
+ return
+
+ self.dir_cache = {}
+ list_names = []
+ with self._open_archive() as arc:
+ for entry in arc:
+ if not entry.isdir and not entry.isfile:
+ # Skip symbolic links, fifo entries, etc.
+ continue
+ self.dir_cache.update(
+ {
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
+ for dirname in self._all_dirnames(set(entry.name))
+ }
+ )
+ f = {key: getattr(entry, fields[key]) for key in fields}
+ f["type"] = "directory" if entry.isdir else "file"
+ list_names.append(entry.name)
+
+ self.dir_cache[f["name"]] = f
+ # libarchive does not seem to return an entry for the directories (at least
+ # not in all formats), so get the directories names from the files names
+ self.dir_cache.update(
+ {
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
+ for dirname in self._all_dirnames(list_names)
+ }
+ )
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ cache_options=None,
+ **kwargs,
+ ):
+ path = self._strip_protocol(path)
+ if mode != "rb":
+ raise NotImplementedError
+
+ data = bytes()
+ with self._open_archive() as arc:
+ for entry in arc:
+ if entry.pathname != path:
+ continue
+
+ if entry.size == 0:
+ # empty file, so there are no blocks
+ break
+
+ for block in entry.get_blocks(entry.size):
+ data = block
+ break
+ else:
+ raise ValueError
+ return MemoryFile(fs=self, path=path, data=data)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/local.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/local.py
new file mode 100644
index 0000000000000000000000000000000000000000..64dc8bb21956e9c5024b47d46d9e9550931891d8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/local.py
@@ -0,0 +1,514 @@
+import datetime
+import io
+import logging
+import os
+import os.path as osp
+import shutil
+import stat
+import tempfile
+from functools import lru_cache
+
+from fsspec import AbstractFileSystem
+from fsspec.compression import compr
+from fsspec.core import get_compression
+from fsspec.utils import isfilelike, stringify_path
+
+logger = logging.getLogger("fsspec.local")
+
+
+class LocalFileSystem(AbstractFileSystem):
+ """Interface to files on local storage
+
+ Parameters
+ ----------
+ auto_mkdir: bool
+ Whether, when opening a file, the directory containing it should
+ be created (if it doesn't already exist). This is assumed by pyarrow
+ code.
+ """
+
+ root_marker = "/"
+ protocol = "file", "local"
+ local_file = True
+
+ def __init__(self, auto_mkdir=False, **kwargs):
+ super().__init__(**kwargs)
+ self.auto_mkdir = auto_mkdir
+
+ @property
+ def fsid(self):
+ return "local"
+
+ def mkdir(self, path, create_parents=True, **kwargs):
+ path = self._strip_protocol(path)
+ if self.exists(path):
+ raise FileExistsError(path)
+ if create_parents:
+ self.makedirs(path, exist_ok=True)
+ else:
+ os.mkdir(path, **kwargs)
+
+ def makedirs(self, path, exist_ok=False):
+ path = self._strip_protocol(path)
+ os.makedirs(path, exist_ok=exist_ok)
+
+ def rmdir(self, path):
+ path = self._strip_protocol(path)
+ os.rmdir(path)
+
+ def ls(self, path, detail=False, **kwargs):
+ path = self._strip_protocol(path)
+ path_info = self.info(path)
+ infos = []
+ if path_info["type"] == "directory":
+ with os.scandir(path) as it:
+ for f in it:
+ try:
+ # Only get the info if requested since it is a bit expensive (the stat call inside)
+ # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths
+ info = self.info(f) if detail else self._strip_protocol(f.path)
+ infos.append(info)
+ except FileNotFoundError:
+ pass
+ else:
+ infos = [path_info] if detail else [path_info["name"]]
+
+ return infos
+
+ def info(self, path, **kwargs):
+ if isinstance(path, os.DirEntry):
+ # scandir DirEntry
+ out = path.stat(follow_symlinks=False)
+ link = path.is_symlink()
+ if path.is_dir(follow_symlinks=False):
+ t = "directory"
+ elif path.is_file(follow_symlinks=False):
+ t = "file"
+ else:
+ t = "other"
+
+ size = out.st_size
+ if link:
+ try:
+ out2 = path.stat(follow_symlinks=True)
+ size = out2.st_size
+ except OSError:
+ size = 0
+ path = self._strip_protocol(path.path)
+ else:
+ # str or path-like
+ path = self._strip_protocol(path)
+ out = os.stat(path, follow_symlinks=False)
+ link = stat.S_ISLNK(out.st_mode)
+ if link:
+ out = os.stat(path, follow_symlinks=True)
+ size = out.st_size
+ if stat.S_ISDIR(out.st_mode):
+ t = "directory"
+ elif stat.S_ISREG(out.st_mode):
+ t = "file"
+ else:
+ t = "other"
+
+ # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime
+ created_time = getattr(out, "st_birthtime", out.st_ctime)
+
+ result = {
+ "name": path,
+ "size": size,
+ "type": t,
+ "created": created_time,
+ "islink": link,
+ }
+ for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]:
+ result[field] = getattr(out, f"st_{field}")
+ if link:
+ result["destination"] = os.readlink(path)
+ return result
+
+ def lexists(self, path, **kwargs):
+ return osp.lexists(path)
+
+ def cp_file(self, path1, path2, **kwargs):
+ path1 = self._strip_protocol(path1)
+ path2 = self._strip_protocol(path2)
+ if self.auto_mkdir:
+ self.makedirs(self._parent(path2), exist_ok=True)
+ if self.isfile(path1):
+ shutil.copyfile(path1, path2)
+ elif self.isdir(path1):
+ self.mkdirs(path2, exist_ok=True)
+ else:
+ raise FileNotFoundError(path1)
+
+ def isfile(self, path):
+ path = self._strip_protocol(path)
+ return os.path.isfile(path)
+
+ def isdir(self, path):
+ path = self._strip_protocol(path)
+ return os.path.isdir(path)
+
+ def get_file(self, path1, path2, callback=None, **kwargs):
+ if isfilelike(path2):
+ with open(path1, "rb") as f:
+ shutil.copyfileobj(f, path2)
+ else:
+ return self.cp_file(path1, path2, **kwargs)
+
+ def put_file(self, path1, path2, callback=None, **kwargs):
+ return self.cp_file(path1, path2, **kwargs)
+
+ def mv(self, path1, path2, recursive: bool = True, **kwargs):
+ """Move files/directories
+ For the specific case of local, all ops on directories are recursive and
+ the recursive= kwarg is ignored.
+ """
+ path1 = self._strip_protocol(path1)
+ path2 = self._strip_protocol(path2)
+ shutil.move(path1, path2)
+
+ def link(self, src, dst, **kwargs):
+ src = self._strip_protocol(src)
+ dst = self._strip_protocol(dst)
+ os.link(src, dst, **kwargs)
+
+ def symlink(self, src, dst, **kwargs):
+ src = self._strip_protocol(src)
+ dst = self._strip_protocol(dst)
+ os.symlink(src, dst, **kwargs)
+
+ def islink(self, path) -> bool:
+ return os.path.islink(self._strip_protocol(path))
+
+ def rm_file(self, path):
+ os.remove(self._strip_protocol(path))
+
+ def rm(self, path, recursive=False, maxdepth=None):
+ if not isinstance(path, list):
+ path = [path]
+
+ for p in path:
+ p = self._strip_protocol(p)
+ if self.isdir(p):
+ if not recursive:
+ raise ValueError("Cannot delete directory, set recursive=True")
+ if osp.abspath(p) == os.getcwd():
+ raise ValueError("Cannot delete current working directory")
+ shutil.rmtree(p)
+ else:
+ os.remove(p)
+
+ def unstrip_protocol(self, name):
+ name = self._strip_protocol(name) # normalise for local/win/...
+ return f"file://{name}"
+
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
+ path = self._strip_protocol(path)
+ if self.auto_mkdir and "w" in mode:
+ self.makedirs(self._parent(path), exist_ok=True)
+ return LocalFileOpener(path, mode, fs=self, **kwargs)
+
+ def touch(self, path, truncate=True, **kwargs):
+ path = self._strip_protocol(path)
+ if self.auto_mkdir:
+ self.makedirs(self._parent(path), exist_ok=True)
+ if self.exists(path):
+ os.utime(path, None)
+ else:
+ open(path, "a").close()
+ if truncate:
+ os.truncate(path, 0)
+
+ def created(self, path):
+ info = self.info(path=path)
+ return datetime.datetime.fromtimestamp(
+ info["created"], tz=datetime.timezone.utc
+ )
+
+ def modified(self, path):
+ info = self.info(path=path)
+ return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
+
+ @classmethod
+ def _parent(cls, path):
+ path = cls._strip_protocol(path)
+ if os.sep == "/":
+ # posix native
+ return path.rsplit("/", 1)[0] or "/"
+ else:
+ # NT
+ path_ = path.rsplit("/", 1)[0]
+ if len(path_) <= 3:
+ if path_[1:2] == ":":
+ # nt root (something like c:/)
+ return path_[0] + ":/"
+ # More cases may be required here
+ return path_
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ path = stringify_path(path)
+ if path.startswith("file://"):
+ path = path[7:]
+ elif path.startswith("file:"):
+ path = path[5:]
+ elif path.startswith("local://"):
+ path = path[8:]
+ elif path.startswith("local:"):
+ path = path[6:]
+
+ path = make_path_posix(path)
+ if os.sep != "/":
+ # This code-path is a stripped down version of
+ # > drive, path = ntpath.splitdrive(path)
+ if path[1:2] == ":":
+ # Absolute drive-letter path, e.g. X:\Windows
+ # Relative path with drive, e.g. X:Windows
+ drive, path = path[:2], path[2:]
+ elif path[:2] == "//":
+ # UNC drives, e.g. \\server\share or \\?\UNC\server\share
+ # Device drives, e.g. \\.\device or \\?\device
+ if (index1 := path.find("/", 2)) == -1 or (
+ index2 := path.find("/", index1 + 1)
+ ) == -1:
+ drive, path = path, ""
+ else:
+ drive, path = path[:index2], path[index2:]
+ else:
+ # Relative path, e.g. Windows
+ drive = ""
+
+ path = path.rstrip("/") or cls.root_marker
+ return drive + path
+
+ else:
+ return path.rstrip("/") or cls.root_marker
+
+ def _isfilestore(self):
+ # Inheriting from DaskFileSystem makes this False (S3, etc. were)
+ # the original motivation. But we are a posix-like file system.
+ # See https://github.com/dask/dask/issues/5526
+ return True
+
+ def chmod(self, path, mode):
+ path = stringify_path(path)
+ return os.chmod(path, mode)
+
+
+def make_path_posix(path):
+ """Make path generic and absolute for current OS"""
+ if not isinstance(path, str):
+ if isinstance(path, (list, set, tuple)):
+ return type(path)(make_path_posix(p) for p in path)
+ else:
+ path = stringify_path(path)
+ if not isinstance(path, str):
+ raise TypeError(f"could not convert {path!r} to string")
+ if os.sep == "/":
+ # Native posix
+ if path.startswith("/"):
+ # most common fast case for posix
+ return path
+ elif path.startswith("~"):
+ return osp.expanduser(path)
+ elif path.startswith("./"):
+ path = path[2:]
+ elif path == ".":
+ path = ""
+ return f"{os.getcwd()}/{path}"
+ else:
+ # NT handling
+ if path[0:1] == "/" and path[2:3] == ":":
+ # path is like "/c:/local/path"
+ path = path[1:]
+ if path[1:2] == ":":
+ # windows full path like "C:\\local\\path"
+ if len(path) <= 3:
+ # nt root (something like c:/)
+ return path[0] + ":/"
+ path = path.replace("\\", "/")
+ return path
+ elif path[0:1] == "~":
+ return make_path_posix(osp.expanduser(path))
+ elif path.startswith(("\\\\", "//")):
+ # windows UNC/DFS-style paths
+ return "//" + path[2:].replace("\\", "/")
+ elif path.startswith(("\\", "/")):
+ # windows relative path with root
+ path = path.replace("\\", "/")
+ return f"{osp.splitdrive(os.getcwd())[0]}{path}"
+ else:
+ path = path.replace("\\", "/")
+ if path.startswith("./"):
+ path = path[2:]
+ elif path == ".":
+ path = ""
+ return f"{make_path_posix(os.getcwd())}/{path}"
+
+
+def trailing_sep(path):
+ """Return True if the path ends with a path separator.
+
+ A forward slash is always considered a path separator, even on Operating
+ Systems that normally use a backslash.
+ """
+ # TODO: if all incoming paths were posix-compliant then separator would
+ # always be a forward slash, simplifying this function.
+ # See https://github.com/fsspec/filesystem_spec/pull/1250
+ return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
+
+
+@lru_cache(maxsize=1)
+def get_umask(mask: int = 0o666) -> int:
+ """Get the current umask.
+
+ Follows https://stackoverflow.com/a/44130549 to get the umask.
+ Temporarily sets the umask to the given value, and then resets it to the
+ original value.
+ """
+ value = os.umask(mask)
+ os.umask(value)
+ return value
+
+
+class LocalFileOpener(io.IOBase):
+ def __init__(
+ self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
+ ):
+ logger.debug("open file: %s", path)
+ self.path = path
+ self.mode = mode
+ self.fs = fs
+ self.f = None
+ self.autocommit = autocommit
+ self.compression = get_compression(path, compression)
+ self.blocksize = io.DEFAULT_BUFFER_SIZE
+ self._open()
+
+ def _open(self):
+ if self.f is None or self.f.closed:
+ if self.autocommit or "w" not in self.mode:
+ self.f = open(self.path, mode=self.mode)
+ if self.compression:
+ compress = compr[self.compression]
+ self.f = compress(self.f, mode=self.mode)
+ else:
+ # TODO: check if path is writable?
+ i, name = tempfile.mkstemp()
+ os.close(i) # we want normal open and normal buffered file
+ self.temp = name
+ self.f = open(name, mode=self.mode)
+ if "w" not in self.mode:
+ self.size = self.f.seek(0, 2)
+ self.f.seek(0)
+ self.f.size = self.size
+
+ def _fetch_range(self, start, end):
+ # probably only used by cached FS
+ if "r" not in self.mode:
+ raise ValueError
+ self._open()
+ self.f.seek(start)
+ return self.f.read(end - start)
+
+ def __setstate__(self, state):
+ self.f = None
+ loc = state.pop("loc", None)
+ self.__dict__.update(state)
+ if "r" in state["mode"]:
+ self.f = None
+ self._open()
+ self.f.seek(loc)
+
+ def __getstate__(self):
+ d = self.__dict__.copy()
+ d.pop("f")
+ if "r" in self.mode:
+ d["loc"] = self.f.tell()
+ else:
+ if not self.f.closed:
+ raise ValueError("Cannot serialise open write-mode local file")
+ return d
+
+ def commit(self):
+ if self.autocommit:
+ raise RuntimeError("Can only commit if not already set to autocommit")
+ try:
+ shutil.move(self.temp, self.path)
+ except PermissionError as e:
+ # shutil.move raises PermissionError if os.rename
+ # and the default copy2 fallback with shutil.copystats fail.
+ # The file should be there nonetheless, but without copied permissions.
+ # If it doesn't exist, there was no permission to create the file.
+ if not os.path.exists(self.path):
+ raise e
+ else:
+ # If PermissionError is not raised, permissions can be set.
+ try:
+ mask = 0o666
+ os.chmod(self.path, mask & ~get_umask(mask))
+ except RuntimeError:
+ pass
+
+ def discard(self):
+ if self.autocommit:
+ raise RuntimeError("Cannot discard if set to autocommit")
+ os.remove(self.temp)
+
+ def readable(self) -> bool:
+ return True
+
+ def writable(self) -> bool:
+ return "r" not in self.mode
+
+ def read(self, *args, **kwargs):
+ return self.f.read(*args, **kwargs)
+
+ def write(self, *args, **kwargs):
+ return self.f.write(*args, **kwargs)
+
+ def tell(self, *args, **kwargs):
+ return self.f.tell(*args, **kwargs)
+
+ def seek(self, *args, **kwargs):
+ return self.f.seek(*args, **kwargs)
+
+ def seekable(self, *args, **kwargs):
+ return self.f.seekable(*args, **kwargs)
+
+ def readline(self, *args, **kwargs):
+ return self.f.readline(*args, **kwargs)
+
+ def readlines(self, *args, **kwargs):
+ return self.f.readlines(*args, **kwargs)
+
+ def close(self):
+ return self.f.close()
+
+ def truncate(self, size=None) -> int:
+ return self.f.truncate(size)
+
+ @property
+ def closed(self):
+ return self.f.closed
+
+ def fileno(self):
+ return self.raw.fileno()
+
+ def flush(self) -> None:
+ self.f.flush()
+
+ def __iter__(self):
+ return self.f.__iter__()
+
+ def __getattr__(self, item):
+ return getattr(self.f, item)
+
+ def __enter__(self):
+ self._incontext = True
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self._incontext = False
+ self.f.__exit__(exc_type, exc_value, traceback)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/memory.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..838876d1f87faa28ed05f02454e210fa534b736e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/memory.py
@@ -0,0 +1,311 @@
+from __future__ import annotations
+
+import logging
+from datetime import datetime, timezone
+from errno import ENOTEMPTY
+from io import BytesIO
+from pathlib import PurePath, PureWindowsPath
+from typing import Any, ClassVar
+
+from fsspec import AbstractFileSystem
+from fsspec.implementations.local import LocalFileSystem
+from fsspec.utils import stringify_path
+
+logger = logging.getLogger("fsspec.memoryfs")
+
+
+class MemoryFileSystem(AbstractFileSystem):
+ """A filesystem based on a dict of BytesIO objects
+
+ This is a global filesystem so instances of this class all point to the same
+ in memory filesystem.
+ """
+
+ store: ClassVar[dict[str, Any]] = {} # global, do not overwrite!
+ pseudo_dirs = [""] # global, do not overwrite!
+ protocol = "memory"
+ root_marker = "/"
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ if isinstance(path, PurePath):
+ if isinstance(path, PureWindowsPath):
+ return LocalFileSystem._strip_protocol(path)
+ else:
+ path = stringify_path(path)
+
+ path = path.removeprefix("memory://")
+ if "::" in path or "://" in path:
+ return path.rstrip("/")
+ path = path.lstrip("/").rstrip("/")
+ return "/" + path if path else ""
+
+ def ls(self, path, detail=True, **kwargs):
+ path = self._strip_protocol(path)
+ if path in self.store:
+ # there is a key with this exact name
+ if not detail:
+ return [path]
+ return [
+ {
+ "name": path,
+ "size": self.store[path].size,
+ "type": "file",
+ "created": self.store[path].created.timestamp(),
+ }
+ ]
+ paths = set()
+ starter = path + "/"
+ out = []
+ for p2 in tuple(self.store):
+ if p2.startswith(starter):
+ if "/" not in p2[len(starter) :]:
+ # exact child
+ out.append(
+ {
+ "name": p2,
+ "size": self.store[p2].size,
+ "type": "file",
+ "created": self.store[p2].created.timestamp(),
+ }
+ )
+ elif len(p2) > len(starter):
+ # implied child directory
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
+ if ppath not in paths:
+ out = out or []
+ out.append(
+ {
+ "name": ppath,
+ "size": 0,
+ "type": "directory",
+ }
+ )
+ paths.add(ppath)
+ for p2 in self.pseudo_dirs:
+ if p2.startswith(starter):
+ if "/" not in p2[len(starter) :]:
+ # exact child pdir
+ if p2 not in paths:
+ out.append({"name": p2, "size": 0, "type": "directory"})
+ paths.add(p2)
+ else:
+ # directory implied by deeper pdir
+ ppath = starter + p2[len(starter) :].split("/", 1)[0]
+ if ppath not in paths:
+ out.append({"name": ppath, "size": 0, "type": "directory"})
+ paths.add(ppath)
+ if not out:
+ if path in self.pseudo_dirs:
+ # empty dir
+ return []
+ raise FileNotFoundError(path)
+ if detail:
+ return out
+ return sorted([f["name"] for f in out])
+
+ def mkdir(self, path, create_parents=True, **kwargs):
+ path = self._strip_protocol(path)
+ if path in self.store or path in self.pseudo_dirs:
+ raise FileExistsError(path)
+ if self._parent(path).strip("/") and self.isfile(self._parent(path)):
+ raise NotADirectoryError(self._parent(path))
+ if create_parents and self._parent(path).strip("/"):
+ try:
+ self.mkdir(self._parent(path), create_parents, **kwargs)
+ except FileExistsError:
+ pass
+ if path and path not in self.pseudo_dirs:
+ self.pseudo_dirs.append(path)
+
+ def makedirs(self, path, exist_ok=False):
+ try:
+ self.mkdir(path, create_parents=True)
+ except FileExistsError:
+ if not exist_ok:
+ raise
+
+ def pipe_file(self, path, value, mode="overwrite", **kwargs):
+ """Set the bytes of given file
+
+ Avoids copies of the data if possible
+ """
+ mode = "xb" if mode == "create" else "wb"
+ self.open(path, mode=mode, data=value)
+
+ def rmdir(self, path):
+ path = self._strip_protocol(path)
+ if path == "":
+ # silently avoid deleting FS root
+ return
+ if path in self.pseudo_dirs:
+ if not self.ls(path):
+ self.pseudo_dirs.remove(path)
+ else:
+ raise OSError(ENOTEMPTY, "Directory not empty", path)
+ else:
+ raise FileNotFoundError(path)
+
+ def info(self, path, **kwargs):
+ logger.debug("info: %s", path)
+ path = self._strip_protocol(path)
+ if path in self.pseudo_dirs or any(
+ p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs
+ ):
+ return {
+ "name": path,
+ "size": 0,
+ "type": "directory",
+ }
+ elif path in self.store:
+ filelike = self.store[path]
+ return {
+ "name": path,
+ "size": filelike.size,
+ "type": "file",
+ "created": getattr(filelike, "created", None),
+ }
+ else:
+ raise FileNotFoundError(path)
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ cache_options=None,
+ **kwargs,
+ ):
+ path = self._strip_protocol(path)
+ if "x" in mode and self.exists(path):
+ raise FileExistsError
+ if path in self.pseudo_dirs:
+ raise IsADirectoryError(path)
+ parent = path
+ while len(parent) > 1:
+ parent = self._parent(parent)
+ if self.isfile(parent):
+ raise FileExistsError(parent)
+ if mode in ["rb", "ab", "r+b"]:
+ if path in self.store:
+ f = self.store[path]
+ if mode == "ab":
+ # position at the end of file
+ f.seek(0, 2)
+ else:
+ # position at the beginning of file
+ f.seek(0)
+ return f
+ else:
+ raise FileNotFoundError(path)
+ elif mode in {"wb", "xb"}:
+ if mode == "xb" and self.exists(path):
+ raise FileExistsError
+ m = MemoryFile(self, path, kwargs.get("data"))
+ if not self._intrans:
+ m.commit()
+ return m
+ else:
+ name = self.__class__.__name__
+ raise ValueError(f"unsupported file mode for {name}: {mode!r}")
+
+ def cp_file(self, path1, path2, **kwargs):
+ path1 = self._strip_protocol(path1)
+ path2 = self._strip_protocol(path2)
+ if self.isfile(path1):
+ self.store[path2] = MemoryFile(
+ self, path2, self.store[path1].getvalue()
+ ) # implicit copy
+ elif self.isdir(path1):
+ if path2 not in self.pseudo_dirs:
+ self.pseudo_dirs.append(path2)
+ else:
+ raise FileNotFoundError(path1)
+
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ logger.debug("cat: %s", path)
+ path = self._strip_protocol(path)
+ try:
+ return bytes(self.store[path].getbuffer()[start:end])
+ except KeyError as e:
+ raise FileNotFoundError(path) from e
+
+ def _rm(self, path):
+ path = self._strip_protocol(path)
+ try:
+ del self.store[path]
+ except KeyError as e:
+ raise FileNotFoundError(path) from e
+
+ def modified(self, path):
+ path = self._strip_protocol(path)
+ try:
+ return self.store[path].modified
+ except KeyError as e:
+ raise FileNotFoundError(path) from e
+
+ def created(self, path):
+ path = self._strip_protocol(path)
+ try:
+ return self.store[path].created
+ except KeyError as e:
+ raise FileNotFoundError(path) from e
+
+ def isfile(self, path):
+ path = self._strip_protocol(path)
+ return path in self.store
+
+ def rm(self, path, recursive=False, maxdepth=None):
+ if isinstance(path, str):
+ path = self._strip_protocol(path)
+ else:
+ path = [self._strip_protocol(p) for p in path]
+ paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
+ for p in reversed(paths):
+ if self.isfile(p):
+ self.rm_file(p)
+ # If the expanded path doesn't exist, it is only because the expanded
+ # path was a directory that does not exist in self.pseudo_dirs. This
+ # is possible if you directly create files without making the
+ # directories first.
+ elif not self.exists(p):
+ continue
+ else:
+ self.rmdir(p)
+
+
+class MemoryFile(BytesIO):
+ """A BytesIO which can't close and works as a context manager
+
+ Can initialise with data. Each path should only be active once at any moment.
+
+ No need to provide fs, path if auto-committing (default)
+ """
+
+ def __init__(self, fs=None, path=None, data=None):
+ logger.debug("open file %s", path)
+ self.fs = fs
+ self.path = path
+ self.created = datetime.now(tz=timezone.utc)
+ self.modified = datetime.now(tz=timezone.utc)
+ if data:
+ super().__init__(data)
+ self.seek(0)
+
+ @property
+ def size(self):
+ return self.getbuffer().nbytes
+
+ def __enter__(self):
+ return self
+
+ def close(self):
+ pass
+
+ def discard(self):
+ pass
+
+ def commit(self):
+ self.fs.store[self.path] = self
+ self.modified = datetime.now(tz=timezone.utc)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/reference.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/reference.py
new file mode 100644
index 0000000000000000000000000000000000000000..66be6ec7ca1cbebc5d80a328f7ed78becaeb0a37
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/reference.py
@@ -0,0 +1,1305 @@
+import base64
+import collections
+import io
+import itertools
+import logging
+import math
+import os
+from functools import lru_cache
+from itertools import chain
+from typing import TYPE_CHECKING, Literal
+
+import fsspec.core
+from fsspec.spec import AbstractBufferedFile
+
+try:
+ import ujson as json
+except ImportError:
+ if not TYPE_CHECKING:
+ import json
+
+from fsspec.asyn import AsyncFileSystem
+from fsspec.callbacks import DEFAULT_CALLBACK
+from fsspec.core import filesystem, open, split_protocol
+from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
+from fsspec.utils import isfilelike, merge_offset_ranges, other_paths
+
+logger = logging.getLogger("fsspec.reference")
+
+
+class ReferenceNotReachable(RuntimeError):
+ def __init__(self, reference, target, *args):
+ super().__init__(*args)
+ self.reference = reference
+ self.target = target
+
+ def __str__(self):
+ return f'Reference "{self.reference}" failed to fetch target {self.target}'
+
+
+def _first(d):
+ return next(iter(d.values()))
+
+
+def _prot_in_references(path, references):
+ ref = references.get(path)
+ if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
+ return split_protocol(ref[0])[0] if ref[0] else ref[0]
+
+
+def _protocol_groups(paths, references):
+ if isinstance(paths, str):
+ return {_prot_in_references(paths, references): [paths]}
+ out = {}
+ for path in paths:
+ protocol = _prot_in_references(path, references)
+ out.setdefault(protocol, []).append(path)
+ return out
+
+
+class RefsValuesView(collections.abc.ValuesView):
+ def __iter__(self):
+ for val in self._mapping.zmetadata.values():
+ yield json.dumps(val).encode()
+ yield from self._mapping._items.values()
+ for field in self._mapping.listdir():
+ chunk_sizes = self._mapping._get_chunk_sizes(field)
+ if len(chunk_sizes) == 0:
+ yield self._mapping[field + "/0"]
+ continue
+ yield from self._mapping._generate_all_records(field)
+
+
+class RefsItemsView(collections.abc.ItemsView):
+ def __iter__(self):
+ return zip(self._mapping.keys(), self._mapping.values())
+
+
+def ravel_multi_index(idx, sizes):
+ val = 0
+ mult = 1
+ for i, s in zip(idx[::-1], sizes[::-1]):
+ val += i * mult
+ mult *= s
+ return val
+
+
+class LazyReferenceMapper(collections.abc.MutableMapping):
+ """This interface can be used to read/write references from Parquet stores.
+ It is not intended for other types of references.
+ It can be used with Kerchunk's MultiZarrToZarr method to combine
+ references into a parquet store.
+ Examples of this use-case can be found here:
+ https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
+
+ # import is class level to prevent numpy dep requirement for fsspec
+ @property
+ def np(self):
+ import numpy as np
+
+ return np
+
+ @property
+ def pd(self):
+ import pandas as pd
+
+ return pd
+
+ def __init__(
+ self,
+ root,
+ fs=None,
+ out_root=None,
+ cache_size=128,
+ categorical_threshold=10,
+ engine: Literal["fastparquet", "pyarrow"] = "fastparquet",
+ ):
+ """
+
+ This instance will be writable, storing changes in memory until full partitions
+ are accumulated or .flush() is called.
+
+ To create an empty lazy store, use .create()
+
+ Parameters
+ ----------
+ root : str
+ Root of parquet store
+ fs : fsspec.AbstractFileSystem
+ fsspec filesystem object, default is local filesystem.
+ cache_size : int, default=128
+ Maximum size of LRU cache, where cache_size*record_size denotes
+ the total number of references that can be loaded in memory at once.
+ categorical_threshold : int
+ Encode urls as pandas.Categorical to reduce memory footprint if the ratio
+ of the number of unique urls to total number of refs for each variable
+ is greater than or equal to this number. (default 10)
+ engine: Literal["fastparquet","pyarrow"]
+ Engine choice for reading parquet files. (default is "fastparquet")
+ """
+
+ self.root = root
+ self.chunk_sizes = {}
+ self.cat_thresh = categorical_threshold
+ self.engine = engine
+ self.cache_size = cache_size
+ self.url = self.root + "/{field}/refs.{record}.parq"
+ # TODO: derive fs from `root`
+ self.fs = fsspec.filesystem("file") if fs is None else fs
+ self.out_root = self.fs.unstrip_protocol(out_root or self.root)
+
+ from importlib.util import find_spec
+
+ if self.engine == "pyarrow" and find_spec("pyarrow") is None:
+ raise ImportError("engine choice `pyarrow` is not installed.")
+
+ def __getattr__(self, item):
+ if item in ("_items", "record_size", "zmetadata"):
+ self.setup()
+ # avoid possible recursion if setup fails somehow
+ return self.__dict__[item]
+ raise AttributeError(item)
+
+ def setup(self):
+ self._items = {}
+ self._items[".zmetadata"] = self.fs.cat_file(
+ "/".join([self.root, ".zmetadata"])
+ )
+ met = json.loads(self._items[".zmetadata"])
+ self.record_size = met["record_size"]
+ self.zmetadata = met["metadata"]
+
+ # Define function to open and decompress refs
+ @lru_cache(maxsize=self.cache_size)
+ def open_refs(field, record):
+ """cached parquet file loader"""
+ path = self.url.format(field=field, record=record)
+ data = io.BytesIO(self.fs.cat_file(path))
+ try:
+ df = self.pd.read_parquet(data, engine=self.engine)
+ refs = {c: df[c].to_numpy() for c in df.columns}
+ except OSError:
+ refs = None
+ return refs
+
+ self.open_refs = open_refs
+
+ @staticmethod
+ def create(root, storage_options=None, fs=None, record_size=10000, **kwargs):
+ """Make empty parquet reference set
+
+ First deletes the contents of the given directory, if it exists.
+
+ Parameters
+ ----------
+ root: str
+ Directory to contain the output; will be created
+ storage_options: dict | None
+ For making the filesystem to use for writing is fs is None
+ fs: FileSystem | None
+ Filesystem for writing
+ record_size: int
+ Number of references per parquet file
+ kwargs: passed to __init__
+
+ Returns
+ -------
+ LazyReferenceMapper instance
+ """
+ met = {"metadata": {}, "record_size": record_size}
+ if fs is None:
+ fs, root = fsspec.core.url_to_fs(root, **(storage_options or {}))
+ if fs.exists(root):
+ fs.rm(root, recursive=True)
+ fs.makedirs(root, exist_ok=True)
+ fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode())
+ return LazyReferenceMapper(root, fs, **kwargs)
+
+ @lru_cache()
+ def listdir(self):
+ """List top-level directories"""
+ dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z"))
+ return set(dirs)
+
+ def ls(self, path="", detail=True):
+ """Shortcut file listings"""
+ path = path.rstrip("/")
+ pathdash = path + "/" if path else ""
+ dirnames = self.listdir()
+ dirs = [
+ d
+ for d in dirnames
+ if d.startswith(pathdash) and "/" not in d.lstrip(pathdash)
+ ]
+ if dirs:
+ others = {
+ f
+ for f in chain(
+ [".zmetadata"],
+ (name for name in self.zmetadata),
+ (name for name in self._items),
+ )
+ if f.startswith(pathdash) and "/" not in f.lstrip(pathdash)
+ }
+ if detail is False:
+ others.update(dirs)
+ return sorted(others)
+ dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs]
+ fileinfo = [
+ {
+ "name": name,
+ "type": "file",
+ "size": len(
+ json.dumps(self.zmetadata[name])
+ if name in self.zmetadata
+ else self._items[name]
+ ),
+ }
+ for name in others
+ ]
+ return sorted(dirinfo + fileinfo, key=lambda s: s["name"])
+ field = path
+ others = set(
+ [name for name in self.zmetadata if name.startswith(f"{path}/")]
+ + [name for name in self._items if name.startswith(f"{path}/")]
+ )
+ fileinfo = [
+ {
+ "name": name,
+ "type": "file",
+ "size": len(
+ json.dumps(self.zmetadata[name])
+ if name in self.zmetadata
+ else self._items[name]
+ ),
+ }
+ for name in others
+ ]
+ keys = self._keys_in_field(field)
+
+ if detail is False:
+ return list(others) + list(keys)
+ recs = self._generate_all_records(field)
+ recinfo = [
+ {"name": name, "type": "file", "size": rec[-1]}
+ for name, rec in zip(keys, recs)
+ if rec[0] # filters out path==None, deleted/missing
+ ]
+ return fileinfo + recinfo
+
+ def _load_one_key(self, key):
+ """Get the reference for one key
+
+ Returns bytes, one-element list or three-element list.
+ """
+ if key in self._items:
+ return self._items[key]
+ elif key in self.zmetadata:
+ return json.dumps(self.zmetadata[key]).encode()
+ elif "/" not in key or self._is_meta(key):
+ raise KeyError(key)
+ field, _ = key.rsplit("/", 1)
+ record, ri, chunk_size = self._key_to_record(key)
+ maybe = self._items.get((field, record), {}).get(ri, False)
+ if maybe is None:
+ # explicitly deleted
+ raise KeyError
+ elif maybe:
+ return maybe
+ elif chunk_size == 0:
+ return b""
+
+ # Chunk keys can be loaded from row group and cached in LRU cache
+ try:
+ refs = self.open_refs(field, record)
+ except (ValueError, TypeError, FileNotFoundError) as exc:
+ raise KeyError(key) from exc
+ columns = ["path", "offset", "size", "raw"]
+ selection = [refs[c][ri] if c in refs else None for c in columns]
+ raw = selection[-1]
+ if raw is not None:
+ return raw
+ if selection[0] is None:
+ raise KeyError("This reference does not exist or has been deleted")
+ if selection[1:3] == [0, 0]:
+ # URL only
+ return selection[:1]
+ # URL, offset, size
+ return selection[:3]
+
+ @lru_cache(4096)
+ def _key_to_record(self, key):
+ """Details needed to construct a reference for one key"""
+ field, chunk = key.rsplit("/", 1)
+ chunk_sizes = self._get_chunk_sizes(field)
+ if len(chunk_sizes) == 0:
+ return 0, 0, 0
+ chunk_idx = [int(c) for c in chunk.split(".")]
+ chunk_number = ravel_multi_index(chunk_idx, chunk_sizes)
+ record = chunk_number // self.record_size
+ ri = chunk_number % self.record_size
+ return record, ri, len(chunk_sizes)
+
+ def _get_chunk_sizes(self, field):
+ """The number of chunks along each axis for a given field"""
+ if field not in self.chunk_sizes:
+ zarray = self.zmetadata[f"{field}/.zarray"]
+ size_ratio = [
+ math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"])
+ ]
+ self.chunk_sizes[field] = size_ratio or [1]
+ return self.chunk_sizes[field]
+
+ def _generate_record(self, field, record):
+ """The references for a given parquet file of a given field"""
+ refs = self.open_refs(field, record)
+ it = iter(zip(*refs.values()))
+ if len(refs) == 3:
+ # All urls
+ return (list(t) for t in it)
+ elif len(refs) == 1:
+ # All raws
+ return refs["raw"]
+ else:
+ # Mix of urls and raws
+ return (list(t[:3]) if not t[3] else t[3] for t in it)
+
+ def _generate_all_records(self, field):
+ """Load all the references within a field by iterating over the parquet files"""
+ nrec = 1
+ for ch in self._get_chunk_sizes(field):
+ nrec *= ch
+ nrec = math.ceil(nrec / self.record_size)
+ for record in range(nrec):
+ yield from self._generate_record(field, record)
+
+ def values(self):
+ return RefsValuesView(self)
+
+ def items(self):
+ return RefsItemsView(self)
+
+ def __hash__(self):
+ return id(self)
+
+ def __getitem__(self, key):
+ return self._load_one_key(key)
+
+ def __setitem__(self, key, value):
+ if "/" in key and not self._is_meta(key):
+ field, chunk = key.rsplit("/", 1)
+ record, i, _ = self._key_to_record(key)
+ subdict = self._items.setdefault((field, record), {})
+ subdict[i] = value
+ if len(subdict) == self.record_size:
+ self.write(field, record)
+ else:
+ # metadata or top-level
+ if hasattr(value, "to_bytes"):
+ val = value.to_bytes().decode()
+ elif isinstance(value, bytes):
+ val = value.decode()
+ else:
+ val = value
+ self._items[key] = val
+ new_value = json.loads(val)
+ self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
+
+ @staticmethod
+ def _is_meta(key):
+ return key.startswith(".z") or "/.z" in key
+
+ def __delitem__(self, key):
+ if key in self._items:
+ del self._items[key]
+ elif key in self.zmetadata:
+ del self.zmetadata[key]
+ else:
+ if "/" in key and not self._is_meta(key):
+ field, _ = key.rsplit("/", 1)
+ record, i, _ = self._key_to_record(key)
+ subdict = self._items.setdefault((field, record), {})
+ subdict[i] = None
+ if len(subdict) == self.record_size:
+ self.write(field, record)
+ else:
+ # metadata or top-level
+ self._items[key] = None
+
+ def write(self, field, record, base_url=None, storage_options=None):
+ # extra requirements if writing
+ import kerchunk.df
+ import numpy as np
+ import pandas as pd
+
+ partition = self._items[(field, record)]
+ original = False
+ if len(partition) < self.record_size:
+ try:
+ original = self.open_refs(field, record)
+ except OSError:
+ pass
+
+ if original:
+ paths = original["path"]
+ offsets = original["offset"]
+ sizes = original["size"]
+ raws = original["raw"]
+ else:
+ paths = np.full(self.record_size, np.nan, dtype="O")
+ offsets = np.zeros(self.record_size, dtype="int64")
+ sizes = np.zeros(self.record_size, dtype="int64")
+ raws = np.full(self.record_size, np.nan, dtype="O")
+ for j, data in partition.items():
+ if isinstance(data, list):
+ if (
+ str(paths.dtype) == "category"
+ and data[0] not in paths.dtype.categories
+ ):
+ paths = paths.add_categories(data[0])
+ paths[j] = data[0]
+ if len(data) > 1:
+ offsets[j] = data[1]
+ sizes[j] = data[2]
+ elif data is None:
+ # delete
+ paths[j] = None
+ offsets[j] = 0
+ sizes[j] = 0
+ raws[j] = None
+ else:
+ # this is the only call into kerchunk, could remove
+ raws[j] = kerchunk.df._proc_raw(data)
+ # TODO: only save needed columns
+ df = pd.DataFrame(
+ {
+ "path": paths,
+ "offset": offsets,
+ "size": sizes,
+ "raw": raws,
+ },
+ copy=False,
+ )
+ if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh:
+ df["path"] = df["path"].astype("category")
+ object_encoding = {"raw": "bytes", "path": "utf8"}
+ has_nulls = ["path", "raw"]
+
+ fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq"
+ self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
+
+ if self.engine == "pyarrow":
+ df_backend_kwargs = {"write_statistics": False}
+ elif self.engine == "fastparquet":
+ df_backend_kwargs = {
+ "stats": False,
+ "object_encoding": object_encoding,
+ "has_nulls": has_nulls,
+ }
+ else:
+ raise NotImplementedError(f"{self.engine} not supported")
+ df.to_parquet(
+ fn,
+ engine=self.engine,
+ storage_options=storage_options
+ or getattr(self.fs, "storage_options", None),
+ compression="zstd",
+ index=False,
+ **df_backend_kwargs,
+ )
+
+ partition.clear()
+ self._items.pop((field, record))
+
+ def flush(self, base_url=None, storage_options=None):
+ """Output any modified or deleted keys
+
+ Parameters
+ ----------
+ base_url: str
+ Location of the output
+ """
+
+ # write what we have so far and clear sub chunks
+ for thing in list(self._items):
+ if isinstance(thing, tuple):
+ field, record = thing
+ self.write(
+ field,
+ record,
+ base_url=base_url,
+ storage_options=storage_options,
+ )
+
+ # gather .zmetadata from self._items and write that too
+ for k in list(self._items):
+ if k != ".zmetadata" and ".z" in k:
+ self.zmetadata[k] = json.loads(self._items.pop(k))
+ met = {"metadata": self.zmetadata, "record_size": self.record_size}
+ self._items.clear()
+ self._items[".zmetadata"] = json.dumps(met).encode()
+ self.fs.pipe(
+ "/".join([base_url or self.out_root, ".zmetadata"]),
+ self._items[".zmetadata"],
+ )
+
+ # TODO: only clear those that we wrote to?
+ self.open_refs.cache_clear()
+
+ def __len__(self):
+ # Caveat: This counts expected references, not actual - but is fast
+ count = 0
+ for field in self.listdir():
+ if field.startswith("."):
+ count += 1
+ else:
+ count += math.prod(self._get_chunk_sizes(field))
+ count += len(self.zmetadata) # all metadata keys
+ # any other files not in reference partitions
+ count += sum(1 for _ in self._items if not isinstance(_, tuple))
+ return count
+
+ def __iter__(self):
+ # Caveat: returns only existing keys, so the number of these does not
+ # match len(self)
+ metas = set(self.zmetadata)
+ metas.update(self._items)
+ for bit in metas:
+ if isinstance(bit, str):
+ yield bit
+ for field in self.listdir():
+ for k in self._keys_in_field(field):
+ if k in self:
+ yield k
+
+ def __contains__(self, item):
+ try:
+ self._load_one_key(item)
+ return True
+ except KeyError:
+ return False
+
+ def _keys_in_field(self, field):
+ """List key names in given field
+
+ Produces strings like "field/x.y" appropriate from the chunking of the array
+ """
+ chunk_sizes = self._get_chunk_sizes(field)
+ if len(chunk_sizes) == 0:
+ yield field + "/0"
+ return
+ inds = itertools.product(*(range(i) for i in chunk_sizes))
+ for ind in inds:
+ yield field + "/" + ".".join([str(c) for c in ind])
+
+
+class ReferenceFileSystem(AsyncFileSystem):
+ """View byte ranges of some other file as a file system
+ Initial version: single file system target, which must support
+ async, and must allow start and end args in _cat_file. Later versions
+ may allow multiple arbitrary URLs for the targets.
+ This FileSystem is read-only. It is designed to be used with async
+ targets (for now). We do not get original file details from the target FS.
+ Configuration is by passing a dict of references at init, or a URL to
+ a JSON file containing the same; this dict
+ can also contain concrete data for some set of paths.
+ Reference dict format:
+ {path0: bytes_data, path1: (target_url, offset, size)}
+ https://github.com/fsspec/kerchunk/blob/main/README.md
+ """
+
+ protocol = "reference"
+ cachable = False
+
+ def __init__(
+ self,
+ fo,
+ target=None,
+ ref_storage_args=None,
+ target_protocol=None,
+ target_options=None,
+ remote_protocol=None,
+ remote_options=None,
+ fs=None,
+ template_overrides=None,
+ simple_templates=True,
+ max_gap=64_000,
+ max_block=256_000_000,
+ cache_size=128,
+ **kwargs,
+ ):
+ """
+ Parameters
+ ----------
+ fo : dict or str
+ The set of references to use for this instance, with a structure as above.
+ If str referencing a JSON file, will use fsspec.open, in conjunction
+ with target_options and target_protocol to open and parse JSON at this
+ location. If a directory, then assume references are a set of parquet
+ files to be loaded lazily.
+ target : str
+ For any references having target_url as None, this is the default file
+ target to use
+ ref_storage_args : dict
+ If references is a str, use these kwargs for loading the JSON file.
+ Deprecated: use target_options instead.
+ target_protocol : str
+ Used for loading the reference file, if it is a path. If None, protocol
+ will be derived from the given path
+ target_options : dict
+ Extra FS options for loading the reference file ``fo``, if given as a path
+ remote_protocol : str
+ The protocol of the filesystem on which the references will be evaluated
+ (unless fs is provided). If not given, will be derived from the first
+ URL that has a protocol in the templates or in the references, in that
+ order.
+ remote_options : dict
+ kwargs to go with remote_protocol
+ fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
+ Directly provide a file system(s):
+ - a single filesystem instance
+ - a dict of protocol:filesystem, where each value is either a filesystem
+ instance, or a dict of kwargs that can be used to create in
+ instance for the given protocol
+
+ If this is given, remote_options and remote_protocol are ignored.
+ template_overrides : dict
+ Swap out any templates in the references file with these - useful for
+ testing.
+ simple_templates: bool
+ Whether templates can be processed with simple replace (True) or if
+ jinja is needed (False, much slower). All reference sets produced by
+ ``kerchunk`` are simple in this sense, but the spec allows for complex.
+ max_gap, max_block: int
+ For merging multiple concurrent requests to the same remote file.
+ Neighboring byte ranges will only be merged when their
+ inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
+ to only merge when it requires no extra bytes. Pass a negative
+ number to disable merging, appropriate for local target files.
+ Neighboring byte ranges will only be merged when the size of
+ the aggregated range is <= ``max_block``. Default is 256MB.
+ cache_size : int
+ Maximum size of LRU cache, where cache_size*record_size denotes
+ the total number of references that can be loaded in memory at once.
+ Only used for lazily loaded references.
+ kwargs : passed to parent class
+ """
+ super().__init__(**kwargs)
+ self.target = target
+ self.template_overrides = template_overrides
+ self.simple_templates = simple_templates
+ self.templates = {}
+ self.fss = {}
+ self._dircache = {}
+ self.max_gap = max_gap
+ self.max_block = max_block
+ if isinstance(fo, str):
+ dic = dict(
+ **(ref_storage_args or target_options or {}), protocol=target_protocol
+ )
+ ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic)
+ if ref_fs.isfile(fo2):
+ # text JSON
+ with fsspec.open(fo, "rb", **dic) as f:
+ logger.info("Read reference from URL %s", fo)
+ text = json.load(f)
+ self._process_references(text, template_overrides)
+ else:
+ # Lazy parquet refs
+ logger.info("Open lazy reference dict from URL %s", fo)
+ self.references = LazyReferenceMapper(
+ fo2,
+ fs=ref_fs,
+ cache_size=cache_size,
+ )
+ else:
+ # dictionaries
+ self._process_references(fo, template_overrides)
+ if isinstance(fs, dict):
+ self.fss = {
+ k: (
+ fsspec.filesystem(k.split(":", 1)[0], **opts)
+ if isinstance(opts, dict)
+ else opts
+ )
+ for k, opts in fs.items()
+ }
+ if None not in self.fss:
+ self.fss[None] = filesystem("file")
+ return
+ if fs is not None:
+ # single remote FS
+ remote_protocol = (
+ fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol
+ )
+ self.fss[remote_protocol] = fs
+
+ if remote_protocol is None:
+ # get single protocol from any templates
+ for ref in self.templates.values():
+ if callable(ref):
+ ref = ref()
+ protocol, _ = fsspec.core.split_protocol(ref)
+ if protocol and protocol not in self.fss:
+ fs = filesystem(protocol, **(remote_options or {}))
+ self.fss[protocol] = fs
+ if remote_protocol is None:
+ # get single protocol from references
+ # TODO: warning here, since this can be very expensive?
+ for ref in self.references.values():
+ if callable(ref):
+ ref = ref()
+ if isinstance(ref, list) and ref[0]:
+ protocol, _ = fsspec.core.split_protocol(ref[0])
+ if protocol not in self.fss:
+ fs = filesystem(protocol, **(remote_options or {}))
+ self.fss[protocol] = fs
+ # only use first remote URL
+ break
+
+ if remote_protocol and remote_protocol not in self.fss:
+ fs = filesystem(remote_protocol, **(remote_options or {}))
+ self.fss[remote_protocol] = fs
+
+ self.fss[None] = fs or filesystem("file") # default one
+ # Wrap any non-async filesystems to ensure async methods are available below
+ for k, f in self.fss.items():
+ if not f.async_impl:
+ self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
+ elif self.asynchronous ^ f.asynchronous:
+ raise ValueError(
+ "Reference-FS's target filesystem must have same value "
+ "of asynchronous"
+ )
+
+ def _cat_common(self, path, start=None, end=None):
+ path = self._strip_protocol(path)
+ logger.debug(f"cat: {path}")
+ try:
+ part = self.references[path]
+ except KeyError as exc:
+ raise FileNotFoundError(path) from exc
+ if isinstance(part, str):
+ part = part.encode()
+ if hasattr(part, "to_bytes"):
+ part = part.to_bytes()
+ if isinstance(part, bytes):
+ logger.debug(f"Reference: {path}, type bytes")
+ if part.startswith(b"base64:"):
+ part = base64.b64decode(part[7:])
+ return part, None, None
+
+ if len(part) == 1:
+ logger.debug(f"Reference: {path}, whole file => {part}")
+ url = part[0]
+ start1, end1 = start, end
+ else:
+ url, start0, size = part
+ logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}")
+ end0 = start0 + size
+
+ if start is not None:
+ if start >= 0:
+ start1 = start0 + start
+ else:
+ start1 = end0 + start
+ else:
+ start1 = start0
+ if end is not None:
+ if end >= 0:
+ end1 = start0 + end
+ else:
+ end1 = end0 + end
+ else:
+ end1 = end0
+ if url is None:
+ url = self.target
+ return url, start1, end1
+
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
+ if isinstance(part_or_url, bytes):
+ return part_or_url[start:end]
+ protocol, _ = split_protocol(part_or_url)
+ try:
+ return await self.fss[protocol]._cat_file(
+ part_or_url, start=start0, end=end0
+ )
+ except Exception as e:
+ raise ReferenceNotReachable(path, part_or_url) from e
+
+ def cat_file(self, path, start=None, end=None, **kwargs):
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
+ if isinstance(part_or_url, bytes):
+ return part_or_url[start:end]
+ protocol, _ = split_protocol(part_or_url)
+ try:
+ return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0)
+ except Exception as e:
+ raise ReferenceNotReachable(path, part_or_url) from e
+
+ def pipe_file(self, path, value, **_):
+ """Temporarily add binary data or reference as a file"""
+ self.references[path] = value
+
+ async def _get_file(self, rpath, lpath, **kwargs):
+ if self.isdir(rpath):
+ return os.makedirs(lpath, exist_ok=True)
+ data = await self._cat_file(rpath)
+ with open(lpath, "wb") as f:
+ f.write(data)
+
+ def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs):
+ if self.isdir(rpath):
+ return os.makedirs(lpath, exist_ok=True)
+ data = self.cat_file(rpath, **kwargs)
+ callback.set_size(len(data))
+ if isfilelike(lpath):
+ lpath.write(data)
+ else:
+ with open(lpath, "wb") as f:
+ f.write(data)
+ callback.absolute_update(len(data))
+
+ def get(self, rpath, lpath, recursive=False, **kwargs):
+ if recursive:
+ # trigger directory build
+ self.ls("")
+ rpath = self.expand_path(rpath, recursive=recursive)
+ fs = fsspec.filesystem("file", auto_mkdir=True)
+ targets = other_paths(rpath, lpath)
+ if recursive:
+ data = self.cat([r for r in rpath if not self.isdir(r)])
+ else:
+ data = self.cat(rpath)
+ for remote, local in zip(rpath, targets):
+ if remote in data:
+ fs.pipe_file(local, data[remote])
+
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
+ if isinstance(path, str) and recursive:
+ raise NotImplementedError
+ if isinstance(path, list) and (recursive or any("*" in p for p in path)):
+ raise NotImplementedError
+ # TODO: if references is lazy, pre-fetch all paths in batch before access
+ proto_dict = _protocol_groups(path, self.references)
+ out = {}
+ for proto, paths in proto_dict.items():
+ fs = self.fss[proto]
+ urls, starts, ends, valid_paths = [], [], [], []
+ for p in paths:
+ # find references or label not-found. Early exit if any not
+ # found and on_error is "raise"
+ try:
+ u, s, e = self._cat_common(p)
+ if not isinstance(u, (bytes, str)):
+ # nan/None from parquet
+ continue
+ except FileNotFoundError as err:
+ if on_error == "raise":
+ raise
+ if on_error != "omit":
+ out[p] = err
+ else:
+ urls.append(u)
+ starts.append(s)
+ ends.append(e)
+ valid_paths.append(p)
+
+ # process references into form for merging
+ urls2 = []
+ starts2 = []
+ ends2 = []
+ paths2 = []
+ whole_files = set()
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
+ if isinstance(u, bytes):
+ # data
+ out[p] = u
+ elif s is None:
+ # whole file - limits are None, None, but no further
+ # entries take for this file
+ whole_files.add(u)
+ urls2.append(u)
+ starts2.append(s)
+ ends2.append(e)
+ paths2.append(p)
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
+ # second run to account for files that are to be loaded whole
+ if s is not None and u not in whole_files:
+ urls2.append(u)
+ starts2.append(s)
+ ends2.append(e)
+ paths2.append(p)
+
+ # merge and fetch consolidated ranges
+ new_paths, new_starts, new_ends = merge_offset_ranges(
+ list(urls2),
+ list(starts2),
+ list(ends2),
+ sort=True,
+ max_gap=self.max_gap,
+ max_block=self.max_block,
+ )
+ bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
+
+ # unbundle from merged bytes - simple approach
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
+ if p in out:
+ continue # was bytes, already handled
+ for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out):
+ if np == u and (ns is None or ne is None):
+ if isinstance(b, Exception):
+ out[p] = b
+ else:
+ out[p] = b[s:e]
+ elif np == u and s >= ns and e <= ne:
+ if isinstance(b, Exception):
+ out[p] = b
+ else:
+ out[p] = b[s - ns : (e - ne) or None]
+
+ for k, v in out.copy().items():
+ # these were valid references, but fetch failed, so transform exc
+ if isinstance(v, Exception) and k in self.references:
+ ex = out[k]
+ new_ex = ReferenceNotReachable(k, self.references[k])
+ new_ex.__cause__ = ex
+ if on_error == "raise":
+ raise new_ex
+ elif on_error != "omit":
+ out[k] = new_ex
+
+ if len(out) == 1 and isinstance(path, str) and "*" not in path:
+ return _first(out)
+ return out
+
+ def _process_references(self, references, template_overrides=None):
+ vers = references.get("version", None)
+ if vers is None:
+ self._process_references0(references)
+ elif vers == 1:
+ self._process_references1(references, template_overrides=template_overrides)
+ else:
+ raise ValueError(f"Unknown reference spec version: {vers}")
+ # TODO: we make dircache by iterating over all entries, but for Spec >= 1,
+ # can replace with programmatic. Is it even needed for mapper interface?
+
+ def _process_references0(self, references):
+ """Make reference dict for Spec Version 0"""
+ if isinstance(references, dict):
+ # do not do this for lazy/parquet backend, which will not make dicts,
+ # but must remain writable in the original object
+ references = {
+ key: json.dumps(val) if isinstance(val, dict) else val
+ for key, val in references.items()
+ }
+ self.references = references
+
+ def _process_references1(self, references, template_overrides=None):
+ if not self.simple_templates or self.templates:
+ import jinja2
+ self.references = {}
+ self._process_templates(references.get("templates", {}))
+
+ @lru_cache(1000)
+ def _render_jinja(u):
+ return jinja2.Template(u).render(**self.templates)
+
+ for k, v in references.get("refs", {}).items():
+ if isinstance(v, str):
+ if v.startswith("base64:"):
+ self.references[k] = base64.b64decode(v[7:])
+ self.references[k] = v
+ elif isinstance(v, dict):
+ self.references[k] = json.dumps(v)
+ elif self.templates:
+ u = v[0]
+ if "{{" in u:
+ if self.simple_templates:
+ u = (
+ u.replace("{{", "{")
+ .replace("}}", "}")
+ .format(**self.templates)
+ )
+ else:
+ u = _render_jinja(u)
+ self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]]
+ else:
+ self.references[k] = v
+ self.references.update(self._process_gen(references.get("gen", [])))
+
+ def _process_templates(self, tmp):
+ self.templates = {}
+ if self.template_overrides is not None:
+ tmp.update(self.template_overrides)
+ for k, v in tmp.items():
+ if "{{" in v:
+ import jinja2
+
+ self.templates[k] = lambda temp=v, **kwargs: jinja2.Template(
+ temp
+ ).render(**kwargs)
+ else:
+ self.templates[k] = v
+
+ def _process_gen(self, gens):
+ out = {}
+ for gen in gens:
+ dimension = {
+ k: (
+ v
+ if isinstance(v, list)
+ else range(v.get("start", 0), v["stop"], v.get("step", 1))
+ )
+ for k, v in gen["dimensions"].items()
+ }
+ products = (
+ dict(zip(dimension.keys(), values))
+ for values in itertools.product(*dimension.values())
+ )
+ for pr in products:
+ import jinja2
+
+ key = jinja2.Template(gen["key"]).render(**pr, **self.templates)
+ url = jinja2.Template(gen["url"]).render(**pr, **self.templates)
+ if ("offset" in gen) and ("length" in gen):
+ offset = int(
+ jinja2.Template(gen["offset"]).render(**pr, **self.templates)
+ )
+ length = int(
+ jinja2.Template(gen["length"]).render(**pr, **self.templates)
+ )
+ out[key] = [url, offset, length]
+ elif ("offset" in gen) ^ ("length" in gen):
+ raise ValueError(
+ "Both 'offset' and 'length' are required for a "
+ "reference generator entry if either is provided."
+ )
+ else:
+ out[key] = [url]
+ return out
+
+ def _dircache_from_items(self):
+ self.dircache = {"": []}
+ it = self.references.items()
+ for path, part in it:
+ if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"):
+ size = len(part)
+ elif len(part) == 1:
+ size = None
+ else:
+ _, _, size = part
+ par = path.rsplit("/", 1)[0] if "/" in path else ""
+ par0 = par
+ subdirs = [par0]
+ while par0 and par0 not in self.dircache:
+ # collect parent directories
+ par0 = self._parent(par0)
+ subdirs.append(par0)
+
+ subdirs.reverse()
+ for parent, child in zip(subdirs, subdirs[1:]):
+ # register newly discovered directories
+ assert child not in self.dircache
+ assert parent in self.dircache
+ self.dircache[parent].append(
+ {"name": child, "type": "directory", "size": 0}
+ )
+ self.dircache[child] = []
+
+ self.dircache[par].append({"name": path, "type": "file", "size": size})
+
+ def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs):
+ part_or_url, start0, end0 = self._cat_common(path)
+ # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection.
+ # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`.
+ if isinstance(part_or_url, bytes):
+ return io.BytesIO(part_or_url[start0:end0])
+
+ protocol, _ = split_protocol(part_or_url)
+ if start0 is None and end0 is None:
+ return self.fss[protocol]._open(
+ part_or_url,
+ mode,
+ block_size=block_size,
+ cache_options=cache_options,
+ **kwargs,
+ )
+
+ return ReferenceFile(
+ self,
+ path,
+ mode,
+ block_size=block_size,
+ cache_options=cache_options,
+ **kwargs,
+ )
+
+ def ls(self, path, detail=True, **kwargs):
+ logger.debug("list %s", path)
+ path = self._strip_protocol(path)
+ if isinstance(self.references, LazyReferenceMapper):
+ try:
+ return self.references.ls(path, detail)
+ except KeyError:
+ pass
+ raise FileNotFoundError(f"'{path}' is not a known key")
+ if not self.dircache:
+ self._dircache_from_items()
+ out = self._ls_from_cache(path)
+ if out is None:
+ raise FileNotFoundError(path)
+ if detail:
+ return out
+ return [o["name"] for o in out]
+
+ def exists(self, path, **kwargs): # overwrite auto-sync version
+ return self.isdir(path) or self.isfile(path)
+
+ def isdir(self, path): # overwrite auto-sync version
+ if self.dircache:
+ return path in self.dircache
+ elif isinstance(self.references, LazyReferenceMapper):
+ return path in self.references.listdir()
+ else:
+ # this may be faster than building dircache for single calls, but
+ # by looping will be slow for many calls; could cache it?
+ return any(_.startswith(f"{path}/") for _ in self.references)
+
+ def isfile(self, path): # overwrite auto-sync version
+ return path in self.references
+
+ async def _ls(self, path, detail=True, **kwargs): # calls fast sync code
+ return self.ls(path, detail, **kwargs)
+
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
+ if withdirs:
+ return super().find(
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs
+ )
+ if path:
+ path = self._strip_protocol(path)
+ r = sorted(k for k in self.references if k.startswith(path))
+ else:
+ r = sorted(self.references)
+ if detail:
+ if not self.dircache:
+ self._dircache_from_items()
+ return {k: self._ls_from_cache(k)[0] for k in r}
+ else:
+ return r
+
+ def info(self, path, **kwargs):
+ out = self.references.get(path)
+ if out is not None:
+ if isinstance(out, (str, bytes)):
+ # decode base64 here
+ return {"name": path, "type": "file", "size": len(out)}
+ elif len(out) > 1:
+ return {"name": path, "type": "file", "size": out[2]}
+ else:
+ out0 = [{"name": path, "type": "file", "size": None}]
+ else:
+ out = self.ls(path, True)
+ out0 = [o for o in out if o["name"] == path]
+ if not out0:
+ return {"name": path, "type": "directory", "size": 0}
+ if out0[0]["size"] is None:
+ # if this is a whole remote file, update size using remote FS
+ prot, _ = split_protocol(self.references[path][0])
+ out0[0]["size"] = self.fss[prot].size(self.references[path][0])
+ return out0[0]
+
+ async def _info(self, path, **kwargs): # calls fast sync code
+ return self.info(path)
+
+ async def _rm_file(self, path, **kwargs):
+ self.references.pop(
+ path, None
+ ) # ignores FileNotFound, just as well for directories
+ self.dircache.clear() # this is a bit heavy handed
+
+ async def _pipe_file(self, path, data, mode="overwrite", **kwargs):
+ if mode == "create" and self.exists(path):
+ raise FileExistsError
+ # can be str or bytes
+ self.references[path] = data
+ self.dircache.clear() # this is a bit heavy handed
+
+ async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
+ # puts binary
+ if mode == "create" and self.exists(rpath):
+ raise FileExistsError
+ with open(lpath, "rb") as f:
+ self.references[rpath] = f.read()
+ self.dircache.clear() # this is a bit heavy handed
+
+ def save_json(self, url, **storage_options):
+ """Write modified references into new location"""
+ out = {}
+ for k, v in self.references.items():
+ if isinstance(v, bytes):
+ try:
+ out[k] = v.decode("ascii")
+ except UnicodeDecodeError:
+ out[k] = (b"base64:" + base64.b64encode(v)).decode()
+ else:
+ out[k] = v
+ with fsspec.open(url, "wb", **storage_options) as f:
+ f.write(json.dumps({"version": 1, "refs": out}).encode())
+
+
+class ReferenceFile(AbstractBufferedFile):
+ def __init__(
+ self,
+ fs,
+ path,
+ mode="rb",
+ block_size="default",
+ autocommit=True,
+ cache_type="readahead",
+ cache_options=None,
+ size=None,
+ **kwargs,
+ ):
+ super().__init__(
+ fs,
+ path,
+ mode=mode,
+ block_size=block_size,
+ autocommit=autocommit,
+ size=size,
+ cache_type=cache_type,
+ cache_options=cache_options,
+ **kwargs,
+ )
+ part_or_url, self.start, self.end = self.fs._cat_common(self.path)
+ protocol, _ = split_protocol(part_or_url)
+ self.src_fs = self.fs.fss[protocol]
+ self.src_path = part_or_url
+ self._f = None
+
+ @property
+ def f(self):
+ if self._f is None or self._f.closed:
+ self._f = self.src_fs._open(
+ self.src_path,
+ mode=self.mode,
+ block_size=self.blocksize,
+ autocommit=self.autocommit,
+ cache_type="none",
+ **self.kwargs,
+ )
+ return self._f
+
+ def close(self):
+ if self._f is not None:
+ self._f.close()
+ return super().close()
+
+ def _fetch_range(self, start, end):
+ start = start + self.start
+ end = min(end + self.start, self.end)
+ self.f.seek(start)
+ return self.f.read(end - start)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/sftp.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/sftp.py
new file mode 100644
index 0000000000000000000000000000000000000000..77f7b370cd246f9a9bfd34141afc3edd728d13c3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/sftp.py
@@ -0,0 +1,180 @@
+import datetime
+import logging
+import os
+import types
+import uuid
+from stat import S_ISDIR, S_ISLNK
+
+import paramiko
+
+from .. import AbstractFileSystem
+from ..utils import infer_storage_options
+
+logger = logging.getLogger("fsspec.sftp")
+
+
+class SFTPFileSystem(AbstractFileSystem):
+ """Files over SFTP/SSH
+
+ Peer-to-peer filesystem over SSH using paramiko.
+
+ Note: if using this with the ``open`` or ``open_files``, with full URLs,
+ there is no way to tell if a path is relative, so all paths are assumed
+ to be absolute.
+ """
+
+ protocol = "sftp", "ssh"
+
+ def __init__(self, host, **ssh_kwargs):
+ """
+
+ Parameters
+ ----------
+ host: str
+ Hostname or IP as a string
+ temppath: str
+ Location on the server to put files, when within a transaction
+ ssh_kwargs: dict
+ Parameters passed on to connection. See details in
+ https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect
+ May include port, username, password...
+ """
+ if self._cached:
+ return
+ super().__init__(**ssh_kwargs)
+ self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory
+ self.host = host
+ self.ssh_kwargs = ssh_kwargs
+ self._connect()
+
+ def _connect(self):
+ logger.debug("Connecting to SFTP server %s", self.host)
+ self.client = paramiko.SSHClient()
+ self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+ self.client.connect(self.host, **self.ssh_kwargs)
+ self.ftp = self.client.open_sftp()
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ return infer_storage_options(path)["path"]
+
+ @staticmethod
+ def _get_kwargs_from_urls(urlpath):
+ out = infer_storage_options(urlpath)
+ out.pop("path", None)
+ out.pop("protocol", None)
+ return out
+
+ def mkdir(self, path, create_parents=True, mode=511):
+ logger.debug("Creating folder %s", path)
+ if self.exists(path):
+ raise FileExistsError(f"File exists: {path}")
+
+ if create_parents:
+ self.makedirs(path)
+ else:
+ self.ftp.mkdir(path, mode)
+
+ def makedirs(self, path, exist_ok=False, mode=511):
+ if self.exists(path) and not exist_ok:
+ raise FileExistsError(f"File exists: {path}")
+
+ parts = path.split("/")
+ new_path = "/" if path[:1] == "/" else ""
+
+ for part in parts:
+ if part:
+ new_path = f"{new_path}/{part}" if new_path else part
+ if not self.exists(new_path):
+ self.ftp.mkdir(new_path, mode)
+
+ def rmdir(self, path):
+ logger.debug("Removing folder %s", path)
+ self.ftp.rmdir(path)
+
+ def info(self, path):
+ stat = self._decode_stat(self.ftp.stat(path))
+ stat["name"] = path
+ return stat
+
+ @staticmethod
+ def _decode_stat(stat, parent_path=None):
+ if S_ISDIR(stat.st_mode):
+ t = "directory"
+ elif S_ISLNK(stat.st_mode):
+ t = "link"
+ else:
+ t = "file"
+ out = {
+ "name": "",
+ "size": stat.st_size,
+ "type": t,
+ "uid": stat.st_uid,
+ "gid": stat.st_gid,
+ "time": datetime.datetime.fromtimestamp(
+ stat.st_atime, tz=datetime.timezone.utc
+ ),
+ "mtime": datetime.datetime.fromtimestamp(
+ stat.st_mtime, tz=datetime.timezone.utc
+ ),
+ }
+ if parent_path:
+ out["name"] = "/".join([parent_path.rstrip("/"), stat.filename])
+ return out
+
+ def ls(self, path, detail=False):
+ logger.debug("Listing folder %s", path)
+ stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)]
+ if detail:
+ return stats
+ else:
+ paths = [stat["name"] for stat in stats]
+ return sorted(paths)
+
+ def put(self, lpath, rpath, callback=None, **kwargs):
+ logger.debug("Put file %s into %s", lpath, rpath)
+ self.ftp.put(lpath, rpath)
+
+ def get_file(self, rpath, lpath, **kwargs):
+ if self.isdir(rpath):
+ os.makedirs(lpath, exist_ok=True)
+ else:
+ self.ftp.get(self._strip_protocol(rpath), lpath)
+
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
+ """
+ block_size: int or None
+ If 0, no buffering, if 1, line buffering, if >1, buffer that many
+ bytes, if None use default from paramiko.
+ """
+ logger.debug("Opening file %s", path)
+ if kwargs.get("autocommit", True) is False:
+ # writes to temporary file, move on commit
+ path2 = "/".join([self.temppath, str(uuid.uuid4())])
+ f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1)
+ f.temppath = path2
+ f.targetpath = path
+ f.fs = self
+ f.commit = types.MethodType(commit_a_file, f)
+ f.discard = types.MethodType(discard_a_file, f)
+ else:
+ f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1)
+ return f
+
+ def _rm(self, path):
+ if self.isdir(path):
+ self.ftp.rmdir(path)
+ else:
+ self.ftp.remove(path)
+
+ def mv(self, old, new):
+ logger.debug("Renaming %s into %s", old, new)
+ self.ftp.posix_rename(old, new)
+
+
+def commit_a_file(self):
+ self.fs.mv(self.temppath, self.targetpath)
+
+
+def discard_a_file(self):
+ self.fs._rm(self.temppath)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/smb.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/smb.py
new file mode 100644
index 0000000000000000000000000000000000000000..db6b3f5c3702de90cf121ccca49f3ca2b580df9f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/smb.py
@@ -0,0 +1,416 @@
+"""
+This module contains SMBFileSystem class responsible for handling access to
+Windows Samba network shares by using package smbprotocol
+"""
+
+import datetime
+import re
+import uuid
+from stat import S_ISDIR, S_ISLNK
+
+import smbclient
+import smbprotocol.exceptions
+
+from .. import AbstractFileSystem
+from ..utils import infer_storage_options
+
+# ! pylint: disable=bad-continuation
+
+
+class SMBFileSystem(AbstractFileSystem):
+ """Allow reading and writing to Windows and Samba network shares.
+
+ When using `fsspec.open()` for getting a file-like object the URI
+ should be specified as this format:
+ ``smb://workgroup;user:password@server:port/share/folder/file.csv``.
+
+ Example::
+
+ >>> import fsspec
+ >>> with fsspec.open(
+ ... 'smb://myuser:mypassword@myserver.com/' 'share/folder/file.csv'
+ ... ) as smbfile:
+ ... df = pd.read_csv(smbfile, sep='|', header=None)
+
+ Note that you need to pass in a valid hostname or IP address for the host
+ component of the URL. Do not use the Windows/NetBIOS machine name for the
+ host component.
+
+ The first component of the path in the URL points to the name of the shared
+ folder. Subsequent path components will point to the directory/folder/file.
+
+ The URL components ``workgroup`` , ``user``, ``password`` and ``port`` may be
+ optional.
+
+ .. note::
+
+ For working this source require `smbprotocol`_ to be installed, e.g.::
+
+ $ pip install smbprotocol
+ # or
+ # pip install smbprotocol[kerberos]
+
+ .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements
+
+ Note: if using this with the ``open`` or ``open_files``, with full URLs,
+ there is no way to tell if a path is relative, so all paths are assumed
+ to be absolute.
+ """
+
+ protocol = "smb"
+
+ # pylint: disable=too-many-arguments
+ def __init__(
+ self,
+ host,
+ port=None,
+ username=None,
+ password=None,
+ timeout=60,
+ encrypt=None,
+ share_access=None,
+ register_session_retries=4,
+ register_session_retry_wait=1,
+ register_session_retry_factor=10,
+ auto_mkdir=False,
+ **kwargs,
+ ):
+ """
+ You can use _get_kwargs_from_urls to get some kwargs from
+ a reasonable SMB url.
+
+ Authentication will be anonymous or integrated if username/password are not
+ given.
+
+ Parameters
+ ----------
+ host: str
+ The remote server name/ip to connect to
+ port: int or None
+ Port to connect with. Usually 445, sometimes 139.
+ username: str or None
+ Username to connect with. Required if Kerberos auth is not being used.
+ password: str or None
+ User's password on the server, if using username
+ timeout: int
+ Connection timeout in seconds
+ encrypt: bool
+ Whether to force encryption or not, once this has been set to True
+ the session cannot be changed back to False.
+ share_access: str or None
+ Specifies the default access applied to file open operations
+ performed with this file system object.
+ This affects whether other processes can concurrently open a handle
+ to the same file.
+
+ - None (the default): exclusively locks the file until closed.
+ - 'r': Allow other handles to be opened with read access.
+ - 'w': Allow other handles to be opened with write access.
+ - 'd': Allow other handles to be opened with delete access.
+ register_session_retries: int
+ Number of retries to register a session with the server. Retries are not performed
+ for authentication errors, as they are considered as invalid credentials and not network
+ issues. If set to negative value, no register attempts will be performed.
+ register_session_retry_wait: int
+ Time in seconds to wait between each retry. Number must be non-negative.
+ register_session_retry_factor: int
+ Base factor for the wait time between each retry. The wait time
+ is calculated using exponential function. For factor=1 all wait times
+ will be equal to `register_session_retry_wait`. For any number of retries,
+ the last wait time will be equal to `register_session_retry_wait` and for retries>1
+ the first wait time will be equal to `register_session_retry_wait / factor`.
+ Number must be equal to or greater than 1. Optimal factor is 10.
+ auto_mkdir: bool
+ Whether, when opening a file, the directory containing it should
+ be created (if it doesn't already exist). This is assumed by pyarrow
+ and zarr-python code.
+ """
+ super().__init__(**kwargs)
+ self.host = host
+ self.port = port
+ self.username = username
+ self.password = password
+ self.timeout = timeout
+ self.encrypt = encrypt
+ self.temppath = kwargs.pop("temppath", "")
+ self.share_access = share_access
+ self.register_session_retries = register_session_retries
+ if register_session_retry_wait < 0:
+ raise ValueError(
+ "register_session_retry_wait must be a non-negative integer"
+ )
+ self.register_session_retry_wait = register_session_retry_wait
+ if register_session_retry_factor < 1:
+ raise ValueError(
+ "register_session_retry_factor must be a positive "
+ "integer equal to or greater than 1"
+ )
+ self.register_session_retry_factor = register_session_retry_factor
+ self.auto_mkdir = auto_mkdir
+ self._connect()
+
+ @property
+ def _port(self):
+ return 445 if self.port is None else self.port
+
+ def _connect(self):
+ import time
+
+ if self.register_session_retries <= -1:
+ return
+
+ retried_errors = []
+
+ wait_time = self.register_session_retry_wait
+ n_waits = (
+ self.register_session_retries - 1
+ ) # -1 = No wait time after the last retry
+ factor = self.register_session_retry_factor
+
+ # Generate wait times for each retry attempt.
+ # Wait times are calculated using exponential function. For factor=1 all wait times
+ # will be equal to `wait`. For any number of retries the last wait time will be
+ # equal to `wait` and for retries>2 the first wait time will be equal to `wait / factor`.
+ wait_times = iter(
+ factor ** (n / n_waits - 1) * wait_time for n in range(0, n_waits + 1)
+ )
+
+ for attempt in range(self.register_session_retries + 1):
+ try:
+ smbclient.register_session(
+ self.host,
+ username=self.username,
+ password=self.password,
+ port=self._port,
+ encrypt=self.encrypt,
+ connection_timeout=self.timeout,
+ )
+ return
+ except (
+ smbprotocol.exceptions.SMBAuthenticationError,
+ smbprotocol.exceptions.LogonFailure,
+ ):
+ # These exceptions should not be repeated, as they clearly indicate
+ # that the credentials are invalid and not a network issue.
+ raise
+ except ValueError as exc:
+ if re.findall(r"\[Errno -\d+]", str(exc)):
+ # This exception is raised by the smbprotocol.transport:Tcp.connect
+ # and originates from socket.gaierror (OSError). These exceptions might
+ # be raised due to network instability. We will retry to connect.
+ retried_errors.append(exc)
+ else:
+ # All another ValueError exceptions should be raised, as they are not
+ # related to network issues.
+ raise
+ except Exception as exc:
+ # Save the exception and retry to connect. This except might be dropped
+ # in the future, once all exceptions suited for retry are identified.
+ retried_errors.append(exc)
+
+ if attempt < self.register_session_retries:
+ time.sleep(next(wait_times))
+
+ # Raise last exception to inform user about the connection issues.
+ # Note: Should we use ExceptionGroup to raise all exceptions?
+ raise retried_errors[-1]
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ return infer_storage_options(path)["path"]
+
+ @staticmethod
+ def _get_kwargs_from_urls(path):
+ # smb://workgroup;user:password@host:port/share/folder/file.csv
+ out = infer_storage_options(path)
+ out.pop("path", None)
+ out.pop("protocol", None)
+ return out
+
+ def mkdir(self, path, create_parents=True, **kwargs):
+ wpath = _as_unc_path(self.host, path)
+ if create_parents:
+ smbclient.makedirs(wpath, exist_ok=False, port=self._port, **kwargs)
+ else:
+ smbclient.mkdir(wpath, port=self._port, **kwargs)
+
+ def makedirs(self, path, exist_ok=False):
+ if _share_has_path(path):
+ wpath = _as_unc_path(self.host, path)
+ smbclient.makedirs(wpath, exist_ok=exist_ok, port=self._port)
+
+ def rmdir(self, path):
+ if _share_has_path(path):
+ wpath = _as_unc_path(self.host, path)
+ smbclient.rmdir(wpath, port=self._port)
+
+ def info(self, path, **kwargs):
+ wpath = _as_unc_path(self.host, path)
+ stats = smbclient.stat(wpath, port=self._port, **kwargs)
+ if S_ISDIR(stats.st_mode):
+ stype = "directory"
+ elif S_ISLNK(stats.st_mode):
+ stype = "link"
+ else:
+ stype = "file"
+ res = {
+ "name": path + "/" if stype == "directory" else path,
+ "size": stats.st_size,
+ "type": stype,
+ "uid": stats.st_uid,
+ "gid": stats.st_gid,
+ "time": stats.st_atime,
+ "mtime": stats.st_mtime,
+ }
+ return res
+
+ def created(self, path):
+ """Return the created timestamp of a file as a datetime.datetime"""
+ wpath = _as_unc_path(self.host, path)
+ stats = smbclient.stat(wpath, port=self._port)
+ return datetime.datetime.fromtimestamp(stats.st_ctime, tz=datetime.timezone.utc)
+
+ def modified(self, path):
+ """Return the modified timestamp of a file as a datetime.datetime"""
+ wpath = _as_unc_path(self.host, path)
+ stats = smbclient.stat(wpath, port=self._port)
+ return datetime.datetime.fromtimestamp(stats.st_mtime, tz=datetime.timezone.utc)
+
+ def ls(self, path, detail=True, **kwargs):
+ unc = _as_unc_path(self.host, path)
+ listed = smbclient.listdir(unc, port=self._port, **kwargs)
+ dirs = ["/".join([path.rstrip("/"), p]) for p in listed]
+ if detail:
+ dirs = [self.info(d) for d in dirs]
+ return dirs
+
+ # pylint: disable=too-many-arguments
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=-1,
+ autocommit=True,
+ cache_options=None,
+ **kwargs,
+ ):
+ """
+ block_size: int or None
+ If 0, no buffering, 1, line buffering, >1, buffer that many bytes
+
+ Notes
+ -----
+ By specifying 'share_access' in 'kwargs' it is possible to override the
+ default shared access setting applied in the constructor of this object.
+ """
+ if self.auto_mkdir and "w" in mode:
+ self.makedirs(self._parent(path), exist_ok=True)
+ bls = block_size if block_size is not None and block_size >= 0 else -1
+ wpath = _as_unc_path(self.host, path)
+ share_access = kwargs.pop("share_access", self.share_access)
+ if "w" in mode and autocommit is False:
+ temp = _as_temp_path(self.host, path, self.temppath)
+ return SMBFileOpener(
+ wpath, temp, mode, port=self._port, block_size=bls, **kwargs
+ )
+ return smbclient.open_file(
+ wpath,
+ mode,
+ buffering=bls,
+ share_access=share_access,
+ port=self._port,
+ **kwargs,
+ )
+
+ def copy(self, path1, path2, **kwargs):
+ """Copy within two locations in the same filesystem"""
+ wpath1 = _as_unc_path(self.host, path1)
+ wpath2 = _as_unc_path(self.host, path2)
+ if self.auto_mkdir:
+ self.makedirs(self._parent(path2), exist_ok=True)
+ smbclient.copyfile(wpath1, wpath2, port=self._port, **kwargs)
+
+ def _rm(self, path):
+ if _share_has_path(path):
+ wpath = _as_unc_path(self.host, path)
+ stats = smbclient.stat(wpath, port=self._port)
+ if S_ISDIR(stats.st_mode):
+ smbclient.rmdir(wpath, port=self._port)
+ else:
+ smbclient.remove(wpath, port=self._port)
+
+ def mv(self, path1, path2, recursive=None, maxdepth=None, **kwargs):
+ wpath1 = _as_unc_path(self.host, path1)
+ wpath2 = _as_unc_path(self.host, path2)
+ smbclient.rename(wpath1, wpath2, port=self._port, **kwargs)
+
+
+def _as_unc_path(host, path):
+ rpath = path.replace("/", "\\")
+ unc = f"\\\\{host}{rpath}"
+ return unc
+
+
+def _as_temp_path(host, path, temppath):
+ share = path.split("/")[1]
+ temp_file = f"/{share}{temppath}/{uuid.uuid4()}"
+ unc = _as_unc_path(host, temp_file)
+ return unc
+
+
+def _share_has_path(path):
+ parts = path.count("/")
+ if path.endswith("/"):
+ return parts > 2
+ return parts > 1
+
+
+class SMBFileOpener:
+ """writes to remote temporary file, move on commit"""
+
+ def __init__(self, path, temp, mode, port=445, block_size=-1, **kwargs):
+ self.path = path
+ self.temp = temp
+ self.mode = mode
+ self.block_size = block_size
+ self.kwargs = kwargs
+ self.smbfile = None
+ self._incontext = False
+ self.port = port
+ self._open()
+
+ def _open(self):
+ if self.smbfile is None or self.smbfile.closed:
+ self.smbfile = smbclient.open_file(
+ self.temp,
+ self.mode,
+ port=self.port,
+ buffering=self.block_size,
+ **self.kwargs,
+ )
+
+ def commit(self):
+ """Move temp file to definitive on success."""
+ # TODO: use transaction support in SMB protocol
+ smbclient.replace(self.temp, self.path, port=self.port)
+
+ def discard(self):
+ """Remove the temp file on failure."""
+ smbclient.remove(self.temp, port=self.port)
+
+ def __fspath__(self):
+ return self.path
+
+ def __iter__(self):
+ return self.smbfile.__iter__()
+
+ def __getattr__(self, item):
+ return getattr(self.smbfile, item)
+
+ def __enter__(self):
+ self._incontext = True
+ return self.smbfile.__enter__()
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self._incontext = False
+ self.smbfile.__exit__(exc_type, exc_value, traceback)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/tar.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/tar.py
new file mode 100644
index 0000000000000000000000000000000000000000..412e5ba4d2cdea7db090dc96412e697909a38d78
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/tar.py
@@ -0,0 +1,124 @@
+import logging
+import tarfile
+
+import fsspec
+from fsspec.archive import AbstractArchiveFileSystem
+from fsspec.compression import compr
+from fsspec.utils import infer_compression
+
+typemap = {b"0": "file", b"5": "directory"}
+
+logger = logging.getLogger("tar")
+
+
+class TarFileSystem(AbstractArchiveFileSystem):
+ """Compressed Tar archives as a file-system (read-only)
+
+ Supports the following formats:
+ tar.gz, tar.bz2, tar.xz
+ """
+
+ root_marker = ""
+ protocol = "tar"
+ cachable = False
+
+ def __init__(
+ self,
+ fo="",
+ index_store=None,
+ target_options=None,
+ target_protocol=None,
+ compression=None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ target_options = target_options or {}
+
+ if isinstance(fo, str):
+ self.of = fsspec.open(fo, protocol=target_protocol, **target_options)
+ fo = self.of.open() # keep the reference
+
+ # Try to infer compression.
+ if compression is None:
+ name = None
+
+ # Try different ways to get hold of the filename. `fo` might either
+ # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an
+ # `fsspec.AbstractFileSystem` instance.
+ try:
+ # Amended io.BufferedReader or similar.
+ # This uses a "protocol extension" where original filenames are
+ # propagated to archive-like filesystems in order to let them
+ # infer the right compression appropriately.
+ if hasattr(fo, "original"):
+ name = fo.original
+
+ # fsspec.LocalFileOpener
+ elif hasattr(fo, "path"):
+ name = fo.path
+
+ # io.BufferedReader
+ elif hasattr(fo, "name"):
+ name = fo.name
+
+ # fsspec.AbstractFileSystem
+ elif hasattr(fo, "info"):
+ name = fo.info()["name"]
+
+ except Exception as ex:
+ logger.warning(
+ f"Unable to determine file name, not inferring compression: {ex}"
+ )
+
+ if name is not None:
+ compression = infer_compression(name)
+ logger.info(f"Inferred compression {compression} from file name {name}")
+
+ if compression is not None:
+ # TODO: tarfile already implements compression with modes like "'r:gz'",
+ # but then would seek to offset in the file work?
+ fo = compr[compression](fo)
+
+ self._fo_ref = fo
+ self.fo = fo # the whole instance is a context
+ self.tar = tarfile.TarFile(fileobj=self.fo)
+ self.dir_cache = None
+
+ self.index_store = index_store
+ self.index = None
+ self._index()
+
+ def _index(self):
+ # TODO: load and set saved index, if exists
+ out = {}
+ for ti in self.tar:
+ info = ti.get_info()
+ info["type"] = typemap.get(info["type"], "file")
+ name = ti.get_info()["name"].rstrip("/")
+ out[name] = (info, ti.offset_data)
+
+ self.index = out
+ # TODO: save index to self.index_store here, if set
+
+ def _get_dirs(self):
+ if self.dir_cache is not None:
+ return
+
+ # This enables ls to get directories as children as well as files
+ self.dir_cache = {
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
+ for dirname in self._all_dirnames(self.tar.getnames())
+ }
+ for member in self.tar.getmembers():
+ info = member.get_info()
+ info["name"] = info["name"].rstrip("/")
+ info["type"] = typemap.get(info["type"], "file")
+ self.dir_cache[info["name"]] = info
+
+ def _open(self, path, mode="rb", **kwargs):
+ if mode != "rb":
+ raise ValueError("Read-only filesystem implementation")
+ details, offset = self.index[path]
+ if details["type"] != "file":
+ raise ValueError("Can only handle regular files")
+ return self.tar.extractfile(path)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6e0d8446f875ec9578cccf055aeb47cd1c2e996
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py
@@ -0,0 +1,485 @@
+# https://hadoop.apache.org/docs/r1.0.4/webhdfs.html
+
+import logging
+import os
+import secrets
+import shutil
+import tempfile
+import uuid
+from contextlib import suppress
+from urllib.parse import quote
+
+import requests
+
+from ..spec import AbstractBufferedFile, AbstractFileSystem
+from ..utils import infer_storage_options, tokenize
+
+logger = logging.getLogger("webhdfs")
+
+
+class WebHDFS(AbstractFileSystem):
+ """
+ Interface to HDFS over HTTP using the WebHDFS API. Supports also HttpFS gateways.
+
+ Four auth mechanisms are supported:
+
+ insecure: no auth is done, and the user is assumed to be whoever they
+ say they are (parameter ``user``), or a predefined value such as
+ "dr.who" if not given
+ spnego: when kerberos authentication is enabled, auth is negotiated by
+ requests_kerberos https://github.com/requests/requests-kerberos .
+ This establishes a session based on existing kinit login and/or
+ specified principal/password; parameters are passed with ``kerb_kwargs``
+ token: uses an existing Hadoop delegation token from another secured
+ service. Indeed, this client can also generate such tokens when
+ not insecure. Note that tokens expire, but can be renewed (by a
+ previously specified user) and may allow for proxying.
+ basic-auth: used when both parameter ``user`` and parameter ``password``
+ are provided.
+
+ """
+
+ tempdir = str(tempfile.gettempdir())
+ protocol = "webhdfs", "webHDFS"
+
+ def __init__(
+ self,
+ host,
+ port=50070,
+ kerberos=False,
+ token=None,
+ user=None,
+ password=None,
+ proxy_to=None,
+ kerb_kwargs=None,
+ data_proxy=None,
+ use_https=False,
+ session_cert=None,
+ session_verify=True,
+ **kwargs,
+ ):
+ """
+ Parameters
+ ----------
+ host: str
+ Name-node address
+ port: int
+ Port for webHDFS
+ kerberos: bool
+ Whether to authenticate with kerberos for this connection
+ token: str or None
+ If given, use this token on every call to authenticate. A user
+ and user-proxy may be encoded in the token and should not be also
+ given
+ user: str or None
+ If given, assert the user name to connect with
+ password: str or None
+ If given, assert the password to use for basic auth. If password
+ is provided, user must be provided also
+ proxy_to: str or None
+ If given, the user has the authority to proxy, and this value is
+ the user in who's name actions are taken
+ kerb_kwargs: dict
+ Any extra arguments for HTTPKerberosAuth, see
+ ``_
+ data_proxy: dict, callable or None
+ If given, map data-node addresses. This can be necessary if the
+ HDFS cluster is behind a proxy, running on Docker or otherwise has
+ a mismatch between the host-names given by the name-node and the
+ address by which to refer to them from the client. If a dict,
+ maps host names ``host->data_proxy[host]``; if a callable, full
+ URLs are passed, and function must conform to
+ ``url->data_proxy(url)``.
+ use_https: bool
+ Whether to connect to the Name-node using HTTPS instead of HTTP
+ session_cert: str or Tuple[str, str] or None
+ Path to a certificate file, or tuple of (cert, key) files to use
+ for the requests.Session
+ session_verify: str, bool or None
+ Path to a certificate file to use for verifying the requests.Session.
+ kwargs
+ """
+ if self._cached:
+ return
+ super().__init__(**kwargs)
+ self.url = f"{'https' if use_https else 'http'}://{host}:{port}/webhdfs/v1"
+ self.kerb = kerberos
+ self.kerb_kwargs = kerb_kwargs or {}
+ self.pars = {}
+ self.proxy = data_proxy or {}
+ if token is not None:
+ if user is not None or proxy_to is not None:
+ raise ValueError(
+ "If passing a delegation token, must not set "
+ "user or proxy_to, as these are encoded in the"
+ " token"
+ )
+ self.pars["delegation"] = token
+ self.user = user
+ self.password = password
+
+ if password is not None:
+ if user is None:
+ raise ValueError(
+ "If passing a password, the user must also be"
+ "set in order to set up the basic-auth"
+ )
+ else:
+ if user is not None:
+ self.pars["user.name"] = user
+
+ if proxy_to is not None:
+ self.pars["doas"] = proxy_to
+ if kerberos and user is not None:
+ raise ValueError(
+ "If using Kerberos auth, do not specify the "
+ "user, this is handled by kinit."
+ )
+
+ self.session_cert = session_cert
+ self.session_verify = session_verify
+
+ self._connect()
+
+ self._fsid = f"webhdfs_{tokenize(host, port)}"
+
+ @property
+ def fsid(self):
+ return self._fsid
+
+ def _connect(self):
+ self.session = requests.Session()
+
+ if self.session_cert:
+ self.session.cert = self.session_cert
+
+ self.session.verify = self.session_verify
+
+ if self.kerb:
+ from requests_kerberos import HTTPKerberosAuth
+
+ self.session.auth = HTTPKerberosAuth(**self.kerb_kwargs)
+
+ if self.user is not None and self.password is not None:
+ from requests.auth import HTTPBasicAuth
+
+ self.session.auth = HTTPBasicAuth(self.user, self.password)
+
+ def _call(self, op, method="get", path=None, data=None, redirect=True, **kwargs):
+ path = self._strip_protocol(path) if path is not None else ""
+ url = self._apply_proxy(self.url + quote(path, safe="/="))
+ args = kwargs.copy()
+ args.update(self.pars)
+ args["op"] = op.upper()
+ logger.debug("sending %s with %s", url, method)
+ out = self.session.request(
+ method=method.upper(),
+ url=url,
+ params=args,
+ data=data,
+ allow_redirects=redirect,
+ )
+ if out.status_code in [400, 401, 403, 404, 500]:
+ try:
+ err = out.json()
+ msg = err["RemoteException"]["message"]
+ exp = err["RemoteException"]["exception"]
+ except (ValueError, KeyError):
+ pass
+ else:
+ if exp in ["IllegalArgumentException", "UnsupportedOperationException"]:
+ raise ValueError(msg)
+ elif exp in ["SecurityException", "AccessControlException"]:
+ raise PermissionError(msg)
+ elif exp in ["FileNotFoundException"]:
+ raise FileNotFoundError(msg)
+ else:
+ raise RuntimeError(msg)
+ out.raise_for_status()
+ return out
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ replication=None,
+ permissions=None,
+ **kwargs,
+ ):
+ """
+
+ Parameters
+ ----------
+ path: str
+ File location
+ mode: str
+ 'rb', 'wb', etc.
+ block_size: int
+ Client buffer size for read-ahead or write buffer
+ autocommit: bool
+ If False, writes to temporary file that only gets put in final
+ location upon commit
+ replication: int
+ Number of copies of file on the cluster, write mode only
+ permissions: str or int
+ posix permissions, write mode only
+ kwargs
+
+ Returns
+ -------
+ WebHDFile instance
+ """
+ block_size = block_size or self.blocksize
+ return WebHDFile(
+ self,
+ path,
+ mode=mode,
+ block_size=block_size,
+ tempdir=self.tempdir,
+ autocommit=autocommit,
+ replication=replication,
+ permissions=permissions,
+ )
+
+ @staticmethod
+ def _process_info(info):
+ info["type"] = info["type"].lower()
+ info["size"] = info["length"]
+ return info
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ return infer_storage_options(path)["path"]
+
+ @staticmethod
+ def _get_kwargs_from_urls(urlpath):
+ out = infer_storage_options(urlpath)
+ out.pop("path", None)
+ out.pop("protocol", None)
+ if "username" in out:
+ out["user"] = out.pop("username")
+ return out
+
+ def info(self, path):
+ out = self._call("GETFILESTATUS", path=path)
+ info = out.json()["FileStatus"]
+ info["name"] = path
+ return self._process_info(info)
+
+ def ls(self, path, detail=False):
+ out = self._call("LISTSTATUS", path=path)
+ infos = out.json()["FileStatuses"]["FileStatus"]
+ for info in infos:
+ self._process_info(info)
+ info["name"] = path.rstrip("/") + "/" + info["pathSuffix"]
+ if detail:
+ return sorted(infos, key=lambda i: i["name"])
+ else:
+ return sorted(info["name"] for info in infos)
+
+ def content_summary(self, path):
+ """Total numbers of files, directories and bytes under path"""
+ out = self._call("GETCONTENTSUMMARY", path=path)
+ return out.json()["ContentSummary"]
+
+ def ukey(self, path):
+ """Checksum info of file, giving method and result"""
+ out = self._call("GETFILECHECKSUM", path=path, redirect=False)
+ if "Location" in out.headers:
+ location = self._apply_proxy(out.headers["Location"])
+ out2 = self.session.get(location)
+ out2.raise_for_status()
+ return out2.json()["FileChecksum"]
+ else:
+ out.raise_for_status()
+ return out.json()["FileChecksum"]
+
+ def home_directory(self):
+ """Get user's home directory"""
+ out = self._call("GETHOMEDIRECTORY")
+ return out.json()["Path"]
+
+ def get_delegation_token(self, renewer=None):
+ """Retrieve token which can give the same authority to other uses
+
+ Parameters
+ ----------
+ renewer: str or None
+ User who may use this token; if None, will be current user
+ """
+ if renewer:
+ out = self._call("GETDELEGATIONTOKEN", renewer=renewer)
+ else:
+ out = self._call("GETDELEGATIONTOKEN")
+ t = out.json()["Token"]
+ if t is None:
+ raise ValueError("No token available for this user/security context")
+ return t["urlString"]
+
+ def renew_delegation_token(self, token):
+ """Make token live longer. Returns new expiry time"""
+ out = self._call("RENEWDELEGATIONTOKEN", method="put", token=token)
+ return out.json()["long"]
+
+ def cancel_delegation_token(self, token):
+ """Stop the token from being useful"""
+ self._call("CANCELDELEGATIONTOKEN", method="put", token=token)
+
+ def chmod(self, path, mod):
+ """Set the permission at path
+
+ Parameters
+ ----------
+ path: str
+ location to set (file or directory)
+ mod: str or int
+ posix epresentation or permission, give as oct string, e.g, '777'
+ or 0o777
+ """
+ self._call("SETPERMISSION", method="put", path=path, permission=mod)
+
+ def chown(self, path, owner=None, group=None):
+ """Change owning user and/or group"""
+ kwargs = {}
+ if owner is not None:
+ kwargs["owner"] = owner
+ if group is not None:
+ kwargs["group"] = group
+ self._call("SETOWNER", method="put", path=path, **kwargs)
+
+ def set_replication(self, path, replication):
+ """
+ Set file replication factor
+
+ Parameters
+ ----------
+ path: str
+ File location (not for directories)
+ replication: int
+ Number of copies of file on the cluster. Should be smaller than
+ number of data nodes; normally 3 on most systems.
+ """
+ self._call("SETREPLICATION", path=path, method="put", replication=replication)
+
+ def mkdir(self, path, **kwargs):
+ self._call("MKDIRS", method="put", path=path)
+
+ def makedirs(self, path, exist_ok=False):
+ if exist_ok is False and self.exists(path):
+ raise FileExistsError(path)
+ self.mkdir(path)
+
+ def mv(self, path1, path2, **kwargs):
+ self._call("RENAME", method="put", path=path1, destination=path2)
+
+ def rm(self, path, recursive=False, **kwargs):
+ self._call(
+ "DELETE",
+ method="delete",
+ path=path,
+ recursive="true" if recursive else "false",
+ )
+
+ def rm_file(self, path, **kwargs):
+ self.rm(path)
+
+ def cp_file(self, lpath, rpath, **kwargs):
+ with self.open(lpath) as lstream:
+ tmp_fname = "/".join([self._parent(rpath), f".tmp.{secrets.token_hex(16)}"])
+ # Perform an atomic copy (stream to a temporary file and
+ # move it to the actual destination).
+ try:
+ with self.open(tmp_fname, "wb") as rstream:
+ shutil.copyfileobj(lstream, rstream)
+ self.mv(tmp_fname, rpath)
+ except BaseException:
+ with suppress(FileNotFoundError):
+ self.rm(tmp_fname)
+ raise
+
+ def _apply_proxy(self, location):
+ if self.proxy and callable(self.proxy):
+ location = self.proxy(location)
+ elif self.proxy:
+ # as a dict
+ for k, v in self.proxy.items():
+ location = location.replace(k, v, 1)
+ return location
+
+
+class WebHDFile(AbstractBufferedFile):
+ """A file living in HDFS over webHDFS"""
+
+ def __init__(self, fs, path, **kwargs):
+ super().__init__(fs, path, **kwargs)
+ kwargs = kwargs.copy()
+ if kwargs.get("permissions", None) is None:
+ kwargs.pop("permissions", None)
+ if kwargs.get("replication", None) is None:
+ kwargs.pop("replication", None)
+ self.permissions = kwargs.pop("permissions", 511)
+ tempdir = kwargs.pop("tempdir")
+ if kwargs.pop("autocommit", False) is False:
+ self.target = self.path
+ self.path = os.path.join(tempdir, str(uuid.uuid4()))
+
+ def _upload_chunk(self, final=False):
+ """Write one part of a multi-block file upload
+
+ Parameters
+ ==========
+ final: bool
+ This is the last block, so should complete file, if
+ self.autocommit is True.
+ """
+ out = self.fs.session.post(
+ self.location,
+ data=self.buffer.getvalue(),
+ headers={"content-type": "application/octet-stream"},
+ )
+ out.raise_for_status()
+ return True
+
+ def _initiate_upload(self):
+ """Create remote file/upload"""
+ kwargs = self.kwargs.copy()
+ if "a" in self.mode:
+ op, method = "APPEND", "POST"
+ else:
+ op, method = "CREATE", "PUT"
+ kwargs["overwrite"] = "true"
+ out = self.fs._call(op, method, self.path, redirect=False, **kwargs)
+ location = self.fs._apply_proxy(out.headers["Location"])
+ if "w" in self.mode:
+ # create empty file to append to
+ out2 = self.fs.session.put(
+ location, headers={"content-type": "application/octet-stream"}
+ )
+ out2.raise_for_status()
+ # after creating empty file, change location to append to
+ out2 = self.fs._call("APPEND", "POST", self.path, redirect=False, **kwargs)
+ self.location = self.fs._apply_proxy(out2.headers["Location"])
+
+ def _fetch_range(self, start, end):
+ start = max(start, 0)
+ end = min(self.size, end)
+ if start >= end or start >= self.size:
+ return b""
+ out = self.fs._call(
+ "OPEN", path=self.path, offset=start, length=end - start, redirect=False
+ )
+ out.raise_for_status()
+ if "Location" in out.headers:
+ location = out.headers["Location"]
+ out2 = self.fs.session.get(self.fs._apply_proxy(location))
+ return out2.content
+ else:
+ return out.content
+
+ def commit(self):
+ self.fs.mv(self.path, self.target)
+
+ def discard(self):
+ self.fs.rm(self.path)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/zip.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/zip.py
new file mode 100644
index 0000000000000000000000000000000000000000..6db3ae27806106a19a366886ab4b183f85c1cb1a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/implementations/zip.py
@@ -0,0 +1,177 @@
+import os
+import zipfile
+
+import fsspec
+from fsspec.archive import AbstractArchiveFileSystem
+
+
+class ZipFileSystem(AbstractArchiveFileSystem):
+ """Read/Write contents of ZIP archive as a file-system
+
+ Keeps file object open while instance lives.
+
+ This class is pickleable, but not necessarily thread-safe
+ """
+
+ root_marker = ""
+ protocol = "zip"
+ cachable = False
+
+ def __init__(
+ self,
+ fo="",
+ mode="r",
+ target_protocol=None,
+ target_options=None,
+ compression=zipfile.ZIP_STORED,
+ allowZip64=True,
+ compresslevel=None,
+ **kwargs,
+ ):
+ """
+ Parameters
+ ----------
+ fo: str or file-like
+ Contains ZIP, and must exist. If a str, will fetch file using
+ :meth:`~fsspec.open_files`, which must return one file exactly.
+ mode: str
+ Accept: "r", "w", "a"
+ target_protocol: str (optional)
+ If ``fo`` is a string, this value can be used to override the
+ FS protocol inferred from a URL
+ target_options: dict (optional)
+ Kwargs passed when instantiating the target FS, if ``fo`` is
+ a string.
+ compression, allowZip64, compresslevel: passed to ZipFile
+ Only relevant when creating a ZIP
+ """
+ super().__init__(self, **kwargs)
+ if mode not in set("rwa"):
+ raise ValueError(f"mode '{mode}' no understood")
+ self.mode = mode
+ if isinstance(fo, (str, os.PathLike)):
+ if mode == "a":
+ m = "r+b"
+ else:
+ m = mode + "b"
+ fo = fsspec.open(
+ fo, mode=m, protocol=target_protocol, **(target_options or {})
+ )
+ self.force_zip_64 = allowZip64
+ self.of = fo
+ self.fo = fo.__enter__() # the whole instance is a context
+ self.zip = zipfile.ZipFile(
+ self.fo,
+ mode=mode,
+ compression=compression,
+ allowZip64=allowZip64,
+ compresslevel=compresslevel,
+ )
+ self.dir_cache = None
+
+ @classmethod
+ def _strip_protocol(cls, path):
+ # zip file paths are always relative to the archive root
+ return super()._strip_protocol(path).lstrip("/")
+
+ def __del__(self):
+ if hasattr(self, "zip"):
+ self.close()
+ del self.zip
+
+ def close(self):
+ """Commits any write changes to the file. Done on ``del`` too."""
+ self.zip.close()
+
+ def _get_dirs(self):
+ if self.dir_cache is None or self.mode in set("wa"):
+ # when writing, dir_cache is always in the ZipFile's attributes,
+ # not read from the file.
+ files = self.zip.infolist()
+ self.dir_cache = {
+ dirname.rstrip("/"): {
+ "name": dirname.rstrip("/"),
+ "size": 0,
+ "type": "directory",
+ }
+ for dirname in self._all_dirnames(self.zip.namelist())
+ }
+ for z in files:
+ f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__}
+ f.update(
+ {
+ "name": z.filename.rstrip("/"),
+ "size": z.file_size,
+ "type": ("directory" if z.is_dir() else "file"),
+ }
+ )
+ self.dir_cache[f["name"]] = f
+
+ def pipe_file(self, path, value, **kwargs):
+ # override upstream, because we know the exact file size in this case
+ self.zip.writestr(path, value, **kwargs)
+
+ def _open(
+ self,
+ path,
+ mode="rb",
+ block_size=None,
+ autocommit=True,
+ cache_options=None,
+ **kwargs,
+ ):
+ path = self._strip_protocol(path)
+ if "r" in mode and self.mode in set("wa"):
+ if self.exists(path):
+ raise OSError("ZipFS can only be open for reading or writing, not both")
+ raise FileNotFoundError(path)
+ if "r" in self.mode and "w" in mode:
+ raise OSError("ZipFS can only be open for reading or writing, not both")
+ out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64)
+ if "r" in mode:
+ info = self.info(path)
+ out.size = info["size"]
+ out.name = info["name"]
+ return out
+
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
+ if maxdepth is not None and maxdepth < 1:
+ raise ValueError("maxdepth must be at least 1")
+
+ # Remove the leading slash, as the zip file paths are always
+ # given without a leading slash
+ path = path.lstrip("/")
+ path_parts = list(filter(lambda s: bool(s), path.split("/")))
+
+ def _matching_starts(file_path):
+ file_parts = filter(lambda s: bool(s), file_path.split("/"))
+ return all(a == b for a, b in zip(path_parts, file_parts))
+
+ self._get_dirs()
+
+ result = {}
+ # To match posix find, if an exact file name is given, we should
+ # return only that file
+ if path in self.dir_cache and self.dir_cache[path]["type"] == "file":
+ result[path] = self.dir_cache[path]
+ return result if detail else [path]
+
+ for file_path, file_info in self.dir_cache.items():
+ if not (path == "" or _matching_starts(file_path)):
+ continue
+
+ if file_info["type"] == "directory":
+ if withdirs:
+ if file_path not in result:
+ result[file_path.strip("/")] = file_info
+ continue
+
+ if file_path not in result:
+ result[file_path] = file_info if detail else None
+
+ if maxdepth:
+ path_depth = path.count("/")
+ result = {
+ k: v for k, v in result.items() if k.count("/") - path_depth < maxdepth
+ }
+ return result if detail else sorted(result)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ed2ad802ecaf021106c25c03112f29e75c7b2f8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py
@@ -0,0 +1,289 @@
+import os
+from hashlib import md5
+
+import pytest
+
+from fsspec.implementations.local import LocalFileSystem
+from fsspec.tests.abstract.copy import AbstractCopyTests # noqa: F401
+from fsspec.tests.abstract.get import AbstractGetTests # noqa: F401
+from fsspec.tests.abstract.open import AbstractOpenTests # noqa: F401
+from fsspec.tests.abstract.pipe import AbstractPipeTests # noqa: F401
+from fsspec.tests.abstract.put import AbstractPutTests # noqa: F401
+
+
+class BaseAbstractFixtures:
+ """
+ Abstract base class containing fixtures that are used by but never need to
+ be overridden in derived filesystem-specific classes to run the abstract
+ tests on such filesystems.
+ """
+
+ @pytest.fixture
+ def fs_bulk_operations_scenario_0(self, fs, fs_join, fs_path):
+ """
+ Scenario on remote filesystem that is used for many cp/get/put tests.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._bulk_operations_scenario_0(fs, fs_join, fs_path)
+ yield source
+ fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def fs_glob_edge_cases_files(self, fs, fs_join, fs_path):
+ """
+ Scenario on remote filesystem that is used for glob edge cases cp/get/put tests.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._glob_edge_cases_files(fs, fs_join, fs_path)
+ yield source
+ fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def fs_dir_and_file_with_same_name_prefix(self, fs, fs_join, fs_path):
+ """
+ Scenario on remote filesystem that is used to check cp/get/put on directory
+ and file with the same name prefixes.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._dir_and_file_with_same_name_prefix(fs, fs_join, fs_path)
+ yield source
+ fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def fs_10_files_with_hashed_names(self, fs, fs_join, fs_path):
+ """
+ Scenario on remote filesystem that is used to check cp/get/put files order
+ when source and destination are lists.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._10_files_with_hashed_names(fs, fs_join, fs_path)
+ yield source
+ fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def fs_target(self, fs, fs_join, fs_path):
+ """
+ Return name of remote directory that does not yet exist to copy into.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ target = fs_join(fs_path, "target")
+ yield target
+ if fs.exists(target):
+ fs.rm(target, recursive=True)
+
+ @pytest.fixture
+ def local_bulk_operations_scenario_0(self, local_fs, local_join, local_path):
+ """
+ Scenario on local filesystem that is used for many cp/get/put tests.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._bulk_operations_scenario_0(local_fs, local_join, local_path)
+ yield source
+ local_fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def local_glob_edge_cases_files(self, local_fs, local_join, local_path):
+ """
+ Scenario on local filesystem that is used for glob edge cases cp/get/put tests.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._glob_edge_cases_files(local_fs, local_join, local_path)
+ yield source
+ local_fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def local_dir_and_file_with_same_name_prefix(
+ self, local_fs, local_join, local_path
+ ):
+ """
+ Scenario on local filesystem that is used to check cp/get/put on directory
+ and file with the same name prefixes.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._dir_and_file_with_same_name_prefix(
+ local_fs, local_join, local_path
+ )
+ yield source
+ local_fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def local_10_files_with_hashed_names(self, local_fs, local_join, local_path):
+ """
+ Scenario on local filesystem that is used to check cp/get/put files order
+ when source and destination are lists.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ source = self._10_files_with_hashed_names(local_fs, local_join, local_path)
+ yield source
+ local_fs.rm(source, recursive=True)
+
+ @pytest.fixture
+ def local_target(self, local_fs, local_join, local_path):
+ """
+ Return name of local directory that does not yet exist to copy into.
+
+ Cleans up at the end of each test it which it is used.
+ """
+ target = local_join(local_path, "target")
+ yield target
+ if local_fs.exists(target):
+ local_fs.rm(target, recursive=True)
+
+ def _glob_edge_cases_files(self, some_fs, some_join, some_path):
+ """
+ Scenario that is used for glob edge cases cp/get/put tests.
+ Creates the following directory and file structure:
+
+ 📁 source
+ ├── 📄 file1
+ ├── 📄 file2
+ ├── 📁 subdir0
+ │ ├── 📄 subfile1
+ │ ├── 📄 subfile2
+ │ └── 📁 nesteddir
+ │ └── 📄 nestedfile
+ └── 📁 subdir1
+ ├── 📄 subfile1
+ ├── 📄 subfile2
+ └── 📁 nesteddir
+ └── 📄 nestedfile
+ """
+ source = some_join(some_path, "source")
+ some_fs.touch(some_join(source, "file1"))
+ some_fs.touch(some_join(source, "file2"))
+
+ for subdir_idx in range(2):
+ subdir = some_join(source, f"subdir{subdir_idx}")
+ nesteddir = some_join(subdir, "nesteddir")
+ some_fs.makedirs(nesteddir)
+ some_fs.touch(some_join(subdir, "subfile1"))
+ some_fs.touch(some_join(subdir, "subfile2"))
+ some_fs.touch(some_join(nesteddir, "nestedfile"))
+
+ return source
+
+ def _bulk_operations_scenario_0(self, some_fs, some_join, some_path):
+ """
+ Scenario that is used for many cp/get/put tests. Creates the following
+ directory and file structure:
+
+ 📁 source
+ ├── 📄 file1
+ ├── 📄 file2
+ └── 📁 subdir
+ ├── 📄 subfile1
+ ├── 📄 subfile2
+ └── 📁 nesteddir
+ └── 📄 nestedfile
+ """
+ source = some_join(some_path, "source")
+ subdir = some_join(source, "subdir")
+ nesteddir = some_join(subdir, "nesteddir")
+ some_fs.makedirs(nesteddir)
+ some_fs.touch(some_join(source, "file1"))
+ some_fs.touch(some_join(source, "file2"))
+ some_fs.touch(some_join(subdir, "subfile1"))
+ some_fs.touch(some_join(subdir, "subfile2"))
+ some_fs.touch(some_join(nesteddir, "nestedfile"))
+ return source
+
+ def _dir_and_file_with_same_name_prefix(self, some_fs, some_join, some_path):
+ """
+ Scenario that is used to check cp/get/put on directory and file with
+ the same name prefixes. Creates the following directory and file structure:
+
+ 📁 source
+ ├── 📄 subdir.txt
+ └── 📁 subdir
+ └── 📄 subfile.txt
+ """
+ source = some_join(some_path, "source")
+ subdir = some_join(source, "subdir")
+ file = some_join(source, "subdir.txt")
+ subfile = some_join(subdir, "subfile.txt")
+ some_fs.makedirs(subdir)
+ some_fs.touch(file)
+ some_fs.touch(subfile)
+ return source
+
+ def _10_files_with_hashed_names(self, some_fs, some_join, some_path):
+ """
+ Scenario that is used to check cp/get/put files order when source and
+ destination are lists. Creates the following directory and file structure:
+
+ 📁 source
+ └── 📄 {hashed([0-9])}.txt
+ """
+ source = some_join(some_path, "source")
+ for i in range(10):
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
+ path = some_join(source, f"{hashed_i}.txt")
+ some_fs.pipe(path=path, value=f"{i}".encode())
+ return source
+
+
+class AbstractFixtures(BaseAbstractFixtures):
+ """
+ Abstract base class containing fixtures that may be overridden in derived
+ filesystem-specific classes to run the abstract tests on such filesystems.
+
+ For any particular filesystem some of these fixtures must be overridden,
+ such as ``fs`` and ``fs_path``, and others may be overridden if the
+ default functions here are not appropriate, such as ``fs_join``.
+ """
+
+ @pytest.fixture
+ def fs(self):
+ raise NotImplementedError("This function must be overridden in derived classes")
+
+ @pytest.fixture
+ def fs_join(self):
+ """
+ Return a function that joins its arguments together into a path.
+
+ Most fsspec implementations join paths in a platform-dependent way,
+ but some will override this to always use a forward slash.
+ """
+ return os.path.join
+
+ @pytest.fixture
+ def fs_path(self):
+ raise NotImplementedError("This function must be overridden in derived classes")
+
+ @pytest.fixture(scope="class")
+ def local_fs(self):
+ # Maybe need an option for auto_mkdir=False? This is only relevant
+ # for certain implementations.
+ return LocalFileSystem(auto_mkdir=True)
+
+ @pytest.fixture
+ def local_join(self):
+ """
+ Return a function that joins its arguments together into a path, on
+ the local filesystem.
+ """
+ return os.path.join
+
+ @pytest.fixture
+ def local_path(self, tmpdir):
+ return tmpdir
+
+ @pytest.fixture
+ def supports_empty_directories(self):
+ """
+ Return whether this implementation supports empty directories.
+ """
+ return True
+
+ @pytest.fixture
+ def fs_sanitize_path(self):
+ return lambda x: x
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0ea0129c1adc5f2499dcd08122b6a82fd7b2e2a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/common.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/common.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48d9fe6bdf5257e4520de420075e16e8d9a6fc12
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/common.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/copy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/copy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1145d286b8aa7edf4ed368efd28eacc4ad7be8eb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/copy.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/get.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/get.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..530f799c5d9c04de2d0c3e6041ee1a463fee6288
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/get.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/mv.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/mv.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72127e41584be2516495710444008ce6e0df135f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/mv.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/open.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/open.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6921aad70e4f0c5f4f96e9dbd5dacd5135a095bf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/open.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/pipe.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/pipe.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..12b66cf02c6d1933fd93641034cadfeae34e8a88
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/pipe.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/put.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/put.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bdf5ee7489babea76a8bec5720a3656bec9425a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/__pycache__/put.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..22e7c4140404ab2a8928689721419cf05c2760b9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/common.py
@@ -0,0 +1,175 @@
+GLOB_EDGE_CASES_TESTS = {
+ "argnames": ("path", "recursive", "maxdepth", "expected"),
+ "argvalues": [
+ ("fil?1", False, None, ["file1"]),
+ ("fil?1", True, None, ["file1"]),
+ ("file[1-2]", False, None, ["file1", "file2"]),
+ ("file[1-2]", True, None, ["file1", "file2"]),
+ ("*", False, None, ["file1", "file2"]),
+ (
+ "*",
+ True,
+ None,
+ [
+ "file1",
+ "file2",
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir0/nesteddir/nestedfile",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ "subdir1/nesteddir/nestedfile",
+ ],
+ ),
+ ("*", True, 1, ["file1", "file2"]),
+ (
+ "*",
+ True,
+ 2,
+ [
+ "file1",
+ "file2",
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ ],
+ ),
+ ("*1", False, None, ["file1"]),
+ (
+ "*1",
+ True,
+ None,
+ [
+ "file1",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ "subdir1/nesteddir/nestedfile",
+ ],
+ ),
+ ("*1", True, 2, ["file1", "subdir1/subfile1", "subdir1/subfile2"]),
+ (
+ "**",
+ False,
+ None,
+ [
+ "file1",
+ "file2",
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir0/nesteddir/nestedfile",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ "subdir1/nesteddir/nestedfile",
+ ],
+ ),
+ (
+ "**",
+ True,
+ None,
+ [
+ "file1",
+ "file2",
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir0/nesteddir/nestedfile",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ "subdir1/nesteddir/nestedfile",
+ ],
+ ),
+ ("**", True, 1, ["file1", "file2"]),
+ (
+ "**",
+ True,
+ 2,
+ [
+ "file1",
+ "file2",
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir0/nesteddir/nestedfile",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ "subdir1/nesteddir/nestedfile",
+ ],
+ ),
+ (
+ "**",
+ False,
+ 2,
+ [
+ "file1",
+ "file2",
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ ],
+ ),
+ ("**/*1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
+ (
+ "**/*1",
+ True,
+ None,
+ [
+ "file1",
+ "subdir0/subfile1",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ "subdir1/nesteddir/nestedfile",
+ ],
+ ),
+ ("**/*1", True, 1, ["file1"]),
+ (
+ "**/*1",
+ True,
+ 2,
+ ["file1", "subdir0/subfile1", "subdir1/subfile1", "subdir1/subfile2"],
+ ),
+ ("**/*1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
+ ("**/subdir0", False, None, []),
+ ("**/subdir0", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]),
+ ("**/subdir0/nested*", False, 2, []),
+ ("**/subdir0/nested*", True, 2, ["nestedfile"]),
+ ("subdir[1-2]", False, None, []),
+ ("subdir[1-2]", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]),
+ ("subdir[1-2]", True, 2, ["subfile1", "subfile2"]),
+ ("subdir[0-1]", False, None, []),
+ (
+ "subdir[0-1]",
+ True,
+ None,
+ [
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir0/nesteddir/nestedfile",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ "subdir1/nesteddir/nestedfile",
+ ],
+ ),
+ (
+ "subdir[0-1]/*fil[e]*",
+ False,
+ None,
+ [
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ ],
+ ),
+ (
+ "subdir[0-1]/*fil[e]*",
+ True,
+ None,
+ [
+ "subdir0/subfile1",
+ "subdir0/subfile2",
+ "subdir1/subfile1",
+ "subdir1/subfile2",
+ ],
+ ),
+ ],
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py
new file mode 100644
index 0000000000000000000000000000000000000000..e39e57e5f7d52bfda8ab5e2398b04cc2303630a0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py
@@ -0,0 +1,557 @@
+from hashlib import md5
+from itertools import product
+
+import pytest
+
+from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS
+
+
+class AbstractCopyTests:
+ def test_copy_file_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ fs_target,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1a
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ fs.touch(fs_join(target, "dummy"))
+ assert fs.isdir(target)
+
+ target_file2 = fs_join(target, "file2")
+ target_subfile1 = fs_join(target, "subfile1")
+
+ # Copy from source directory
+ fs.cp(fs_join(source, "file2"), target)
+ assert fs.isfile(target_file2)
+
+ # Copy from sub directory
+ fs.cp(fs_join(source, "subdir", "subfile1"), target)
+ assert fs.isfile(target_subfile1)
+
+ # Remove copied files
+ fs.rm([target_file2, target_subfile1])
+ assert not fs.exists(target_file2)
+ assert not fs.exists(target_subfile1)
+
+ # Repeat with trailing slash on target
+ fs.cp(fs_join(source, "file2"), target + "/")
+ assert fs.isdir(target)
+ assert fs.isfile(target_file2)
+
+ fs.cp(fs_join(source, "subdir", "subfile1"), target + "/")
+ assert fs.isfile(target_subfile1)
+
+ def test_copy_file_to_new_directory(
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
+ ):
+ # Copy scenario 1b
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ fs.cp(
+ fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir/")
+ ) # Note trailing slash
+ assert fs.isdir(target)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+
+ def test_copy_file_to_file_in_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ fs_target,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1c
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ fs.touch(fs_join(target, "dummy"))
+ assert fs.isdir(target)
+
+ fs.cp(fs_join(source, "subdir", "subfile1"), fs_join(target, "newfile"))
+ assert fs.isfile(fs_join(target, "newfile"))
+
+ def test_copy_file_to_file_in_new_directory(
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
+ ):
+ # Copy scenario 1d
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ fs.cp(
+ fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir", "newfile")
+ )
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "newfile"))
+
+ def test_copy_directory_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ fs_target,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1e
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ dummy = fs_join(target, "dummy")
+ fs.touch(dummy)
+ assert fs.isdir(target)
+
+ for source_slash, target_slash in zip([False, True], [False, True]):
+ s = fs_join(source, "subdir")
+ if source_slash:
+ s += "/"
+ t = target + "/" if target_slash else target
+
+ # Without recursive does nothing
+ fs.cp(s, t)
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # With recursive
+ fs.cp(s, t, recursive=True)
+ if source_slash:
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert fs.isdir(fs_join(target, "nesteddir"))
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ fs_join(target, "nesteddir"),
+ ],
+ recursive=True,
+ )
+ else:
+ assert fs.isdir(fs_join(target, "subdir"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
+ assert fs.isdir(fs_join(target, "subdir", "nesteddir"))
+ assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile"))
+
+ fs.rm(fs_join(target, "subdir"), recursive=True)
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # Limit recursive by maxdepth
+ fs.cp(s, t, recursive=True, maxdepth=1)
+ if source_slash:
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert not fs.exists(fs_join(target, "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ else:
+ assert fs.isdir(fs_join(target, "subdir"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "subdir", "nesteddir"))
+
+ fs.rm(fs_join(target, "subdir"), recursive=True)
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ def test_copy_directory_to_new_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ fs_target,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1f
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ for source_slash, target_slash in zip([False, True], [False, True]):
+ s = fs_join(source, "subdir")
+ if source_slash:
+ s += "/"
+ t = fs_join(target, "newdir")
+ if target_slash:
+ t += "/"
+
+ # Without recursive does nothing
+ fs.cp(s, t)
+ if supports_empty_directories:
+ assert fs.ls(target) == []
+ else:
+ with pytest.raises(FileNotFoundError):
+ fs.ls(target)
+
+ # With recursive
+ fs.cp(s, t, recursive=True)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ # Limit recursive by maxdepth
+ fs.cp(s, t, recursive=True, maxdepth=1)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ def test_copy_glob_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ fs_target,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1g
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ dummy = fs_join(target, "dummy")
+ fs.touch(dummy)
+ assert fs.isdir(target)
+
+ for target_slash in [False, True]:
+ t = target + "/" if target_slash else target
+
+ # Without recursive
+ fs.cp(fs_join(source, "subdir", "*"), t)
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert not fs.isdir(fs_join(target, "nesteddir"))
+ assert not fs.exists(fs_join(target, "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # With recursive
+ for glob, recursive in zip(["*", "**"], [True, False]):
+ fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive)
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert fs.isdir(fs_join(target, "nesteddir"))
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ fs_join(target, "nesteddir"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # Limit recursive by maxdepth
+ fs.cp(
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
+ )
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert not fs.exists(fs_join(target, "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ def test_copy_glob_to_new_directory(
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
+ ):
+ # Copy scenario 1h
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ for target_slash in [False, True]:
+ t = fs_join(target, "newdir")
+ if target_slash:
+ t += "/"
+
+ # Without recursive
+ fs.cp(fs_join(source, "subdir", "*"), t)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ # With recursive
+ for glob, recursive in zip(["*", "**"], [True, False]):
+ fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ # Limit recursive by maxdepth
+ fs.cp(
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
+ )
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ @pytest.mark.parametrize(
+ GLOB_EDGE_CASES_TESTS["argnames"],
+ GLOB_EDGE_CASES_TESTS["argvalues"],
+ )
+ def test_copy_glob_edge_cases(
+ self,
+ path,
+ recursive,
+ maxdepth,
+ expected,
+ fs,
+ fs_join,
+ fs_glob_edge_cases_files,
+ fs_target,
+ fs_sanitize_path,
+ ):
+ # Copy scenario 1g
+ source = fs_glob_edge_cases_files
+
+ target = fs_target
+
+ for new_dir, target_slash in product([True, False], [True, False]):
+ fs.mkdir(target)
+
+ t = fs_join(target, "newdir") if new_dir else target
+ t = t + "/" if target_slash else t
+
+ fs.copy(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
+
+ output = fs.find(target)
+ if new_dir:
+ prefixed_expected = [
+ fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected
+ ]
+ else:
+ prefixed_expected = [
+ fs_sanitize_path(fs_join(target, p)) for p in expected
+ ]
+ assert sorted(output) == sorted(prefixed_expected)
+
+ try:
+ fs.rm(target, recursive=True)
+ except FileNotFoundError:
+ pass
+
+ def test_copy_list_of_files_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ fs_target,
+ supports_empty_directories,
+ ):
+ # Copy scenario 2a
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ dummy = fs_join(target, "dummy")
+ fs.touch(dummy)
+ assert fs.isdir(target)
+
+ source_files = [
+ fs_join(source, "file1"),
+ fs_join(source, "file2"),
+ fs_join(source, "subdir", "subfile1"),
+ ]
+
+ for target_slash in [False, True]:
+ t = target + "/" if target_slash else target
+
+ fs.cp(source_files, t)
+ assert fs.isfile(fs_join(target, "file1"))
+ assert fs.isfile(fs_join(target, "file2"))
+ assert fs.isfile(fs_join(target, "subfile1"))
+
+ fs.rm(
+ [
+ fs_join(target, "file1"),
+ fs_join(target, "file2"),
+ fs_join(target, "subfile1"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ def test_copy_list_of_files_to_new_directory(
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
+ ):
+ # Copy scenario 2b
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ source_files = [
+ fs_join(source, "file1"),
+ fs_join(source, "file2"),
+ fs_join(source, "subdir", "subfile1"),
+ ]
+
+ fs.cp(source_files, fs_join(target, "newdir") + "/") # Note trailing slash
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "file1"))
+ assert fs.isfile(fs_join(target, "newdir", "file2"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+
+ def test_copy_two_files_new_directory(
+ self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
+ ):
+ # This is a duplicate of test_copy_list_of_files_to_new_directory and
+ # can eventually be removed.
+ source = fs_bulk_operations_scenario_0
+
+ target = fs_target
+ assert not fs.exists(target)
+ fs.cp([fs_join(source, "file1"), fs_join(source, "file2")], target)
+
+ assert fs.isdir(target)
+ assert fs.isfile(fs_join(target, "file1"))
+ assert fs.isfile(fs_join(target, "file2"))
+
+ def test_copy_directory_without_files_with_same_name_prefix(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ fs_dir_and_file_with_same_name_prefix,
+ supports_empty_directories,
+ ):
+ # Create the test dirs
+ source = fs_dir_and_file_with_same_name_prefix
+ target = fs_target
+
+ # Test without glob
+ fs.cp(fs_join(source, "subdir"), target, recursive=True)
+
+ assert fs.isfile(fs_join(target, "subfile.txt"))
+ assert not fs.isfile(fs_join(target, "subdir.txt"))
+
+ fs.rm([fs_join(target, "subfile.txt")])
+ if supports_empty_directories:
+ assert fs.ls(target) == []
+ else:
+ assert not fs.exists(target)
+
+ # Test with glob
+ fs.cp(fs_join(source, "subdir*"), target, recursive=True)
+
+ assert fs.isdir(fs_join(target, "subdir"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile.txt"))
+ assert fs.isfile(fs_join(target, "subdir.txt"))
+
+ def test_copy_with_source_and_destination_as_list(
+ self, fs, fs_target, fs_join, fs_10_files_with_hashed_names
+ ):
+ # Create the test dir
+ source = fs_10_files_with_hashed_names
+ target = fs_target
+
+ # Create list of files for source and destination
+ source_files = []
+ destination_files = []
+ for i in range(10):
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
+ source_files.append(fs_join(source, f"{hashed_i}.txt"))
+ destination_files.append(fs_join(target, f"{hashed_i}.txt"))
+
+ # Copy and assert order was kept
+ fs.copy(path1=source_files, path2=destination_files)
+
+ for i in range(10):
+ file_content = fs.cat(destination_files[i]).decode("utf-8")
+ assert file_content == str(i)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/get.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/get.py
new file mode 100644
index 0000000000000000000000000000000000000000..851ab81ee581e74cac41c64c83ef0af75826d6b0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/get.py
@@ -0,0 +1,587 @@
+from hashlib import md5
+from itertools import product
+
+import pytest
+
+from fsspec.implementations.local import make_path_posix
+from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS
+
+
+class AbstractGetTests:
+ def test_get_file_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1a
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+ assert local_fs.isdir(target)
+
+ target_file2 = local_join(target, "file2")
+ target_subfile1 = local_join(target, "subfile1")
+
+ # Copy from source directory
+ fs.get(fs_join(source, "file2"), target)
+ assert local_fs.isfile(target_file2)
+
+ # Copy from sub directory
+ fs.get(fs_join(source, "subdir", "subfile1"), target)
+ assert local_fs.isfile(target_subfile1)
+
+ # Remove copied files
+ local_fs.rm([target_file2, target_subfile1])
+ assert not local_fs.exists(target_file2)
+ assert not local_fs.exists(target_subfile1)
+
+ # Repeat with trailing slash on target
+ fs.get(fs_join(source, "file2"), target + "/")
+ assert local_fs.isdir(target)
+ assert local_fs.isfile(target_file2)
+
+ fs.get(fs_join(source, "subdir", "subfile1"), target + "/")
+ assert local_fs.isfile(target_subfile1)
+
+ def test_get_file_to_new_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1b
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ fs.get(
+ fs_join(source, "subdir", "subfile1"), local_join(target, "newdir/")
+ ) # Note trailing slash
+
+ assert local_fs.isdir(target)
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
+
+ def test_get_file_to_file_in_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1c
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ fs.get(fs_join(source, "subdir", "subfile1"), local_join(target, "newfile"))
+ assert local_fs.isfile(local_join(target, "newfile"))
+
+ def test_get_file_to_file_in_new_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1d
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ fs.get(
+ fs_join(source, "subdir", "subfile1"),
+ local_join(target, "newdir", "newfile"),
+ )
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "newfile"))
+
+ def test_get_directory_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1e
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+ assert local_fs.isdir(target)
+
+ for source_slash, target_slash in zip([False, True], [False, True]):
+ s = fs_join(source, "subdir")
+ if source_slash:
+ s += "/"
+ t = target + "/" if target_slash else target
+
+ # Without recursive does nothing
+ fs.get(s, t)
+ assert local_fs.ls(target) == []
+
+ # With recursive
+ fs.get(s, t, recursive=True)
+ if source_slash:
+ assert local_fs.isfile(local_join(target, "subfile1"))
+ assert local_fs.isfile(local_join(target, "subfile2"))
+ assert local_fs.isdir(local_join(target, "nesteddir"))
+ assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile"))
+ assert not local_fs.exists(local_join(target, "subdir"))
+
+ local_fs.rm(
+ [
+ local_join(target, "subfile1"),
+ local_join(target, "subfile2"),
+ local_join(target, "nesteddir"),
+ ],
+ recursive=True,
+ )
+ else:
+ assert local_fs.isdir(local_join(target, "subdir"))
+ assert local_fs.isfile(local_join(target, "subdir", "subfile1"))
+ assert local_fs.isfile(local_join(target, "subdir", "subfile2"))
+ assert local_fs.isdir(local_join(target, "subdir", "nesteddir"))
+ assert local_fs.isfile(
+ local_join(target, "subdir", "nesteddir", "nestedfile")
+ )
+
+ local_fs.rm(local_join(target, "subdir"), recursive=True)
+ assert local_fs.ls(target) == []
+
+ # Limit recursive by maxdepth
+ fs.get(s, t, recursive=True, maxdepth=1)
+ if source_slash:
+ assert local_fs.isfile(local_join(target, "subfile1"))
+ assert local_fs.isfile(local_join(target, "subfile2"))
+ assert not local_fs.exists(local_join(target, "nesteddir"))
+ assert not local_fs.exists(local_join(target, "subdir"))
+
+ local_fs.rm(
+ [
+ local_join(target, "subfile1"),
+ local_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ else:
+ assert local_fs.isdir(local_join(target, "subdir"))
+ assert local_fs.isfile(local_join(target, "subdir", "subfile1"))
+ assert local_fs.isfile(local_join(target, "subdir", "subfile2"))
+ assert not local_fs.exists(local_join(target, "subdir", "nesteddir"))
+
+ local_fs.rm(local_join(target, "subdir"), recursive=True)
+ assert local_fs.ls(target) == []
+
+ def test_get_directory_to_new_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1f
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ for source_slash, target_slash in zip([False, True], [False, True]):
+ s = fs_join(source, "subdir")
+ if source_slash:
+ s += "/"
+ t = local_join(target, "newdir")
+ if target_slash:
+ t += "/"
+
+ # Without recursive does nothing
+ fs.get(s, t)
+ assert local_fs.ls(target) == []
+
+ # With recursive
+ fs.get(s, t, recursive=True)
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
+ assert local_fs.isdir(local_join(target, "newdir", "nesteddir"))
+ assert local_fs.isfile(
+ local_join(target, "newdir", "nesteddir", "nestedfile")
+ )
+ assert not local_fs.exists(local_join(target, "subdir"))
+
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
+ assert local_fs.ls(target) == []
+
+ # Limit recursive by maxdepth
+ fs.get(s, t, recursive=True, maxdepth=1)
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
+ assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
+ assert not local_fs.exists(local_join(target, "subdir"))
+
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
+ assert not local_fs.exists(local_join(target, "newdir"))
+
+ def test_get_glob_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1g
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ for target_slash in [False, True]:
+ t = target + "/" if target_slash else target
+
+ # Without recursive
+ fs.get(fs_join(source, "subdir", "*"), t)
+ assert local_fs.isfile(local_join(target, "subfile1"))
+ assert local_fs.isfile(local_join(target, "subfile2"))
+ assert not local_fs.isdir(local_join(target, "nesteddir"))
+ assert not local_fs.exists(local_join(target, "nesteddir", "nestedfile"))
+ assert not local_fs.exists(local_join(target, "subdir"))
+
+ local_fs.rm(
+ [
+ local_join(target, "subfile1"),
+ local_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ assert local_fs.ls(target) == []
+
+ # With recursive
+ for glob, recursive in zip(["*", "**"], [True, False]):
+ fs.get(fs_join(source, "subdir", glob), t, recursive=recursive)
+ assert local_fs.isfile(local_join(target, "subfile1"))
+ assert local_fs.isfile(local_join(target, "subfile2"))
+ assert local_fs.isdir(local_join(target, "nesteddir"))
+ assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile"))
+ assert not local_fs.exists(local_join(target, "subdir"))
+
+ local_fs.rm(
+ [
+ local_join(target, "subfile1"),
+ local_join(target, "subfile2"),
+ local_join(target, "nesteddir"),
+ ],
+ recursive=True,
+ )
+ assert local_fs.ls(target) == []
+
+ # Limit recursive by maxdepth
+ fs.get(
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
+ )
+ assert local_fs.isfile(local_join(target, "subfile1"))
+ assert local_fs.isfile(local_join(target, "subfile2"))
+ assert not local_fs.exists(local_join(target, "nesteddir"))
+ assert not local_fs.exists(local_join(target, "subdir"))
+
+ local_fs.rm(
+ [
+ local_join(target, "subfile1"),
+ local_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ assert local_fs.ls(target) == []
+
+ def test_get_glob_to_new_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1h
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ for target_slash in [False, True]:
+ t = fs_join(target, "newdir")
+ if target_slash:
+ t += "/"
+
+ # Without recursive
+ fs.get(fs_join(source, "subdir", "*"), t)
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
+ assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
+ assert not local_fs.exists(
+ local_join(target, "newdir", "nesteddir", "nestedfile")
+ )
+ assert not local_fs.exists(local_join(target, "subdir"))
+ assert not local_fs.exists(local_join(target, "newdir", "subdir"))
+
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
+ assert local_fs.ls(target) == []
+
+ # With recursive
+ for glob, recursive in zip(["*", "**"], [True, False]):
+ fs.get(fs_join(source, "subdir", glob), t, recursive=recursive)
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
+ assert local_fs.isdir(local_join(target, "newdir", "nesteddir"))
+ assert local_fs.isfile(
+ local_join(target, "newdir", "nesteddir", "nestedfile")
+ )
+ assert not local_fs.exists(local_join(target, "subdir"))
+ assert not local_fs.exists(local_join(target, "newdir", "subdir"))
+
+ local_fs.rm(local_join(target, "newdir"), recursive=True)
+ assert not local_fs.exists(local_join(target, "newdir"))
+
+ # Limit recursive by maxdepth
+ fs.get(
+ fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
+ )
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
+ assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
+ assert not local_fs.exists(local_join(target, "subdir"))
+ assert not local_fs.exists(local_join(target, "newdir", "subdir"))
+
+ local_fs.rm(local_fs.ls(target, detail=False), recursive=True)
+ assert not local_fs.exists(local_join(target, "newdir"))
+
+ @pytest.mark.parametrize(
+ GLOB_EDGE_CASES_TESTS["argnames"],
+ GLOB_EDGE_CASES_TESTS["argvalues"],
+ )
+ def test_get_glob_edge_cases(
+ self,
+ path,
+ recursive,
+ maxdepth,
+ expected,
+ fs,
+ fs_join,
+ fs_glob_edge_cases_files,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 1g
+ source = fs_glob_edge_cases_files
+
+ target = local_target
+
+ for new_dir, target_slash in product([True, False], [True, False]):
+ local_fs.mkdir(target)
+
+ t = local_join(target, "newdir") if new_dir else target
+ t = t + "/" if target_slash else t
+
+ fs.get(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
+
+ output = local_fs.find(target)
+ if new_dir:
+ prefixed_expected = [
+ make_path_posix(local_join(target, "newdir", p)) for p in expected
+ ]
+ else:
+ prefixed_expected = [
+ make_path_posix(local_join(target, p)) for p in expected
+ ]
+ assert sorted(output) == sorted(prefixed_expected)
+
+ try:
+ local_fs.rm(target, recursive=True)
+ except FileNotFoundError:
+ pass
+
+ def test_get_list_of_files_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 2a
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ source_files = [
+ fs_join(source, "file1"),
+ fs_join(source, "file2"),
+ fs_join(source, "subdir", "subfile1"),
+ ]
+
+ for target_slash in [False, True]:
+ t = target + "/" if target_slash else target
+
+ fs.get(source_files, t)
+ assert local_fs.isfile(local_join(target, "file1"))
+ assert local_fs.isfile(local_join(target, "file2"))
+ assert local_fs.isfile(local_join(target, "subfile1"))
+
+ local_fs.rm(
+ [
+ local_join(target, "file1"),
+ local_join(target, "file2"),
+ local_join(target, "subfile1"),
+ ],
+ recursive=True,
+ )
+ assert local_fs.ls(target) == []
+
+ def test_get_list_of_files_to_new_directory(
+ self,
+ fs,
+ fs_join,
+ fs_bulk_operations_scenario_0,
+ local_fs,
+ local_join,
+ local_target,
+ ):
+ # Copy scenario 2b
+ source = fs_bulk_operations_scenario_0
+
+ target = local_target
+ local_fs.mkdir(target)
+
+ source_files = [
+ fs_join(source, "file1"),
+ fs_join(source, "file2"),
+ fs_join(source, "subdir", "subfile1"),
+ ]
+
+ fs.get(source_files, local_join(target, "newdir") + "/") # Note trailing slash
+ assert local_fs.isdir(local_join(target, "newdir"))
+ assert local_fs.isfile(local_join(target, "newdir", "file1"))
+ assert local_fs.isfile(local_join(target, "newdir", "file2"))
+ assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
+
+ def test_get_directory_recursive(
+ self, fs, fs_join, fs_path, local_fs, local_join, local_target
+ ):
+ # https://github.com/fsspec/filesystem_spec/issues/1062
+ # Recursive cp/get/put of source directory into non-existent target directory.
+ src = fs_join(fs_path, "src")
+ src_file = fs_join(src, "file")
+ fs.mkdir(src)
+ fs.touch(src_file)
+
+ target = local_target
+
+ # get without slash
+ assert not local_fs.exists(target)
+ for loop in range(2):
+ fs.get(src, target, recursive=True)
+ assert local_fs.isdir(target)
+
+ if loop == 0:
+ assert local_fs.isfile(local_join(target, "file"))
+ assert not local_fs.exists(local_join(target, "src"))
+ else:
+ assert local_fs.isfile(local_join(target, "file"))
+ assert local_fs.isdir(local_join(target, "src"))
+ assert local_fs.isfile(local_join(target, "src", "file"))
+
+ local_fs.rm(target, recursive=True)
+
+ # get with slash
+ assert not local_fs.exists(target)
+ for loop in range(2):
+ fs.get(src + "/", target, recursive=True)
+ assert local_fs.isdir(target)
+ assert local_fs.isfile(local_join(target, "file"))
+ assert not local_fs.exists(local_join(target, "src"))
+
+ def test_get_directory_without_files_with_same_name_prefix(
+ self,
+ fs,
+ fs_join,
+ local_fs,
+ local_join,
+ local_target,
+ fs_dir_and_file_with_same_name_prefix,
+ ):
+ # Create the test dirs
+ source = fs_dir_and_file_with_same_name_prefix
+ target = local_target
+
+ # Test without glob
+ fs.get(fs_join(source, "subdir"), target, recursive=True)
+
+ assert local_fs.isfile(local_join(target, "subfile.txt"))
+ assert not local_fs.isfile(local_join(target, "subdir.txt"))
+
+ local_fs.rm([local_join(target, "subfile.txt")])
+ assert local_fs.ls(target) == []
+
+ # Test with glob
+ fs.get(fs_join(source, "subdir*"), target, recursive=True)
+
+ assert local_fs.isdir(local_join(target, "subdir"))
+ assert local_fs.isfile(local_join(target, "subdir", "subfile.txt"))
+ assert local_fs.isfile(local_join(target, "subdir.txt"))
+
+ def test_get_with_source_and_destination_as_list(
+ self,
+ fs,
+ fs_join,
+ local_fs,
+ local_join,
+ local_target,
+ fs_10_files_with_hashed_names,
+ ):
+ # Create the test dir
+ source = fs_10_files_with_hashed_names
+ target = local_target
+
+ # Create list of files for source and destination
+ source_files = []
+ destination_files = []
+ for i in range(10):
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
+ source_files.append(fs_join(source, f"{hashed_i}.txt"))
+ destination_files.append(
+ make_path_posix(local_join(target, f"{hashed_i}.txt"))
+ )
+
+ # Copy and assert order was kept
+ fs.get(rpath=source_files, lpath=destination_files)
+
+ for i in range(10):
+ file_content = local_fs.cat(destination_files[i]).decode("utf-8")
+ assert file_content == str(i)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py
new file mode 100644
index 0000000000000000000000000000000000000000..39f6caa3de815e024fa84de2acecc986c823ed29
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py
@@ -0,0 +1,57 @@
+import os
+
+import pytest
+
+import fsspec
+
+
+def test_move_raises_error_with_tmpdir(tmpdir):
+ # Create a file in the temporary directory
+ source = tmpdir.join("source_file.txt")
+ source.write("content")
+
+ # Define a destination that simulates a protected or invalid path
+ destination = tmpdir.join("non_existent_directory/destination_file.txt")
+
+ # Instantiate the filesystem (assuming the local file system interface)
+ fs = fsspec.filesystem("file")
+
+ # Use the actual file paths as string
+ with pytest.raises(FileNotFoundError):
+ fs.mv(str(source), str(destination))
+
+
+@pytest.mark.parametrize("recursive", (True, False))
+def test_move_raises_error_with_tmpdir_permission(recursive, tmpdir):
+ # Create a file in the temporary directory
+ source = tmpdir.join("source_file.txt")
+ source.write("content")
+
+ # Create a protected directory (non-writable)
+ protected_dir = tmpdir.mkdir("protected_directory")
+ protected_path = str(protected_dir)
+
+ # Set the directory to read-only
+ if os.name == "nt":
+ os.system(f'icacls "{protected_path}" /deny Everyone:(W)')
+ else:
+ os.chmod(protected_path, 0o555) # Sets the directory to read-only
+
+ # Define a destination inside the protected directory
+ destination = protected_dir.join("destination_file.txt")
+
+ # Instantiate the filesystem (assuming the local file system interface)
+ fs = fsspec.filesystem("file")
+
+ # Try to move the file to the read-only directory, expecting a permission error
+ with pytest.raises(PermissionError):
+ fs.mv(str(source), str(destination), recursive=recursive)
+
+ # Assert the file was not created in the destination
+ assert not os.path.exists(destination)
+
+ # Cleanup: Restore permissions so the directory can be cleaned up
+ if os.name == "nt":
+ os.system(f'icacls "{protected_path}" /remove:d Everyone')
+ else:
+ os.chmod(protected_path, 0o755) # Restore write permission for cleanup
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/open.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/open.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb75ea852276fb8d834345883813b8e27a0ae24c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/open.py
@@ -0,0 +1,11 @@
+import pytest
+
+
+class AbstractOpenTests:
+ def test_open_exclusive(self, fs, fs_target):
+ with fs.open(fs_target, "wb") as f:
+ f.write(b"data")
+ with fs.open(fs_target, "rb") as f:
+ assert f.read() == b"data"
+ with pytest.raises(FileExistsError):
+ fs.open(fs_target, "xb")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ecca96e9d23ff268a253c48269d5cca451ea270
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py
@@ -0,0 +1,11 @@
+import pytest
+
+
+class AbstractPipeTests:
+ def test_pipe_exclusive(self, fs, fs_target):
+ fs.pipe_file(fs_target, b"data")
+ assert fs.cat_file(fs_target) == b"data"
+ with pytest.raises(FileExistsError):
+ fs.pipe_file(fs_target, b"data", mode="create")
+ fs.pipe_file(fs_target, b"new data", mode="overwrite")
+ assert fs.cat_file(fs_target) == b"new data"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/put.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/put.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fc349977f0384d9fc86126498be5c6ad99a21d3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/fsspec/tests/abstract/put.py
@@ -0,0 +1,591 @@
+from hashlib import md5
+from itertools import product
+
+import pytest
+
+from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS
+
+
+class AbstractPutTests:
+ def test_put_file_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ local_join,
+ local_bulk_operations_scenario_0,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1a
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ fs.touch(fs_join(target, "dummy"))
+ assert fs.isdir(target)
+
+ target_file2 = fs_join(target, "file2")
+ target_subfile1 = fs_join(target, "subfile1")
+
+ # Copy from source directory
+ fs.put(local_join(source, "file2"), target)
+ assert fs.isfile(target_file2)
+
+ # Copy from sub directory
+ fs.put(local_join(source, "subdir", "subfile1"), target)
+ assert fs.isfile(target_subfile1)
+
+ # Remove copied files
+ fs.rm([target_file2, target_subfile1])
+ assert not fs.exists(target_file2)
+ assert not fs.exists(target_subfile1)
+
+ # Repeat with trailing slash on target
+ fs.put(local_join(source, "file2"), target + "/")
+ assert fs.isdir(target)
+ assert fs.isfile(target_file2)
+
+ fs.put(local_join(source, "subdir", "subfile1"), target + "/")
+ assert fs.isfile(target_subfile1)
+
+ def test_put_file_to_new_directory(
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
+ ):
+ # Copy scenario 1b
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ fs.put(
+ local_join(source, "subdir", "subfile1"), fs_join(target, "newdir/")
+ ) # Note trailing slash
+ assert fs.isdir(target)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+
+ def test_put_file_to_file_in_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ local_join,
+ supports_empty_directories,
+ local_bulk_operations_scenario_0,
+ ):
+ # Copy scenario 1c
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ fs.touch(fs_join(target, "dummy"))
+ assert fs.isdir(target)
+
+ fs.put(local_join(source, "subdir", "subfile1"), fs_join(target, "newfile"))
+ assert fs.isfile(fs_join(target, "newfile"))
+
+ def test_put_file_to_file_in_new_directory(
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
+ ):
+ # Copy scenario 1d
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ fs.put(
+ local_join(source, "subdir", "subfile1"),
+ fs_join(target, "newdir", "newfile"),
+ )
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "newfile"))
+
+ def test_put_directory_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ local_bulk_operations_scenario_0,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1e
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ dummy = fs_join(target, "dummy")
+ fs.touch(dummy)
+ assert fs.isdir(target)
+
+ for source_slash, target_slash in zip([False, True], [False, True]):
+ s = fs_join(source, "subdir")
+ if source_slash:
+ s += "/"
+ t = target + "/" if target_slash else target
+
+ # Without recursive does nothing
+ fs.put(s, t)
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # With recursive
+ fs.put(s, t, recursive=True)
+ if source_slash:
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert fs.isdir(fs_join(target, "nesteddir"))
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ fs_join(target, "nesteddir"),
+ ],
+ recursive=True,
+ )
+ else:
+ assert fs.isdir(fs_join(target, "subdir"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
+ assert fs.isdir(fs_join(target, "subdir", "nesteddir"))
+ assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile"))
+
+ fs.rm(fs_join(target, "subdir"), recursive=True)
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # Limit recursive by maxdepth
+ fs.put(s, t, recursive=True, maxdepth=1)
+ if source_slash:
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert not fs.exists(fs_join(target, "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ else:
+ assert fs.isdir(fs_join(target, "subdir"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "subdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "subdir", "nesteddir"))
+
+ fs.rm(fs_join(target, "subdir"), recursive=True)
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ def test_put_directory_to_new_directory(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ local_bulk_operations_scenario_0,
+ supports_empty_directories,
+ ):
+ # Copy scenario 1f
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ for source_slash, target_slash in zip([False, True], [False, True]):
+ s = fs_join(source, "subdir")
+ if source_slash:
+ s += "/"
+ t = fs_join(target, "newdir")
+ if target_slash:
+ t += "/"
+
+ # Without recursive does nothing
+ fs.put(s, t)
+ if supports_empty_directories:
+ assert fs.ls(target) == []
+ else:
+ with pytest.raises(FileNotFoundError):
+ fs.ls(target)
+
+ # With recursive
+ fs.put(s, t, recursive=True)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ # Limit recursive by maxdepth
+ fs.put(s, t, recursive=True, maxdepth=1)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ def test_put_glob_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ local_join,
+ supports_empty_directories,
+ local_bulk_operations_scenario_0,
+ ):
+ # Copy scenario 1g
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ dummy = fs_join(target, "dummy")
+ fs.touch(dummy)
+ assert fs.isdir(target)
+
+ for target_slash in [False, True]:
+ t = target + "/" if target_slash else target
+
+ # Without recursive
+ fs.put(local_join(source, "subdir", "*"), t)
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert not fs.isdir(fs_join(target, "nesteddir"))
+ assert not fs.exists(fs_join(target, "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # With recursive
+ for glob, recursive in zip(["*", "**"], [True, False]):
+ fs.put(local_join(source, "subdir", glob), t, recursive=recursive)
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert fs.isdir(fs_join(target, "nesteddir"))
+ assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ fs_join(target, "nesteddir"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ # Limit recursive by maxdepth
+ fs.put(
+ local_join(source, "subdir", glob),
+ t,
+ recursive=recursive,
+ maxdepth=1,
+ )
+ assert fs.isfile(fs_join(target, "subfile1"))
+ assert fs.isfile(fs_join(target, "subfile2"))
+ assert not fs.exists(fs_join(target, "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+
+ fs.rm(
+ [
+ fs_join(target, "subfile1"),
+ fs_join(target, "subfile2"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ def test_put_glob_to_new_directory(
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
+ ):
+ # Copy scenario 1h
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ for target_slash in [False, True]:
+ t = fs_join(target, "newdir")
+ if target_slash:
+ t += "/"
+
+ # Without recursive
+ fs.put(local_join(source, "subdir", "*"), t)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ # With recursive
+ for glob, recursive in zip(["*", "**"], [True, False]):
+ fs.put(local_join(source, "subdir", glob), t, recursive=recursive)
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
+ assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
+ assert not fs.exists(fs_join(target, "subdir"))
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ # Limit recursive by maxdepth
+ fs.put(
+ local_join(source, "subdir", glob),
+ t,
+ recursive=recursive,
+ maxdepth=1,
+ )
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile2"))
+ assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
+ assert not fs.exists(fs_join(target, "subdir"))
+ assert not fs.exists(fs_join(target, "newdir", "subdir"))
+
+ fs.rm(fs_join(target, "newdir"), recursive=True)
+ assert not fs.exists(fs_join(target, "newdir"))
+
+ @pytest.mark.parametrize(
+ GLOB_EDGE_CASES_TESTS["argnames"],
+ GLOB_EDGE_CASES_TESTS["argvalues"],
+ )
+ def test_put_glob_edge_cases(
+ self,
+ path,
+ recursive,
+ maxdepth,
+ expected,
+ fs,
+ fs_join,
+ fs_target,
+ local_glob_edge_cases_files,
+ local_join,
+ fs_sanitize_path,
+ ):
+ # Copy scenario 1g
+ source = local_glob_edge_cases_files
+
+ target = fs_target
+
+ for new_dir, target_slash in product([True, False], [True, False]):
+ fs.mkdir(target)
+
+ t = fs_join(target, "newdir") if new_dir else target
+ t = t + "/" if target_slash else t
+
+ fs.put(local_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
+
+ output = fs.find(target)
+ if new_dir:
+ prefixed_expected = [
+ fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected
+ ]
+ else:
+ prefixed_expected = [
+ fs_sanitize_path(fs_join(target, p)) for p in expected
+ ]
+ assert sorted(output) == sorted(prefixed_expected)
+
+ try:
+ fs.rm(target, recursive=True)
+ except FileNotFoundError:
+ pass
+
+ def test_put_list_of_files_to_existing_directory(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ local_join,
+ local_bulk_operations_scenario_0,
+ supports_empty_directories,
+ ):
+ # Copy scenario 2a
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+ if not supports_empty_directories:
+ # Force target directory to exist by adding a dummy file
+ dummy = fs_join(target, "dummy")
+ fs.touch(dummy)
+ assert fs.isdir(target)
+
+ source_files = [
+ local_join(source, "file1"),
+ local_join(source, "file2"),
+ local_join(source, "subdir", "subfile1"),
+ ]
+
+ for target_slash in [False, True]:
+ t = target + "/" if target_slash else target
+
+ fs.put(source_files, t)
+ assert fs.isfile(fs_join(target, "file1"))
+ assert fs.isfile(fs_join(target, "file2"))
+ assert fs.isfile(fs_join(target, "subfile1"))
+
+ fs.rm(
+ [
+ fs_join(target, "file1"),
+ fs_join(target, "file2"),
+ fs_join(target, "subfile1"),
+ ],
+ recursive=True,
+ )
+ assert fs.ls(target, detail=False) == (
+ [] if supports_empty_directories else [dummy]
+ )
+
+ def test_put_list_of_files_to_new_directory(
+ self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0
+ ):
+ # Copy scenario 2b
+ source = local_bulk_operations_scenario_0
+
+ target = fs_target
+ fs.mkdir(target)
+
+ source_files = [
+ local_join(source, "file1"),
+ local_join(source, "file2"),
+ local_join(source, "subdir", "subfile1"),
+ ]
+
+ fs.put(source_files, fs_join(target, "newdir") + "/") # Note trailing slash
+ assert fs.isdir(fs_join(target, "newdir"))
+ assert fs.isfile(fs_join(target, "newdir", "file1"))
+ assert fs.isfile(fs_join(target, "newdir", "file2"))
+ assert fs.isfile(fs_join(target, "newdir", "subfile1"))
+
+ def test_put_directory_recursive(
+ self, fs, fs_join, fs_target, local_fs, local_join, local_path
+ ):
+ # https://github.com/fsspec/filesystem_spec/issues/1062
+ # Recursive cp/get/put of source directory into non-existent target directory.
+ src = local_join(local_path, "src")
+ src_file = local_join(src, "file")
+ local_fs.mkdir(src)
+ local_fs.touch(src_file)
+
+ target = fs_target
+
+ # put without slash
+ assert not fs.exists(target)
+ for loop in range(2):
+ fs.put(src, target, recursive=True)
+ assert fs.isdir(target)
+
+ if loop == 0:
+ assert fs.isfile(fs_join(target, "file"))
+ assert not fs.exists(fs_join(target, "src"))
+ else:
+ assert fs.isfile(fs_join(target, "file"))
+ assert fs.isdir(fs_join(target, "src"))
+ assert fs.isfile(fs_join(target, "src", "file"))
+
+ fs.rm(target, recursive=True)
+
+ # put with slash
+ assert not fs.exists(target)
+ for loop in range(2):
+ fs.put(src + "/", target, recursive=True)
+ assert fs.isdir(target)
+ assert fs.isfile(fs_join(target, "file"))
+ assert not fs.exists(fs_join(target, "src"))
+
+ def test_put_directory_without_files_with_same_name_prefix(
+ self,
+ fs,
+ fs_join,
+ fs_target,
+ local_join,
+ local_dir_and_file_with_same_name_prefix,
+ supports_empty_directories,
+ ):
+ # Create the test dirs
+ source = local_dir_and_file_with_same_name_prefix
+ target = fs_target
+
+ # Test without glob
+ fs.put(local_join(source, "subdir"), fs_target, recursive=True)
+
+ assert fs.isfile(fs_join(fs_target, "subfile.txt"))
+ assert not fs.isfile(fs_join(fs_target, "subdir.txt"))
+
+ fs.rm([fs_join(target, "subfile.txt")])
+ if supports_empty_directories:
+ assert fs.ls(target) == []
+ else:
+ assert not fs.exists(target)
+
+ # Test with glob
+ fs.put(local_join(source, "subdir*"), fs_target, recursive=True)
+
+ assert fs.isdir(fs_join(fs_target, "subdir"))
+ assert fs.isfile(fs_join(fs_target, "subdir", "subfile.txt"))
+ assert fs.isfile(fs_join(fs_target, "subdir.txt"))
+
+ def test_copy_with_source_and_destination_as_list(
+ self, fs, fs_target, fs_join, local_join, local_10_files_with_hashed_names
+ ):
+ # Create the test dir
+ source = local_10_files_with_hashed_names
+ target = fs_target
+
+ # Create list of files for source and destination
+ source_files = []
+ destination_files = []
+ for i in range(10):
+ hashed_i = md5(str(i).encode("utf-8")).hexdigest()
+ source_files.append(local_join(source, f"{hashed_i}.txt"))
+ destination_files.append(fs_join(target, f"{hashed_i}.txt"))
+
+ # Copy and assert order was kept
+ fs.put(lpath=source_files, rpath=destination_files)
+
+ for i in range(10):
+ file_content = fs.cat(destination_files[i]).decode("utf-8")
+ assert file_content == str(i)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48036769da3e81a122f81e28ba6bc31ca089497b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_python_package_support.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_python_package_support.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f09d97614933157a115275f6e81e56c7ece9fe63
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_python_package_support.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_python_version_support.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_python_version_support.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca423a37456817d548fe7e7804ae6683d7a15ed0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_python_version_support.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_rest_streaming_base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_rest_streaming_base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b80548ef08cdef0f9886a7c855a976cd99ab8a93
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/_rest_streaming_base.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5255f1c2d9a4319ac34d02534d6227a9e5e87bd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a4944c0d643e3ad21ddae2ee0e45a49803460d0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi_base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi_base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2dd90ede0b3f31478556a6226260cdb01f115303
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/bidi_base.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_info.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_info.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba1096649d412d218e0512d2da92e839e9cb5417
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_info.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_logging.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_logging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d7012dd548beaf9a508428c712357c3cbc74cf4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_logging.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_options.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_options.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5b12542bc02f912bf18df1635f85f3295044527
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/client_options.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/datetime_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/datetime_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb8fbf28b99314d6399d032614ab52f7d72da992
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/datetime_helpers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e99ef2f0b9da740ad7ea0f7915c6ba79539af032
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/exceptions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/extended_operation.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/extended_operation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60e768d48446f9898c37bf7a246e2fa854013287
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/extended_operation.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/general_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/general_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bad24752d7f6565e5fde61116e0f55ed068a35e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/general_helpers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/grpc_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/grpc_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6b1814a9efe33e68a3729e05b975999792af3dc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/grpc_helpers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/grpc_helpers_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/grpc_helpers_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d54e4ac25c1d8e15e5821e1564070550ea18984
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/grpc_helpers_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/iam.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/iam.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89e8efa8920303092beb508838e83b20d6ebdf08
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/iam.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/operation.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/operation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8760b327c760e144a49c541b3896125c34e1799b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/operation.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/operation_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/operation_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef173082e365879568bd6e0c3415d0d7812b7db6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/operation_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/page_iterator.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/page_iterator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17912cee3da6567686586997a250b2fa0cc0cfa1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/page_iterator.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/page_iterator_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/page_iterator_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47bc79b9353b0360ae6ad9ff31bebea5a87496c4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/page_iterator_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/path_template.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/path_template.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f988c32e0c39ade214a571e3933ec657b17f66c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/path_template.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/protobuf_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/protobuf_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0a4f4e9488d2f071c90b7a745fe4bb55652f6d5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/protobuf_helpers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e7386f801a98f666fb3aa1df363a29c3931a04d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_helpers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_streaming.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_streaming.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bffa5e8a5daae04046b656ce8f422e35460feca
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_streaming.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_streaming_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_streaming_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..503aa755cdd9b8292db84ef52d68d87da7d573c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/rest_streaming_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/retry_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/retry_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19d4a7cfba3bc18441744474b5bc8801e155d77b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/retry_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/timeout.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/timeout.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db14f530455c7cb791905c21f8cfd437a7eecbe3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/timeout.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/universe.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/universe.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1518fdb08432b6d6ec87e730d30114fd4503ad6e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/universe.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63a11b6a68684fd54289acdb5cacd7e261a0b29f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/version.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/version_header.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/version_header.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c00bd0bfe4a8aeb1dff040aa7e9c647cd940e88f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/__pycache__/version_header.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3768b2c53f5336c880fc81275850a57030e10062
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__init__.py
@@ -0,0 +1,19 @@
+# Copyright 2017, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Futures for dealing with asynchronous operations."""
+
+from google.api_core.future.base import Future
+
+__all__ = ["Future"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11f83dc52ff48227c808bd56e1ba2416a0e7bd8c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6859418e6d3d3e69b3feba246ec4d16fe3b46cd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/_helpers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/async_future.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/async_future.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f21e262ce9bb3f59ce1b40c86d6da8314b41b935
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/async_future.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9960ae6fb2c89cb4e20dd322f1a71458f488f474
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/base.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/polling.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/polling.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0c01f20bfdc4ee4c1618b938a966c556f1b883d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/__pycache__/polling.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/_helpers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e88ca9d561d968a2ba66c65bdbe83a4a4a0e374
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/_helpers.py
@@ -0,0 +1,39 @@
+# Copyright 2017, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Private helpers for futures."""
+
+import logging
+import threading
+
+
+_LOGGER = logging.getLogger(__name__)
+
+
+def start_daemon_thread(*args, **kwargs):
+ """Starts a thread and marks it as a daemon thread."""
+ thread = threading.Thread(*args, **kwargs)
+ thread.daemon = True
+ thread.start()
+ return thread
+
+
+def safe_invoke_callback(callback, *args, **kwargs):
+ """Invoke a callback, swallowing and logging any exceptions."""
+ # pylint: disable=bare-except
+ # We intentionally want to swallow all exceptions.
+ try:
+ return callback(*args, **kwargs)
+ except Exception:
+ _LOGGER.exception("Error while executing Future callback.")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/async_future.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/async_future.py
new file mode 100644
index 0000000000000000000000000000000000000000..325ee9cd4facd8f5a3a268857998438cdd57dfb5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/async_future.py
@@ -0,0 +1,162 @@
+# Copyright 2020, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""AsyncIO implementation of the abstract base Future class."""
+
+import asyncio
+
+from google.api_core import exceptions
+from google.api_core import retry
+from google.api_core import retry_async
+from google.api_core.future import base
+
+
+class _OperationNotComplete(Exception):
+ """Private exception used for polling via retry."""
+
+ pass
+
+
+RETRY_PREDICATE = retry.if_exception_type(
+ _OperationNotComplete,
+ exceptions.TooManyRequests,
+ exceptions.InternalServerError,
+ exceptions.BadGateway,
+)
+DEFAULT_RETRY = retry_async.AsyncRetry(predicate=RETRY_PREDICATE)
+
+
+class AsyncFuture(base.Future):
+ """A Future that polls peer service to self-update.
+
+ The :meth:`done` method should be implemented by subclasses. The polling
+ behavior will repeatedly call ``done`` until it returns True.
+
+ .. note::
+
+ Privacy here is intended to prevent the final class from
+ overexposing, not to prevent subclasses from accessing methods.
+
+ Args:
+ retry (google.api_core.retry.Retry): The retry configuration used
+ when polling. This can be used to control how often :meth:`done`
+ is polled. Regardless of the retry's ``deadline``, it will be
+ overridden by the ``timeout`` argument to :meth:`result`.
+ """
+
+ def __init__(self, retry=DEFAULT_RETRY):
+ super().__init__()
+ self._retry = retry
+ self._future = asyncio.get_event_loop().create_future()
+ self._background_task = None
+
+ async def done(self, retry=DEFAULT_RETRY):
+ """Checks to see if the operation is complete.
+
+ Args:
+ retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
+
+ Returns:
+ bool: True if the operation is complete, False otherwise.
+ """
+ # pylint: disable=redundant-returns-doc, missing-raises-doc
+ raise NotImplementedError()
+
+ async def _done_or_raise(self):
+ """Check if the future is done and raise if it's not."""
+ result = await self.done()
+ if not result:
+ raise _OperationNotComplete()
+
+ async def running(self):
+ """True if the operation is currently running."""
+ result = await self.done()
+ return not result
+
+ async def _blocking_poll(self, timeout=None):
+ """Poll and await for the Future to be resolved.
+
+ Args:
+ timeout (int):
+ How long (in seconds) to wait for the operation to complete.
+ If None, wait indefinitely.
+ """
+ if self._future.done():
+ return
+
+ retry_ = self._retry.with_timeout(timeout)
+
+ try:
+ await retry_(self._done_or_raise)()
+ except exceptions.RetryError:
+ raise asyncio.TimeoutError(
+ "Operation did not complete within the designated " "timeout."
+ )
+
+ async def result(self, timeout=None):
+ """Get the result of the operation.
+
+ Args:
+ timeout (int):
+ How long (in seconds) to wait for the operation to complete.
+ If None, wait indefinitely.
+
+ Returns:
+ google.protobuf.Message: The Operation's result.
+
+ Raises:
+ google.api_core.GoogleAPICallError: If the operation errors or if
+ the timeout is reached before the operation completes.
+ """
+ await self._blocking_poll(timeout=timeout)
+ return self._future.result()
+
+ async def exception(self, timeout=None):
+ """Get the exception from the operation.
+
+ Args:
+ timeout (int): How long to wait for the operation to complete.
+ If None, wait indefinitely.
+
+ Returns:
+ Optional[google.api_core.GoogleAPICallError]: The operation's
+ error.
+ """
+ await self._blocking_poll(timeout=timeout)
+ return self._future.exception()
+
+ def add_done_callback(self, fn):
+ """Add a callback to be executed when the operation is complete.
+
+ If the operation is completed, the callback will be scheduled onto the
+ event loop. Otherwise, the callback will be stored and invoked when the
+ future is done.
+
+ Args:
+ fn (Callable[Future]): The callback to execute when the operation
+ is complete.
+ """
+ if self._background_task is None:
+ self._background_task = asyncio.get_event_loop().create_task(
+ self._blocking_poll()
+ )
+ self._future.add_done_callback(fn)
+
+ def set_result(self, result):
+ """Set the Future's result."""
+ self._future.set_result(result)
+
+ def set_exception(self, exception):
+ """Set the Future's exception."""
+ self._future.set_exception(exception)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f300586060deb52f27fadc385e68d65eb4c4e6b5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/base.py
@@ -0,0 +1,64 @@
+# Copyright 2017, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Abstract and helper bases for Future implementations."""
+
+import abc
+
+
+class Future(object, metaclass=abc.ABCMeta):
+ # pylint: disable=missing-docstring
+ # We inherit the interfaces here from concurrent.futures.
+
+ """Future interface.
+
+ This interface is based on :class:`concurrent.futures.Future`.
+ """
+
+ @abc.abstractmethod
+ def cancel(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancelled(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def running(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def done(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def result(self, timeout=None):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def exception(self, timeout=None):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def add_done_callback(self, fn):
+ # pylint: disable=invalid-name
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def set_result(self, result):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def set_exception(self, exception):
+ raise NotImplementedError()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/polling.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/polling.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1e2a1882117eb7882a8d8348ce2eeac6c2f1ba7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/future/polling.py
@@ -0,0 +1,323 @@
+# Copyright 2017, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Abstract and helper bases for Future implementations."""
+
+import abc
+import concurrent.futures
+
+from google.api_core import exceptions
+from google.api_core import retry as retries
+from google.api_core.future import _helpers
+from google.api_core.future import base
+
+
+class _OperationNotComplete(Exception):
+ """Private exception used for polling via retry."""
+
+ pass
+
+
+# DEPRECATED as it conflates RPC retry and polling concepts into one.
+# Use POLLING_PREDICATE instead to configure polling.
+RETRY_PREDICATE = retries.if_exception_type(
+ _OperationNotComplete,
+ exceptions.TooManyRequests,
+ exceptions.InternalServerError,
+ exceptions.BadGateway,
+ exceptions.ServiceUnavailable,
+)
+
+# DEPRECATED: use DEFAULT_POLLING to configure LRO polling logic. Construct
+# Retry object using its default values as a baseline for any custom retry logic
+# (not to be confused with polling logic).
+DEFAULT_RETRY = retries.Retry(predicate=RETRY_PREDICATE)
+
+# POLLING_PREDICATE is supposed to poll only on _OperationNotComplete.
+# Any RPC-specific errors (like ServiceUnavailable) will be handled
+# by retry logic (not to be confused with polling logic) which is triggered for
+# every polling RPC independently of polling logic but within its context.
+POLLING_PREDICATE = retries.if_exception_type(
+ _OperationNotComplete,
+)
+
+# Default polling configuration
+DEFAULT_POLLING = retries.Retry(
+ predicate=POLLING_PREDICATE,
+ initial=1.0, # seconds
+ maximum=20.0, # seconds
+ multiplier=1.5,
+ timeout=900, # seconds
+)
+
+
+class PollingFuture(base.Future):
+ """A Future that needs to poll some service to check its status.
+
+ The :meth:`done` method should be implemented by subclasses. The polling
+ behavior will repeatedly call ``done`` until it returns True.
+
+ The actual polling logic is encapsulated in :meth:`result` method. See
+ documentation for that method for details on how polling works.
+
+ .. note::
+
+ Privacy here is intended to prevent the final class from
+ overexposing, not to prevent subclasses from accessing methods.
+
+ Args:
+ polling (google.api_core.retry.Retry): The configuration used for polling.
+ This parameter controls how often :meth:`done` is polled. If the
+ ``timeout`` argument is specified in :meth:`result` method it will
+ override the ``polling.timeout`` property.
+ retry (google.api_core.retry.Retry): DEPRECATED use ``polling`` instead.
+ If set, it will override ``polling`` parameter for backward
+ compatibility.
+ """
+
+ _DEFAULT_VALUE = object()
+
+ def __init__(self, polling=DEFAULT_POLLING, **kwargs):
+ super(PollingFuture, self).__init__()
+ self._polling = kwargs.get("retry", polling)
+ self._result = None
+ self._exception = None
+ self._result_set = False
+ """bool: Set to True when the result has been set via set_result or
+ set_exception."""
+ self._polling_thread = None
+ self._done_callbacks = []
+
+ @abc.abstractmethod
+ def done(self, retry=None):
+ """Checks to see if the operation is complete.
+
+ Args:
+ retry (google.api_core.retry.Retry): (Optional) How to retry the
+ polling RPC (to not be confused with polling configuration. See
+ the documentation for :meth:`result` for details).
+
+ Returns:
+ bool: True if the operation is complete, False otherwise.
+ """
+ # pylint: disable=redundant-returns-doc, missing-raises-doc
+ raise NotImplementedError()
+
+ def _done_or_raise(self, retry=None):
+ """Check if the future is done and raise if it's not."""
+ if not self.done(retry=retry):
+ raise _OperationNotComplete()
+
+ def running(self):
+ """True if the operation is currently running."""
+ return not self.done()
+
+ def _blocking_poll(self, timeout=_DEFAULT_VALUE, retry=None, polling=None):
+ """Poll and wait for the Future to be resolved."""
+
+ if self._result_set:
+ return
+
+ polling = polling or self._polling
+ if timeout is not PollingFuture._DEFAULT_VALUE:
+ polling = polling.with_timeout(timeout)
+
+ try:
+ polling(self._done_or_raise)(retry=retry)
+ except exceptions.RetryError:
+ raise concurrent.futures.TimeoutError(
+ f"Operation did not complete within the designated timeout of "
+ f"{polling.timeout} seconds."
+ )
+
+ def result(self, timeout=_DEFAULT_VALUE, retry=None, polling=None):
+ """Get the result of the operation.
+
+ This method will poll for operation status periodically, blocking if
+ necessary. If you just want to make sure that this method does not block
+ for more than X seconds and you do not care about the nitty-gritty of
+ how this method operates, just call it with ``result(timeout=X)``. The
+ other parameters are for advanced use only.
+
+ Every call to this method is controlled by the following three
+ parameters, each of which has a specific, distinct role, even though all three
+ may look very similar: ``timeout``, ``retry`` and ``polling``. In most
+ cases users do not need to specify any custom values for any of these
+ parameters and may simply rely on default ones instead.
+
+ If you choose to specify custom parameters, please make sure you've
+ read the documentation below carefully.
+
+ First, please check :class:`google.api_core.retry.Retry`
+ class documentation for the proper definition of timeout and deadline
+ terms and for the definition the three different types of timeouts.
+ This class operates in terms of Retry Timeout and Polling Timeout. It
+ does not let customizing RPC timeout and the user is expected to rely on
+ default behavior for it.
+
+ The roles of each argument of this method are as follows:
+
+ ``timeout`` (int): (Optional) The Polling Timeout as defined in
+ :class:`google.api_core.retry.Retry`. If the operation does not complete
+ within this timeout an exception will be thrown. This parameter affects
+ neither Retry Timeout nor RPC Timeout.
+
+ ``retry`` (google.api_core.retry.Retry): (Optional) How to retry the
+ polling RPC. The ``retry.timeout`` property of this parameter is the
+ Retry Timeout as defined in :class:`google.api_core.retry.Retry`.
+ This parameter defines ONLY how the polling RPC call is retried
+ (i.e. what to do if the RPC we used for polling returned an error). It
+ does NOT define how the polling is done (i.e. how frequently and for
+ how long to call the polling RPC); use the ``polling`` parameter for that.
+ If a polling RPC throws and error and retrying it fails, the whole
+ future fails with the corresponding exception. If you want to tune which
+ server response error codes are not fatal for operation polling, use this
+ parameter to control that (``retry.predicate`` in particular).
+
+ ``polling`` (google.api_core.retry.Retry): (Optional) How often and
+ for how long to call the polling RPC periodically (i.e. what to do if
+ a polling rpc returned successfully but its returned result indicates
+ that the long running operation is not completed yet, so we need to
+ check it again at some point in future). This parameter does NOT define
+ how to retry each individual polling RPC in case of an error; use the
+ ``retry`` parameter for that. The ``polling.timeout`` of this parameter
+ is Polling Timeout as defined in as defined in
+ :class:`google.api_core.retry.Retry`.
+
+ For each of the arguments, there are also default values in place, which
+ will be used if a user does not specify their own. The default values
+ for the three parameters are not to be confused with the default values
+ for the corresponding arguments in this method (those serve as "not set"
+ markers for the resolution logic).
+
+ If ``timeout`` is provided (i.e.``timeout is not _DEFAULT VALUE``; note
+ the ``None`` value means "infinite timeout"), it will be used to control
+ the actual Polling Timeout. Otherwise, the ``polling.timeout`` value
+ will be used instead (see below for how the ``polling`` config itself
+ gets resolved). In other words, this parameter effectively overrides
+ the ``polling.timeout`` value if specified. This is so to preserve
+ backward compatibility.
+
+ If ``retry`` is provided (i.e. ``retry is not None``) it will be used to
+ control retry behavior for the polling RPC and the ``retry.timeout``
+ will determine the Retry Timeout. If not provided, the
+ polling RPC will be called with whichever default retry config was
+ specified for the polling RPC at the moment of the construction of the
+ polling RPC's client. For example, if the polling RPC is
+ ``operations_client.get_operation()``, the ``retry`` parameter will be
+ controlling its retry behavior (not polling behavior) and, if not
+ specified, that specific method (``operations_client.get_operation()``)
+ will be retried according to the default retry config provided during
+ creation of ``operations_client`` client instead. This argument exists
+ mainly for backward compatibility; users are very unlikely to ever need
+ to set this parameter explicitly.
+
+ If ``polling`` is provided (i.e. ``polling is not None``), it will be used
+ to control the overall polling behavior and ``polling.timeout`` will
+ control Polling Timeout unless it is overridden by ``timeout`` parameter
+ as described above. If not provided, the``polling`` parameter specified
+ during construction of this future (the ``polling`` argument in the
+ constructor) will be used instead. Note: since the ``timeout`` argument may
+ override ``polling.timeout`` value, this parameter should be viewed as
+ coupled with the ``timeout`` parameter as described above.
+
+ Args:
+ timeout (int): (Optional) How long (in seconds) to wait for the
+ operation to complete. If None, wait indefinitely.
+ retry (google.api_core.retry.Retry): (Optional) How to retry the
+ polling RPC. This defines ONLY how the polling RPC call is
+ retried (i.e. what to do if the RPC we used for polling returned
+ an error). It does NOT define how the polling is done (i.e. how
+ frequently and for how long to call the polling RPC).
+ polling (google.api_core.retry.Retry): (Optional) How often and
+ for how long to call polling RPC periodically. This parameter
+ does NOT define how to retry each individual polling RPC call
+ (use the ``retry`` parameter for that).
+
+ Returns:
+ google.protobuf.Message: The Operation's result.
+
+ Raises:
+ google.api_core.GoogleAPICallError: If the operation errors or if
+ the timeout is reached before the operation completes.
+ """
+
+ self._blocking_poll(timeout=timeout, retry=retry, polling=polling)
+
+ if self._exception is not None:
+ # pylint: disable=raising-bad-type
+ # Pylint doesn't recognize that this is valid in this case.
+ raise self._exception
+
+ return self._result
+
+ def exception(self, timeout=_DEFAULT_VALUE):
+ """Get the exception from the operation, blocking if necessary.
+
+ See the documentation for the :meth:`result` method for details on how
+ this method operates, as both ``result`` and this method rely on the
+ exact same polling logic. The only difference is that this method does
+ not accept ``retry`` and ``polling`` arguments but relies on the default ones
+ instead.
+
+ Args:
+ timeout (int): How long to wait for the operation to complete.
+ If None, wait indefinitely.
+
+ Returns:
+ Optional[google.api_core.GoogleAPICallError]: The operation's
+ error.
+ """
+ self._blocking_poll(timeout=timeout)
+ return self._exception
+
+ def add_done_callback(self, fn):
+ """Add a callback to be executed when the operation is complete.
+
+ If the operation is not already complete, this will start a helper
+ thread to poll for the status of the operation in the background.
+
+ Args:
+ fn (Callable[Future]): The callback to execute when the operation
+ is complete.
+ """
+ if self._result_set:
+ _helpers.safe_invoke_callback(fn, self)
+ return
+
+ self._done_callbacks.append(fn)
+
+ if self._polling_thread is None:
+ # The polling thread will exit on its own as soon as the operation
+ # is done.
+ self._polling_thread = _helpers.start_daemon_thread(
+ target=self._blocking_poll
+ )
+
+ def _invoke_callbacks(self, *args, **kwargs):
+ """Invoke all done callbacks."""
+ for callback in self._done_callbacks:
+ _helpers.safe_invoke_callback(callback, *args, **kwargs)
+
+ def set_result(self, result):
+ """Set the Future's result."""
+ self._result = result
+ self._result_set = True
+ self._invoke_callbacks(self)
+
+ def set_exception(self, exception):
+ """Set the Future's exception."""
+ self._exception = exception
+ self._result_set = True
+ self._invoke_callbacks(self)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5b7ad352ee60fe79e8ddefbf3e61bb28afe6432
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from google.api_core.gapic_v1 import client_info
+from google.api_core.gapic_v1 import config
+from google.api_core.gapic_v1 import config_async
+from google.api_core.gapic_v1 import method
+from google.api_core.gapic_v1 import method_async
+from google.api_core.gapic_v1 import routing_header
+
+__all__ = [
+ "client_info",
+ "config",
+ "config_async",
+ "method",
+ "method_async",
+ "routing_header",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a91e45d52c260a478836d1aefd917e97251d069a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/client_info.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/client_info.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad1718aec3bb2f12779142de0ed07c4af0f9a52a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/client_info.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..700aacd36e90d2f4c11425a5abcb5955c6c0a013
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/config.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/config_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/config_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4920f431142f6bf30be921636544a0a67323540d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/config_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/method.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/method.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02c258a3a5cea1b3e6daa0e7ce98b30d3179ab40
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/method.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/method_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/method_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38ac55758dc0790c59c3d9462d94b0273f644cd1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/method_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/routing_header.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/routing_header.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..03fe77cd1b4152942a07fb4cbc31a9e57eb3ba48
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/__pycache__/routing_header.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/client_info.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/client_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b3b56493f8afc3948889cbbf77611f7f609f607
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/client_info.py
@@ -0,0 +1,58 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers for providing client information.
+
+Client information is used to send information about the calling client,
+such as the library and Python version, to API services.
+"""
+
+from google.api_core import client_info
+
+
+METRICS_METADATA_KEY = "x-goog-api-client"
+
+
+class ClientInfo(client_info.ClientInfo):
+ """Client information used to generate a user-agent for API calls.
+
+ This user-agent information is sent along with API calls to allow the
+ receiving service to do analytics on which versions of Python and Google
+ libraries are being used.
+
+ Args:
+ python_version (str): The Python interpreter version, for example,
+ ``'3.9.6'``.
+ grpc_version (Optional[str]): The gRPC library version.
+ api_core_version (str): The google-api-core library version.
+ gapic_version (Optional[str]): The version of gapic-generated client
+ library, if the library was generated by gapic.
+ client_library_version (Optional[str]): The version of the client
+ library, generally used if the client library was not generated
+ by gapic or if additional functionality was built on top of
+ a gapic client library.
+ user_agent (Optional[str]): Prefix to the user agent header. This is
+ used to supply information such as application name or partner tool.
+ Recommended format: ``application-or-tool-ID/major.minor.version``.
+ rest_version (Optional[str]): A string with labeled versions of the
+ dependencies used for REST transport.
+ protobuf_runtime_version (Optional[str]): The protobuf runtime version.
+ """
+
+ def to_grpc_metadata(self):
+ """Returns the gRPC metadata for this client info."""
+ return (METRICS_METADATA_KEY, self.to_user_agent())
+
+
+DEFAULT_CLIENT_INFO = ClientInfo()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/config.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..36b50d9fc4b4a59cf2a8b6c7335e74a43bb5fe97
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/config.py
@@ -0,0 +1,175 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers for loading gapic configuration data.
+
+The Google API generator creates supplementary configuration for each RPC
+method to tell the client library how to deal with retries and timeouts.
+"""
+
+import collections
+
+import grpc
+
+from google.api_core import exceptions
+from google.api_core import retry
+from google.api_core import timeout
+
+
+_MILLIS_PER_SECOND = 1000.0
+
+
+def _exception_class_for_grpc_status_name(name):
+ """Returns the Google API exception class for a gRPC error code name.
+
+ DEPRECATED: use ``exceptions.exception_class_for_grpc_status`` method
+ directly instead.
+
+ Args:
+ name (str): The name of the gRPC status code, for example,
+ ``UNAVAILABLE``.
+
+ Returns:
+ :func:`type`: The appropriate subclass of
+ :class:`google.api_core.exceptions.GoogleAPICallError`.
+ """
+ return exceptions.exception_class_for_grpc_status(getattr(grpc.StatusCode, name))
+
+
+def _retry_from_retry_config(retry_params, retry_codes, retry_impl=retry.Retry):
+ """Creates a Retry object given a gapic retry configuration.
+
+ DEPRECATED: instantiate retry and timeout classes directly instead.
+
+ Args:
+ retry_params (dict): The retry parameter values, for example::
+
+ {
+ "initial_retry_delay_millis": 1000,
+ "retry_delay_multiplier": 2.5,
+ "max_retry_delay_millis": 120000,
+ "initial_rpc_timeout_millis": 120000,
+ "rpc_timeout_multiplier": 1.0,
+ "max_rpc_timeout_millis": 120000,
+ "total_timeout_millis": 600000
+ }
+
+ retry_codes (sequence[str]): The list of retryable gRPC error code
+ names.
+
+ Returns:
+ google.api_core.retry.Retry: The default retry object for the method.
+ """
+ exception_classes = [
+ _exception_class_for_grpc_status_name(code) for code in retry_codes
+ ]
+ return retry_impl(
+ retry.if_exception_type(*exception_classes),
+ initial=(retry_params["initial_retry_delay_millis"] / _MILLIS_PER_SECOND),
+ maximum=(retry_params["max_retry_delay_millis"] / _MILLIS_PER_SECOND),
+ multiplier=retry_params["retry_delay_multiplier"],
+ deadline=retry_params["total_timeout_millis"] / _MILLIS_PER_SECOND,
+ )
+
+
+def _timeout_from_retry_config(retry_params):
+ """Creates a ExponentialTimeout object given a gapic retry configuration.
+
+ DEPRECATED: instantiate retry and timeout classes directly instead.
+
+ Args:
+ retry_params (dict): The retry parameter values, for example::
+
+ {
+ "initial_retry_delay_millis": 1000,
+ "retry_delay_multiplier": 2.5,
+ "max_retry_delay_millis": 120000,
+ "initial_rpc_timeout_millis": 120000,
+ "rpc_timeout_multiplier": 1.0,
+ "max_rpc_timeout_millis": 120000,
+ "total_timeout_millis": 600000
+ }
+
+ Returns:
+ google.api_core.retry.ExponentialTimeout: The default time object for
+ the method.
+ """
+ return timeout.ExponentialTimeout(
+ initial=(retry_params["initial_rpc_timeout_millis"] / _MILLIS_PER_SECOND),
+ maximum=(retry_params["max_rpc_timeout_millis"] / _MILLIS_PER_SECOND),
+ multiplier=retry_params["rpc_timeout_multiplier"],
+ deadline=(retry_params["total_timeout_millis"] / _MILLIS_PER_SECOND),
+ )
+
+
+MethodConfig = collections.namedtuple("MethodConfig", ["retry", "timeout"])
+
+
+def parse_method_configs(interface_config, retry_impl=retry.Retry):
+ """Creates default retry and timeout objects for each method in a gapic
+ interface config.
+
+ DEPRECATED: instantiate retry and timeout classes directly instead.
+
+ Args:
+ interface_config (Mapping): The interface config section of the full
+ gapic library config. For example, If the full configuration has
+ an interface named ``google.example.v1.ExampleService`` you would
+ pass in just that interface's configuration, for example
+ ``gapic_config['interfaces']['google.example.v1.ExampleService']``.
+ retry_impl (Callable): The constructor that creates a retry decorator
+ that will be applied to the method based on method configs.
+
+ Returns:
+ Mapping[str, MethodConfig]: A mapping of RPC method names to their
+ configuration.
+ """
+ # Grab all the retry codes
+ retry_codes_map = {
+ name: retry_codes
+ for name, retry_codes in interface_config.get("retry_codes", {}).items()
+ }
+
+ # Grab all of the retry params
+ retry_params_map = {
+ name: retry_params
+ for name, retry_params in interface_config.get("retry_params", {}).items()
+ }
+
+ # Iterate through all the API methods and create a flat MethodConfig
+ # instance for each one.
+ method_configs = {}
+
+ for method_name, method_params in interface_config.get("methods", {}).items():
+ retry_params_name = method_params.get("retry_params_name")
+
+ if retry_params_name is not None:
+ retry_params = retry_params_map[retry_params_name]
+ retry_ = _retry_from_retry_config(
+ retry_params,
+ retry_codes_map[method_params["retry_codes_name"]],
+ retry_impl,
+ )
+ timeout_ = _timeout_from_retry_config(retry_params)
+
+ # No retry config, so this is a non-retryable method.
+ else:
+ retry_ = None
+ timeout_ = timeout.ConstantTimeout(
+ method_params["timeout_millis"] / _MILLIS_PER_SECOND
+ )
+
+ method_configs[method_name] = MethodConfig(retry=retry_, timeout=timeout_)
+
+ return method_configs
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/config_async.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/config_async.py
new file mode 100644
index 0000000000000000000000000000000000000000..13d6a4805bf56e97ce5ac5337fa4638a577bf74f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/config_async.py
@@ -0,0 +1,42 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""AsyncIO helpers for loading gapic configuration data.
+
+The Google API generator creates supplementary configuration for each RPC
+method to tell the client library how to deal with retries and timeouts.
+"""
+
+from google.api_core import retry_async
+from google.api_core.gapic_v1 import config
+from google.api_core.gapic_v1.config import MethodConfig # noqa: F401
+
+
+def parse_method_configs(interface_config):
+ """Creates default retry and timeout objects for each method in a gapic
+ interface config with AsyncIO semantics.
+
+ Args:
+ interface_config (Mapping): The interface config section of the full
+ gapic library config. For example, If the full configuration has
+ an interface named ``google.example.v1.ExampleService`` you would
+ pass in just that interface's configuration, for example
+ ``gapic_config['interfaces']['google.example.v1.ExampleService']``.
+
+ Returns:
+ Mapping[str, MethodConfig]: A mapping of RPC method names to their
+ configuration.
+ """
+ return config.parse_method_configs(
+ interface_config, retry_impl=retry_async.AsyncRetry
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/method.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/method.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4481ca198a4cc1dd4a802ed4b9408670e0b1a2f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/method.py
@@ -0,0 +1,250 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers for wrapping low-level gRPC methods with common functionality.
+
+This is used by gapic clients to provide common error mapping, retry, timeout,
+compression, pagination, and long-running operations to gRPC methods.
+"""
+
+import enum
+import functools
+
+from google.api_core import grpc_helpers
+from google.api_core.gapic_v1 import client_info
+from google.api_core.timeout import TimeToDeadlineTimeout
+
+USE_DEFAULT_METADATA = object()
+
+
+class _MethodDefault(enum.Enum):
+ # Uses enum so that pytype/mypy knows that this is the only possible value.
+ # https://stackoverflow.com/a/60605919/101923
+ _DEFAULT_VALUE = object()
+
+
+DEFAULT = _MethodDefault._DEFAULT_VALUE
+"""Sentinel value indicating that a retry, timeout, or compression argument was unspecified,
+so the default should be used."""
+
+
+def _is_not_none_or_false(value):
+ return value is not None and value is not False
+
+
+def _apply_decorators(func, decorators):
+ """Apply a list of decorators to a given function.
+
+ ``decorators`` may contain items that are ``None`` or ``False`` which will
+ be ignored.
+ """
+ filtered_decorators = filter(_is_not_none_or_false, reversed(decorators))
+
+ for decorator in filtered_decorators:
+ func = decorator(func)
+
+ return func
+
+
+class _GapicCallable(object):
+ """Callable that applies retry, timeout, and metadata logic.
+
+ Args:
+ target (Callable): The low-level RPC method.
+ retry (google.api_core.retry.Retry): The default retry for the
+ callable. If ``None``, this callable will not retry by default
+ timeout (google.api_core.timeout.Timeout): The default timeout for the
+ callable (i.e. duration of time within which an RPC must terminate
+ after its start, not to be confused with deadline). If ``None``,
+ this callable will not specify a timeout argument to the low-level
+ RPC method.
+ compression (grpc.Compression): The default compression for the callable.
+ If ``None``, this callable will not specify a compression argument
+ to the low-level RPC method.
+ metadata (Sequence[Tuple[str, str]]): Additional metadata that is
+ provided to the RPC method on every invocation. This is merged with
+ any metadata specified during invocation. If ``None``, no
+ additional metadata will be passed to the RPC method.
+ """
+
+ def __init__(
+ self,
+ target,
+ retry,
+ timeout,
+ compression,
+ metadata=None,
+ ):
+ self._target = target
+ self._retry = retry
+ self._timeout = timeout
+ self._compression = compression
+ self._metadata = metadata
+
+ def __call__(
+ self, *args, timeout=DEFAULT, retry=DEFAULT, compression=DEFAULT, **kwargs
+ ):
+ """Invoke the low-level RPC with retry, timeout, compression, and metadata."""
+
+ if retry is DEFAULT:
+ retry = self._retry
+
+ if timeout is DEFAULT:
+ timeout = self._timeout
+
+ if compression is DEFAULT:
+ compression = self._compression
+
+ if isinstance(timeout, (int, float)):
+ timeout = TimeToDeadlineTimeout(timeout=timeout)
+
+ # Apply all applicable decorators.
+ wrapped_func = _apply_decorators(self._target, [retry, timeout])
+
+ # Add the user agent metadata to the call.
+ if self._metadata is not None:
+ metadata = kwargs.get("metadata", [])
+ # Due to the nature of invocation, None should be treated the same
+ # as not specified.
+ if metadata is None:
+ metadata = []
+ metadata = list(metadata)
+ metadata.extend(self._metadata)
+ kwargs["metadata"] = metadata
+ if self._compression is not None:
+ kwargs["compression"] = compression
+
+ return wrapped_func(*args, **kwargs)
+
+
+def wrap_method(
+ func,
+ default_retry=None,
+ default_timeout=None,
+ default_compression=None,
+ client_info=client_info.DEFAULT_CLIENT_INFO,
+ *,
+ with_call=False,
+):
+ """Wrap an RPC method with common behavior.
+
+ This applies common error wrapping, retry, timeout, and compression behavior to a function.
+ The wrapped function will take optional ``retry``, ``timeout``, and ``compression``
+ arguments.
+
+ For example::
+
+ import google.api_core.gapic_v1.method
+ from google.api_core import retry
+ from google.api_core import timeout
+ from grpc import Compression
+
+ # The original RPC method.
+ def get_topic(name, timeout=None):
+ request = publisher_v2.GetTopicRequest(name=name)
+ return publisher_stub.GetTopic(request, timeout=timeout)
+
+ default_retry = retry.Retry(deadline=60)
+ default_timeout = timeout.Timeout(deadline=60)
+ default_compression = Compression.NoCompression
+ wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method(
+ get_topic, default_retry)
+
+ # Execute get_topic with default retry and timeout:
+ response = wrapped_get_topic()
+
+ # Execute get_topic without doing any retying but with the default
+ # timeout:
+ response = wrapped_get_topic(retry=None)
+
+ # Execute get_topic but only retry on 5xx errors:
+ my_retry = retry.Retry(retry.if_exception_type(
+ exceptions.InternalServerError))
+ response = wrapped_get_topic(retry=my_retry)
+
+ The way this works is by late-wrapping the given function with the retry
+ and timeout decorators. Essentially, when ``wrapped_get_topic()`` is
+ called:
+
+ * ``get_topic()`` is first wrapped with the ``timeout`` into
+ ``get_topic_with_timeout``.
+ * ``get_topic_with_timeout`` is wrapped with the ``retry`` into
+ ``get_topic_with_timeout_and_retry()``.
+ * The final ``get_topic_with_timeout_and_retry`` is called passing through
+ the ``args`` and ``kwargs``.
+
+ The callstack is therefore::
+
+ method.__call__() ->
+ Retry.__call__() ->
+ Timeout.__call__() ->
+ wrap_errors() ->
+ get_topic()
+
+ Note that if ``timeout`` or ``retry`` is ``None``, then they are not
+ applied to the function. For example,
+ ``wrapped_get_topic(timeout=None, retry=None)`` is more or less
+ equivalent to just calling ``get_topic`` but with error re-mapping.
+
+ Args:
+ func (Callable[Any]): The function to wrap. It should accept an
+ optional ``timeout`` argument. If ``metadata`` is not ``None``, it
+ should accept a ``metadata`` argument.
+ default_retry (Optional[google.api_core.Retry]): The default retry
+ strategy. If ``None``, the method will not retry by default.
+ default_timeout (Optional[google.api_core.Timeout]): The default
+ timeout strategy. Can also be specified as an int or float. If
+ ``None``, the method will not have timeout specified by default.
+ default_compression (Optional[grpc.Compression]): The default
+ grpc.Compression. If ``None``, the method will not have
+ compression specified by default.
+ client_info
+ (Optional[google.api_core.gapic_v1.client_info.ClientInfo]):
+ Client information used to create a user-agent string that's
+ passed as gRPC metadata to the method. If unspecified, then
+ a sane default will be used. If ``None``, then no user agent
+ metadata will be provided to the RPC method.
+ with_call (bool): If True, wrapped grpc.UnaryUnaryMulticallables will
+ return a tuple of (response, grpc.Call) instead of just the response.
+ This is useful for extracting trailing metadata from unary calls.
+ Defaults to False.
+
+ Returns:
+ Callable: A new callable that takes optional ``retry``, ``timeout``,
+ and ``compression``
+ arguments and applies the common error mapping, retry, timeout, compression,
+ and metadata behavior to the low-level RPC method.
+ """
+ if with_call:
+ try:
+ func = func.with_call
+ except AttributeError as exc:
+ raise ValueError(
+ "with_call=True is only supported for unary calls."
+ ) from exc
+ func = grpc_helpers.wrap_errors(func)
+ if client_info is not None:
+ user_agent_metadata = [client_info.to_grpc_metadata()]
+ else:
+ user_agent_metadata = None
+
+ return functools.wraps(func)(
+ _GapicCallable(
+ func,
+ default_retry,
+ default_timeout,
+ default_compression,
+ metadata=user_agent_metadata,
+ )
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/method_async.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/method_async.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0f38c0e871bb7411707fb73c24a81638be863ae
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/method_async.py
@@ -0,0 +1,59 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""AsyncIO helpers for wrapping gRPC methods with common functionality.
+
+This is used by gapic clients to provide common error mapping, retry, timeout,
+compression, pagination, and long-running operations to gRPC methods.
+"""
+
+import functools
+
+from google.api_core import grpc_helpers_async
+from google.api_core.gapic_v1 import client_info
+from google.api_core.gapic_v1.method import _GapicCallable
+from google.api_core.gapic_v1.method import DEFAULT # noqa: F401
+from google.api_core.gapic_v1.method import USE_DEFAULT_METADATA # noqa: F401
+
+_DEFAULT_ASYNC_TRANSPORT_KIND = "grpc_asyncio"
+
+
+def wrap_method(
+ func,
+ default_retry=None,
+ default_timeout=None,
+ default_compression=None,
+ client_info=client_info.DEFAULT_CLIENT_INFO,
+ kind=_DEFAULT_ASYNC_TRANSPORT_KIND,
+):
+ """Wrap an async RPC method with common behavior.
+
+ Returns:
+ Callable: A new callable that takes optional ``retry``, ``timeout``,
+ and ``compression`` arguments and applies the common error mapping,
+ retry, timeout, metadata, and compression behavior to the low-level RPC method.
+ """
+ if kind == _DEFAULT_ASYNC_TRANSPORT_KIND:
+ func = grpc_helpers_async.wrap_errors(func)
+
+ metadata = [client_info.to_grpc_metadata()] if client_info is not None else None
+
+ return functools.wraps(func)(
+ _GapicCallable(
+ func,
+ default_retry,
+ default_timeout,
+ default_compression,
+ metadata=metadata,
+ )
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/routing_header.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/routing_header.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0c6f648233b92b07cd2c222cdd32781e39ff5f1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/gapic_v1/routing_header.py
@@ -0,0 +1,87 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers for constructing routing headers.
+
+These headers are used by Google infrastructure to determine how to route
+requests, especially for services that are regional.
+
+Generally, these headers are specified as gRPC metadata.
+"""
+
+import functools
+from enum import Enum
+from urllib.parse import urlencode
+
+ROUTING_METADATA_KEY = "x-goog-request-params"
+# This is the value for the `maxsize` argument of @functools.lru_cache
+# https://docs.python.org/3/library/functools.html#functools.lru_cache
+# This represents the number of recent function calls to store.
+ROUTING_PARAM_CACHE_SIZE = 32
+
+
+def to_routing_header(params, qualified_enums=True):
+ """Returns a routing header string for the given request parameters.
+
+ Args:
+ params (Mapping[str, str | bytes | Enum]): A dictionary containing the request
+ parameters used for routing.
+ qualified_enums (bool): Whether to represent enum values
+ as their type-qualified symbol names instead of as their
+ unqualified symbol names.
+
+ Returns:
+ str: The routing header string.
+ """
+ tuples = params.items() if isinstance(params, dict) else params
+ if not qualified_enums:
+ tuples = [(x[0], x[1].name) if isinstance(x[1], Enum) else x for x in tuples]
+ return "&".join([_urlencode_param(*t) for t in tuples])
+
+
+def to_grpc_metadata(params, qualified_enums=True):
+ """Returns the gRPC metadata containing the routing headers for the given
+ request parameters.
+
+ Args:
+ params (Mapping[str, str | bytes | Enum]): A dictionary containing the request
+ parameters used for routing.
+ qualified_enums (bool): Whether to represent enum values
+ as their type-qualified symbol names instead of as their
+ unqualified symbol names.
+
+ Returns:
+ Tuple(str, str): The gRPC metadata containing the routing header key
+ and value.
+ """
+ return (ROUTING_METADATA_KEY, to_routing_header(params, qualified_enums))
+
+
+# use caching to avoid repeated computation
+@functools.lru_cache(maxsize=ROUTING_PARAM_CACHE_SIZE)
+def _urlencode_param(key, value):
+ """Cacheable wrapper over urlencode
+
+ Args:
+ key (str): The key of the parameter to encode.
+ value (str | bytes | Enum): The value of the parameter to encode.
+
+ Returns:
+ str: The encoded parameter.
+ """
+ return urlencode(
+ {key: value},
+ # Per Google API policy (go/api-url-encoding), / is not encoded.
+ safe="/",
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4db32a4cb0afe86c0302184f7e8b2c7c053ff5f3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__init__.py
@@ -0,0 +1,40 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Package for interacting with the google.longrunning.operations meta-API."""
+
+from google.api_core.operations_v1.abstract_operations_client import AbstractOperationsClient
+from google.api_core.operations_v1.operations_async_client import OperationsAsyncClient
+from google.api_core.operations_v1.operations_client import OperationsClient
+from google.api_core.operations_v1.transports.rest import OperationsRestTransport
+
+__all__ = [
+ "AbstractOperationsClient",
+ "OperationsAsyncClient",
+ "OperationsClient",
+ "OperationsRestTransport"
+]
+
+try:
+ from google.api_core.operations_v1.transports.rest_asyncio import (
+ AsyncOperationsRestTransport,
+ )
+ from google.api_core.operations_v1.operations_rest_client_async import AsyncOperationsRestClient
+
+ __all__ += ["AsyncOperationsRestClient", "AsyncOperationsRestTransport"]
+except ImportError:
+ # This import requires the `async_rest` extra.
+ # Don't raise an exception if `AsyncOperationsRestTransport` cannot be imported
+ # as other transports are still available.
+ pass
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..affa665ba2d8cc2911ed448f0af6da7e0bf2a852
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_base_client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_base_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..036b6d69ee22bb5ff3c9f314a3f83164d6912c27
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_base_client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59c8c2c7f34feb3cac06616cb177fb220e3c4500
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_async_client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_async_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b08b382b78cf6e80a7f62e03d28ad113529d6c53
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_async_client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ca8746b5f7a6352ac725e77431e225bfc7da8e3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client_config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client_config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5971fc7dbacec47be4cd42a3282c6d9e7338cae8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client_config.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_rest_client_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_rest_client_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0999b4cac806bcf03babbe1f4ed30f0dca03773
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_rest_client_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31c4cb0ca75f7691c2eb63ee3515bb18d5c26200
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8034549d784a5848b503ab58f26b9f57af1ea3f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4a53ba9d5e1c0b2aa081c795b5dea69aa911270
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_base.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_base_client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_base_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..f62f60b0414a71a4b859839ff8e02b1411f858c4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_base_client.py
@@ -0,0 +1,376 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections import OrderedDict
+import os
+import re
+from typing import Dict, Optional, Type, Union
+
+from google.api_core import client_options as client_options_lib # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core.operations_v1.transports.base import (
+ DEFAULT_CLIENT_INFO,
+ OperationsTransport,
+)
+from google.api_core.operations_v1.transports.rest import OperationsRestTransport
+
+try:
+ from google.api_core.operations_v1.transports.rest_asyncio import (
+ AsyncOperationsRestTransport,
+ )
+
+ HAS_ASYNC_REST_DEPENDENCIES = True
+except ImportError as e:
+ HAS_ASYNC_REST_DEPENDENCIES = False
+ ASYNC_REST_EXCEPTION = e
+
+from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.exceptions import MutualTLSChannelError # type: ignore
+from google.auth.transport import mtls # type: ignore
+
+
+class AbstractOperationsBaseClientMeta(type):
+ """Metaclass for the Operations Base client.
+
+ This provides base class-level methods for building and retrieving
+ support objects (e.g. transport) without polluting the client instance
+ objects.
+ """
+
+ _transport_registry = OrderedDict() # type: Dict[str, Type[OperationsTransport]]
+ _transport_registry["rest"] = OperationsRestTransport
+ if HAS_ASYNC_REST_DEPENDENCIES:
+ _transport_registry["rest_asyncio"] = AsyncOperationsRestTransport
+
+ def get_transport_class(
+ cls,
+ label: Optional[str] = None,
+ ) -> Type[OperationsTransport]:
+ """Returns an appropriate transport class.
+
+ Args:
+ label: The name of the desired transport. If none is
+ provided, then the first transport in the registry is used.
+
+ Returns:
+ The transport class to use.
+ """
+ # If a specific transport is requested, return that one.
+ if (
+ label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES
+ ): # pragma: NO COVER
+ raise ASYNC_REST_EXCEPTION
+
+ if label:
+ return cls._transport_registry[label]
+
+ # No transport is requested; return the default (that is, the first one
+ # in the dictionary).
+ return next(iter(cls._transport_registry.values()))
+
+
+class AbstractOperationsBaseClient(metaclass=AbstractOperationsBaseClientMeta):
+ """Manages long-running operations with an API service.
+
+ When an API method normally takes long time to complete, it can be
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
+ client, and the client can use this interface to receive the real
+ response asynchronously by polling the operation resource, or pass
+ the operation resource to another API (such as Google Cloud Pub/Sub
+ API) to receive the response. Any API service that returns
+ long-running operations should implement the ``Operations``
+ interface so developers can have a consistent client experience.
+ """
+
+ @staticmethod
+ def _get_default_mtls_endpoint(api_endpoint):
+ """Converts api endpoint to mTLS endpoint.
+
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
+ Args:
+ api_endpoint (Optional[str]): the api endpoint to convert.
+ Returns:
+ str: converted mTLS api endpoint.
+ """
+ if not api_endpoint:
+ return api_endpoint
+
+ mtls_endpoint_re = re.compile(
+ r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?"
+ )
+
+ m = mtls_endpoint_re.match(api_endpoint)
+ name, mtls, sandbox, googledomain = m.groups()
+ if mtls or not googledomain:
+ return api_endpoint
+
+ if sandbox:
+ return api_endpoint.replace(
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
+ )
+
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
+
+ DEFAULT_ENDPOINT = "longrunning.googleapis.com"
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
+ DEFAULT_ENDPOINT
+ )
+
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """
+ This class method should be overridden by the subclasses.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Raises:
+ NotImplementedError: If the method is called on the base class.
+ """
+ raise NotImplementedError("`from_service_account_info` is not implemented.")
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """
+ This class method should be overridden by the subclasses.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Raises:
+ NotImplementedError: If the method is called on the base class.
+ """
+ raise NotImplementedError("`from_service_account_file` is not implemented.")
+
+ from_service_account_json = from_service_account_file
+
+ @property
+ def transport(self) -> OperationsTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ OperationsTransport: The transport used by the client
+ instance.
+ """
+ return self._transport
+
+ @staticmethod
+ def common_billing_account_path(
+ billing_account: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account string."""
+ return "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+
+ @staticmethod
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
+ """Parse a billing_account path into its component segments."""
+ m = re.match(r"^billingAccounts/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_folder_path(
+ folder: str,
+ ) -> str:
+ """Returns a fully-qualified folder string."""
+ return "folders/{folder}".format(
+ folder=folder,
+ )
+
+ @staticmethod
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
+ """Parse a folder path into its component segments."""
+ m = re.match(r"^folders/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_organization_path(
+ organization: str,
+ ) -> str:
+ """Returns a fully-qualified organization string."""
+ return "organizations/{organization}".format(
+ organization=organization,
+ )
+
+ @staticmethod
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
+ """Parse a organization path into its component segments."""
+ m = re.match(r"^organizations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_project_path(
+ project: str,
+ ) -> str:
+ """Returns a fully-qualified project string."""
+ return "projects/{project}".format(
+ project=project,
+ )
+
+ @staticmethod
+ def parse_common_project_path(path: str) -> Dict[str, str]:
+ """Parse a project path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_location_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified location string."""
+ return "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_common_location_path(path: str) -> Dict[str, str]:
+ """Parse a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Union[str, OperationsTransport, None] = None,
+ client_options: Optional[client_options_lib.ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the operations client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, OperationsTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
+ client. It won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint) and "auto" (auto switch to the
+ default mTLS endpoint if client certificate is present, this is
+ the default value). However, the ``api_endpoint`` property takes
+ precedence if provided.
+ (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
+ is "true", then the ``client_cert_source`` property can be used
+ to provide client certificate for mutual TLS transport. If
+ not provided, the default SSL client certificate will be used if
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
+ set, no client certificate will be used.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+
+ Raises:
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+ if isinstance(client_options, dict):
+ client_options = client_options_lib.from_dict(client_options)
+ if client_options is None:
+ client_options = client_options_lib.ClientOptions()
+
+ # Create SSL credentials for mutual TLS if needed.
+ if hasattr(mtls, "should_use_client_cert"):
+ use_client_cert = mtls.should_use_client_cert()
+ else:
+ # if unsupported, fallback to reading from env var
+ use_client_cert_str = os.getenv(
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
+ ).lower()
+ if use_client_cert_str not in ("true", "false"):
+ raise ValueError(
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be"
+ " either `true` or `false`"
+ )
+ use_client_cert = use_client_cert_str == "true"
+ client_cert_source_func = None
+ is_mtls = False
+ if use_client_cert:
+ if client_options.client_cert_source:
+ is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
+ else:
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
+
+ # Figure out which api endpoint to use.
+ if client_options.api_endpoint is not None:
+ api_endpoint = client_options.api_endpoint
+ else:
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
+ if use_mtls_env == "never":
+ api_endpoint = self.DEFAULT_ENDPOINT
+ elif use_mtls_env == "always":
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ elif use_mtls_env == "auto":
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
+ else:
+ raise MutualTLSChannelError(
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
+ )
+
+ # Save or instantiate the transport.
+ # Ordinarily, we provide the transport, but allowing a custom transport
+ # instance provides an extensibility point for unusual situations.
+ if isinstance(transport, OperationsTransport):
+ # transport is a OperationsTransport instance.
+ if credentials or client_options.credentials_file:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its credentials directly."
+ )
+ if client_options.scopes:
+ raise ValueError(
+ "When providing a transport instance, provide its scopes "
+ "directly."
+ )
+ self._transport = transport
+ else:
+ Transport = type(self).get_transport_class(transport)
+ self._transport = Transport(
+ credentials=credentials,
+ credentials_file=client_options.credentials_file,
+ host=api_endpoint,
+ scopes=client_options.scopes,
+ client_cert_source_for_mtls=client_cert_source_func,
+ quota_project_id=client_options.quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=True,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc445362532cd56e25668b83367f1bb80fe1405e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_client.py
@@ -0,0 +1,387 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import Optional, Sequence, Tuple, Union
+
+from google.api_core import client_options as client_options_lib # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.api_core.operations_v1 import pagers
+from google.api_core.operations_v1.transports.base import (
+ DEFAULT_CLIENT_INFO,
+ OperationsTransport,
+)
+from google.api_core.operations_v1.abstract_operations_base_client import (
+ AbstractOperationsBaseClient,
+)
+from google.auth import credentials as ga_credentials # type: ignore
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account # type: ignore
+import grpc
+
+OptionalRetry = Union[retries.Retry, object]
+
+
+class AbstractOperationsClient(AbstractOperationsBaseClient):
+ """Manages long-running operations with an API service.
+
+ When an API method normally takes long time to complete, it can be
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
+ client, and the client can use this interface to receive the real
+ response asynchronously by polling the operation resource, or pass
+ the operation resource to another API (such as Google Cloud Pub/Sub
+ API) to receive the response. Any API service that returns
+ long-running operations should implement the ``Operations``
+ interface so developers can have a consistent client experience.
+ """
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Union[str, OperationsTransport, None] = None,
+ client_options: Optional[client_options_lib.ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the operations client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, OperationsTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
+ client. It won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint) and "auto" (auto switch to the
+ default mTLS endpoint if client certificate is present, this is
+ the default value). However, the ``api_endpoint`` property takes
+ precedence if provided.
+ (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
+ is "true", then the ``client_cert_source`` property can be used
+ to provide client certificate for mutual TLS transport. If
+ not provided, the default SSL client certificate will be used if
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
+ set, no client certificate will be used.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+
+ Raises:
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+ super().__init__(
+ credentials=credentials,
+ transport=transport,
+ client_options=client_options,
+ client_info=client_info,
+ )
+
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ AbstractOperationsClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ AbstractOperationsClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_file(filename)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
+ from_service_account_json = from_service_account_file
+
+ def list_operations(
+ self,
+ name: str,
+ filter_: Optional[str] = None,
+ *,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListOperationsPager:
+ r"""Lists operations that match the specified filter in the request.
+ If the server doesn't support this method, it returns
+ ``UNIMPLEMENTED``.
+
+ NOTE: the ``name`` binding allows API services to override the
+ binding to use different resource name schemes, such as
+ ``users/*/operations``. To override the binding, API services
+ can add a binding such as ``"/v1/{name=users/*}/operations"`` to
+ their service configuration. For backwards compatibility, the
+ default name includes the operations collection id, however
+ overriding users must ensure the name binding is the parent
+ resource, without the operations collection id.
+
+ Args:
+ name (str):
+ The name of the operation's parent
+ resource.
+ filter_ (str):
+ The standard list filter.
+ This corresponds to the ``filter`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ google.api_core.operations_v1.pagers.ListOperationsPager:
+ The response message for
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
+
+ Iterating over this object will yield results and
+ resolve additional pages automatically.
+
+ """
+ # Create a protobuf request object.
+ request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
+ if page_size is not None:
+ request.page_size = page_size
+ if page_token is not None:
+ request.page_token = page_token
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.list_operations]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__iter__` convenience method.
+ response = pagers.ListOperationsPager(
+ method=rpc,
+ request=request,
+ response=response,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ def get_operation(
+ self,
+ name: str,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operations_pb2.Operation:
+ r"""Gets the latest state of a long-running operation.
+ Clients can use this method to poll the operation result
+ at intervals as recommended by the API service.
+
+ Args:
+ name (str):
+ The name of the operation resource.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ google.longrunning.operations_pb2.Operation:
+ This resource represents a long-
+ running operation that is the result of a
+ network API call.
+
+ """
+
+ request = operations_pb2.GetOperationRequest(name=name)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.get_operation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ def delete_operation(
+ self,
+ name: str,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes a long-running operation. This method indicates that the
+ client is no longer interested in the operation result. It does
+ not cancel the operation. If the server doesn't support this
+ method, it returns ``google.rpc.Code.UNIMPLEMENTED``.
+
+ Args:
+ name (str):
+ The name of the operation resource to
+ be deleted.
+
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create the request object.
+ request = operations_pb2.DeleteOperationRequest(name=name)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.delete_operation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ def cancel_operation(
+ self,
+ name: Optional[str] = None,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Starts asynchronous cancellation on a long-running operation.
+ The server makes a best effort to cancel the operation, but
+ success is not guaranteed. If the server doesn't support this
+ method, it returns ``google.rpc.Code.UNIMPLEMENTED``. Clients
+ can use
+ [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation]
+ or other methods to check whether the cancellation succeeded or
+ whether the operation completed despite cancellation. On
+ successful cancellation, the operation is not deleted; instead,
+ it becomes an operation with an
+ [Operation.error][google.api_core.operations_v1.Operation.error] value with
+ a [google.rpc.Status.code][google.rpc.Status.code] of 1,
+ corresponding to ``Code.CANCELLED``.
+
+ Args:
+ name (str):
+ The name of the operation resource to
+ be cancelled.
+
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create the request object.
+ request = operations_pb2.CancelOperationRequest(name=name)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_async_client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_async_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..a60c7177705a4bdcadfc6a82171be3787ecbc417
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_async_client.py
@@ -0,0 +1,364 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""An async client for the google.longrunning.operations meta-API.
+
+.. _Google API Style Guide:
+ https://cloud.google.com/apis/design/design_pattern
+ s#long_running_operations
+.. _google/longrunning/operations.proto:
+ https://github.com/googleapis/googleapis/blob/master/google/longrunning
+ /operations.proto
+"""
+
+import functools
+
+from google.api_core import exceptions as core_exceptions
+from google.api_core import gapic_v1, page_iterator_async
+from google.api_core import retry_async as retries
+from google.api_core import timeout as timeouts
+from google.longrunning import operations_pb2
+from grpc import Compression
+
+
+class OperationsAsyncClient:
+ """Async client for interacting with long-running operations.
+
+ Args:
+ channel (aio.Channel): The gRPC AsyncIO channel associated with the
+ service that implements the ``google.longrunning.operations``
+ interface.
+ client_config (dict):
+ A dictionary of call options for each method. If not specified
+ the default configuration is used.
+ """
+
+ def __init__(self, channel, client_config=None):
+ # Create the gRPC client stub with gRPC AsyncIO channel.
+ self.operations_stub = operations_pb2.OperationsStub(channel)
+
+ default_retry = retries.AsyncRetry(
+ initial=0.1, # seconds
+ maximum=60.0, # seconds
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
+ ),
+ timeout=600.0, # seconds
+ )
+ default_timeout = timeouts.TimeToDeadlineTimeout(timeout=600.0)
+
+ default_compression = Compression.NoCompression
+
+ self._get_operation = gapic_v1.method_async.wrap_method(
+ self.operations_stub.GetOperation,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ self._list_operations = gapic_v1.method_async.wrap_method(
+ self.operations_stub.ListOperations,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ self._cancel_operation = gapic_v1.method_async.wrap_method(
+ self.operations_stub.CancelOperation,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ self._delete_operation = gapic_v1.method_async.wrap_method(
+ self.operations_stub.DeleteOperation,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ async def get_operation(
+ self,
+ name,
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout=gapic_v1.method_async.DEFAULT,
+ compression=gapic_v1.method_async.DEFAULT,
+ metadata=None,
+ ):
+ """Gets the latest state of a long-running operation.
+
+ Clients can use this method to poll the operation result at intervals
+ as recommended by the API service.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>> response = await api.get_operation(name)
+
+ Args:
+ name (str): The name of the operation resource.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]):
+ Additional gRPC metadata.
+
+ Returns:
+ google.longrunning.operations_pb2.Operation: The state of the
+ operation.
+
+ Raises:
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ """
+ request = operations_pb2.GetOperationRequest(name=name)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ return await self._get_operation(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ async def list_operations(
+ self,
+ name,
+ filter_,
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout=gapic_v1.method_async.DEFAULT,
+ compression=gapic_v1.method_async.DEFAULT,
+ metadata=None,
+ ):
+ """
+ Lists operations that match the specified filter in the request.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>>
+ >>> # Iterate over all results
+ >>> for operation in await api.list_operations(name):
+ >>> # process operation
+ >>> pass
+ >>>
+ >>> # Or iterate over results one page at a time
+ >>> iter = await api.list_operations(name)
+ >>> for page in iter.pages:
+ >>> for operation in page:
+ >>> # process operation
+ >>> pass
+
+ Args:
+ name (str): The name of the operation collection.
+ filter_ (str): The standard list filter.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
+ metadata.
+
+ Returns:
+ google.api_core.page_iterator.Iterator: An iterator that yields
+ :class:`google.longrunning.operations_pb2.Operation` instances.
+
+ Raises:
+ google.api_core.exceptions.MethodNotImplemented: If the server
+ does not support this method. Services are not required to
+ implement this method.
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ """
+ # Create the request object.
+ request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ # Create the method used to fetch pages
+ method = functools.partial(
+ self._list_operations,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ iterator = page_iterator_async.AsyncGRPCIterator(
+ client=None,
+ method=method,
+ request=request,
+ items_field="operations",
+ request_token_field="page_token",
+ response_token_field="next_page_token",
+ )
+
+ return iterator
+
+ async def cancel_operation(
+ self,
+ name,
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout=gapic_v1.method_async.DEFAULT,
+ compression=gapic_v1.method_async.DEFAULT,
+ metadata=None,
+ ):
+ """Starts asynchronous cancellation on a long-running operation.
+
+ The server makes a best effort to cancel the operation, but success is
+ not guaranteed. Clients can use :meth:`get_operation` or service-
+ specific methods to check whether the cancellation succeeded or whether
+ the operation completed despite cancellation. On successful
+ cancellation, the operation is not deleted; instead, it becomes an
+ operation with an ``Operation.error`` value with a
+ ``google.rpc.Status.code`` of ``1``, corresponding to
+ ``Code.CANCELLED``.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>> api.cancel_operation(name)
+
+ Args:
+ name (str): The name of the operation resource to be cancelled.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+
+ Raises:
+ google.api_core.exceptions.MethodNotImplemented: If the server
+ does not support this method. Services are not required to
+ implement this method.
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
+ metadata.
+ """
+ # Create the request object.
+ request = operations_pb2.CancelOperationRequest(name=name)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ await self._cancel_operation(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ async def delete_operation(
+ self,
+ name,
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout=gapic_v1.method_async.DEFAULT,
+ compression=gapic_v1.method_async.DEFAULT,
+ metadata=None,
+ ):
+ """Deletes a long-running operation.
+
+ This method indicates that the client is no longer interested in the
+ operation result. It does not cancel the operation.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>> api.delete_operation(name)
+
+ Args:
+ name (str): The name of the operation resource to be deleted.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
+ metadata.
+
+ Raises:
+ google.api_core.exceptions.MethodNotImplemented: If the server
+ does not support this method. Services are not required to
+ implement this method.
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ """
+ # Create the request object.
+ request = operations_pb2.DeleteOperationRequest(name=name)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ await self._delete_operation(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1d3fd55c783fefb0af9795728e0b0ab76c325ad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client.py
@@ -0,0 +1,378 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""A client for the google.longrunning.operations meta-API.
+
+This is a client that deals with long-running operations that follow the
+pattern outlined by the `Google API Style Guide`_.
+
+When an API method normally takes long time to complete, it can be designed to
+return ``Operation`` to the client, and the client can use this interface to
+receive the real response asynchronously by polling the operation resource to
+receive the response.
+
+It is not a separate service, but rather an interface implemented by a larger
+service. The protocol-level definition is available at
+`google/longrunning/operations.proto`_. Typically, this will be constructed
+automatically by another client class to deal with operations.
+
+.. _Google API Style Guide:
+ https://cloud.google.com/apis/design/design_pattern
+ s#long_running_operations
+.. _google/longrunning/operations.proto:
+ https://github.com/googleapis/googleapis/blob/master/google/longrunning
+ /operations.proto
+"""
+
+import functools
+
+from google.api_core import exceptions as core_exceptions
+from google.api_core import gapic_v1
+from google.api_core import page_iterator
+from google.api_core import retry as retries
+from google.api_core import timeout as timeouts
+from google.longrunning import operations_pb2
+from grpc import Compression
+
+
+class OperationsClient(object):
+ """Client for interacting with long-running operations within a service.
+
+ Args:
+ channel (grpc.Channel): The gRPC channel associated with the service
+ that implements the ``google.longrunning.operations`` interface.
+ client_config (dict):
+ A dictionary of call options for each method. If not specified
+ the default configuration is used.
+ """
+
+ def __init__(self, channel, client_config=None):
+ # Create the gRPC client stub.
+ self.operations_stub = operations_pb2.OperationsStub(channel)
+
+ default_retry = retries.Retry(
+ initial=0.1, # seconds
+ maximum=60.0, # seconds
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
+ ),
+ timeout=600.0, # seconds
+ )
+ default_timeout = timeouts.TimeToDeadlineTimeout(timeout=600.0)
+
+ default_compression = Compression.NoCompression
+
+ self._get_operation = gapic_v1.method.wrap_method(
+ self.operations_stub.GetOperation,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ self._list_operations = gapic_v1.method.wrap_method(
+ self.operations_stub.ListOperations,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ self._cancel_operation = gapic_v1.method.wrap_method(
+ self.operations_stub.CancelOperation,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ self._delete_operation = gapic_v1.method.wrap_method(
+ self.operations_stub.DeleteOperation,
+ default_retry=default_retry,
+ default_timeout=default_timeout,
+ default_compression=default_compression,
+ )
+
+ # Service calls
+ def get_operation(
+ self,
+ name,
+ retry=gapic_v1.method.DEFAULT,
+ timeout=gapic_v1.method.DEFAULT,
+ compression=gapic_v1.method.DEFAULT,
+ metadata=None,
+ ):
+ """Gets the latest state of a long-running operation.
+
+ Clients can use this method to poll the operation result at intervals
+ as recommended by the API service.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>> response = api.get_operation(name)
+
+ Args:
+ name (str): The name of the operation resource.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]):
+ Additional gRPC metadata.
+
+ Returns:
+ google.longrunning.operations_pb2.Operation: The state of the
+ operation.
+
+ Raises:
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ """
+ request = operations_pb2.GetOperationRequest(name=name)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ return self._get_operation(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ def list_operations(
+ self,
+ name,
+ filter_,
+ retry=gapic_v1.method.DEFAULT,
+ timeout=gapic_v1.method.DEFAULT,
+ compression=gapic_v1.method.DEFAULT,
+ metadata=None,
+ ):
+ """
+ Lists operations that match the specified filter in the request.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>>
+ >>> # Iterate over all results
+ >>> for operation in api.list_operations(name):
+ >>> # process operation
+ >>> pass
+ >>>
+ >>> # Or iterate over results one page at a time
+ >>> iter = api.list_operations(name)
+ >>> for page in iter.pages:
+ >>> for operation in page:
+ >>> # process operation
+ >>> pass
+
+ Args:
+ name (str): The name of the operation collection.
+ filter_ (str): The standard list filter.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
+ metadata.
+
+ Returns:
+ google.api_core.page_iterator.Iterator: An iterator that yields
+ :class:`google.longrunning.operations_pb2.Operation` instances.
+
+ Raises:
+ google.api_core.exceptions.MethodNotImplemented: If the server
+ does not support this method. Services are not required to
+ implement this method.
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ """
+ # Create the request object.
+ request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ # Create the method used to fetch pages
+ method = functools.partial(
+ self._list_operations,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ iterator = page_iterator.GRPCIterator(
+ client=None,
+ method=method,
+ request=request,
+ items_field="operations",
+ request_token_field="page_token",
+ response_token_field="next_page_token",
+ )
+
+ return iterator
+
+ def cancel_operation(
+ self,
+ name,
+ retry=gapic_v1.method.DEFAULT,
+ timeout=gapic_v1.method.DEFAULT,
+ compression=gapic_v1.method.DEFAULT,
+ metadata=None,
+ ):
+ """Starts asynchronous cancellation on a long-running operation.
+
+ The server makes a best effort to cancel the operation, but success is
+ not guaranteed. Clients can use :meth:`get_operation` or service-
+ specific methods to check whether the cancellation succeeded or whether
+ the operation completed despite cancellation. On successful
+ cancellation, the operation is not deleted; instead, it becomes an
+ operation with an ``Operation.error`` value with a
+ ``google.rpc.Status.code`` of ``1``, corresponding to
+ ``Code.CANCELLED``.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>> api.cancel_operation(name)
+
+ Args:
+ name (str): The name of the operation resource to be cancelled.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
+ metadata.
+
+ Raises:
+ google.api_core.exceptions.MethodNotImplemented: If the server
+ does not support this method. Services are not required to
+ implement this method.
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ """
+ # Create the request object.
+ request = operations_pb2.CancelOperationRequest(name=name)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ self._cancel_operation(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
+
+ def delete_operation(
+ self,
+ name,
+ retry=gapic_v1.method.DEFAULT,
+ timeout=gapic_v1.method.DEFAULT,
+ compression=gapic_v1.method.DEFAULT,
+ metadata=None,
+ ):
+ """Deletes a long-running operation.
+
+ This method indicates that the client is no longer interested in the
+ operation result. It does not cancel the operation.
+
+ Example:
+ >>> from google.api_core import operations_v1
+ >>> api = operations_v1.OperationsClient()
+ >>> name = ''
+ >>> api.delete_operation(name)
+
+ Args:
+ name (str): The name of the operation resource to be deleted.
+ retry (google.api_core.retry.Retry): The retry strategy to use
+ when invoking the RPC. If unspecified, the default retry from
+ the client configuration will be used. If ``None``, then this
+ method will not retry the RPC at all.
+ timeout (float): The amount of time in seconds to wait for the RPC
+ to complete. Note that if ``retry`` is used, this timeout
+ applies to each individual attempt and the overall time it
+ takes for this method to complete may be longer. If
+ unspecified, the the default timeout in the client
+ configuration is used. If ``None``, then the RPC method will
+ not time out.
+ compression (grpc.Compression): An element of grpc.compression
+ e.g. grpc.compression.Gzip.
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
+ metadata.
+
+ Raises:
+ google.api_core.exceptions.MethodNotImplemented: If the server
+ does not support this method. Services are not required to
+ implement this method.
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
+ subclass will be raised.
+ """
+ # Create the request object.
+ request = operations_pb2.DeleteOperationRequest(name=name)
+
+ # Add routing header
+ metadata = metadata or []
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
+
+ self._delete_operation(
+ request,
+ retry=retry,
+ timeout=timeout,
+ compression=compression,
+ metadata=metadata,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client_config.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad3548c651a32a79e46dfc7fd668fd36692b00d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client_config.py
@@ -0,0 +1,60 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""gapic configuration for the google.longrunning.operations client."""
+
+# DEPRECATED: retry and timeout classes are instantiated directly
+config = {
+ "interfaces": {
+ "google.longrunning.Operations": {
+ "retry_codes": {
+ "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
+ "non_idempotent": [],
+ },
+ "retry_params": {
+ "default": {
+ "initial_retry_delay_millis": 100,
+ "retry_delay_multiplier": 1.3,
+ "max_retry_delay_millis": 60000,
+ "initial_rpc_timeout_millis": 20000,
+ "rpc_timeout_multiplier": 1.0,
+ "max_rpc_timeout_millis": 600000,
+ "total_timeout_millis": 600000,
+ }
+ },
+ "methods": {
+ "GetOperation": {
+ "timeout_millis": 60000,
+ "retry_codes_name": "idempotent",
+ "retry_params_name": "default",
+ },
+ "ListOperations": {
+ "timeout_millis": 60000,
+ "retry_codes_name": "idempotent",
+ "retry_params_name": "default",
+ },
+ "CancelOperation": {
+ "timeout_millis": 60000,
+ "retry_codes_name": "idempotent",
+ "retry_params_name": "default",
+ },
+ "DeleteOperation": {
+ "timeout_millis": 60000,
+ "retry_codes_name": "idempotent",
+ "retry_params_name": "default",
+ },
+ },
+ }
+ }
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_rest_client_async.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_rest_client_async.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ab0cd36f799bf1288d057d0af7cdf1df4109e63
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/operations_rest_client_async.py
@@ -0,0 +1,345 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import Optional, Sequence, Tuple, Union
+
+from google.api_core import client_options as client_options_lib # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core.operations_v1 import pagers_async as pagers
+from google.api_core.operations_v1.transports.base import (
+ DEFAULT_CLIENT_INFO,
+ OperationsTransport,
+)
+from google.api_core.operations_v1.abstract_operations_base_client import (
+ AbstractOperationsBaseClient,
+)
+from google.longrunning import operations_pb2
+
+try:
+ from google.auth.aio import credentials as ga_credentials # type: ignore
+except ImportError as e: # pragma: NO COVER
+ raise ImportError(
+ "The `async_rest` extra of `google-api-core` is required to use long-running operations. Install it by running "
+ "`pip install google-api-core[async_rest]`."
+ ) from e
+
+
+class AsyncOperationsRestClient(AbstractOperationsBaseClient):
+ """Manages long-running operations with a REST API service for the asynchronous client.
+
+ When an API method normally takes long time to complete, it can be
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
+ client, and the client can use this interface to receive the real
+ response asynchronously by polling the operation resource, or pass
+ the operation resource to another API (such as Google Cloud Pub/Sub
+ API) to receive the response. Any API service that returns
+ long-running operations should implement the ``Operations``
+ interface so developers can have a consistent client experience.
+ """
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Union[str, OperationsTransport, None] = None,
+ client_options: Optional[client_options_lib.ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the operations client.
+
+ Args:
+ credentials (Optional[google.auth.aio.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, OperationsTransport]): The
+ transport to use. If set to None, this defaults to 'rest_asyncio'.
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
+ client. It won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint) and "auto" (auto switch to the
+ default mTLS endpoint if client certificate is present, this is
+ the default value). However, the ``api_endpoint`` property takes
+ precedence if provided.
+ (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
+ is "true", then the ``client_cert_source`` property can be used
+ to provide client certificate for mutual TLS transport. If
+ not provided, the default SSL client certificate will be used if
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
+ set, no client certificate will be used.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+
+ Raises:
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+ super().__init__(
+ credentials=credentials, # type: ignore
+ # NOTE: If a transport is not provided, we force the client to use the async
+ # REST transport.
+ transport=transport or "rest_asyncio",
+ client_options=client_options,
+ client_info=client_info,
+ )
+
+ async def get_operation(
+ self,
+ name: str,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operations_pb2.Operation:
+ r"""Gets the latest state of a long-running operation.
+ Clients can use this method to poll the operation result
+ at intervals as recommended by the API service.
+
+ Args:
+ name (str):
+ The name of the operation resource.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ google.longrunning.operations_pb2.Operation:
+ This resource represents a long-
+ running operation that is the result of a
+ network API call.
+
+ """
+
+ request = operations_pb2.GetOperationRequest(name=name)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.get_operation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def list_operations(
+ self,
+ name: str,
+ filter_: Optional[str] = None,
+ *,
+ page_size: Optional[int] = None,
+ page_token: Optional[str] = None,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListOperationsAsyncPager:
+ r"""Lists operations that match the specified filter in the request.
+ If the server doesn't support this method, it returns
+ ``UNIMPLEMENTED``.
+
+ NOTE: the ``name`` binding allows API services to override the
+ binding to use different resource name schemes, such as
+ ``users/*/operations``. To override the binding, API services
+ can add a binding such as ``"/v1/{name=users/*}/operations"`` to
+ their service configuration. For backwards compatibility, the
+ default name includes the operations collection id, however
+ overriding users must ensure the name binding is the parent
+ resource, without the operations collection id.
+
+ Args:
+ name (str):
+ The name of the operation's parent
+ resource.
+ filter_ (str):
+ The standard list filter.
+ This corresponds to the ``filter`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ google.api_core.operations_v1.pagers.ListOperationsPager:
+ The response message for
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
+
+ Iterating over this object will yield results and
+ resolve additional pages automatically.
+
+ """
+ # Create a protobuf request object.
+ request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
+ if page_size is not None:
+ request.page_size = page_size
+ if page_token is not None:
+ request.page_token = page_token
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.list_operations]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__iter__` convenience method.
+ response = pagers.ListOperationsAsyncPager(
+ method=rpc,
+ request=request,
+ response=response,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def delete_operation(
+ self,
+ name: str,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes a long-running operation. This method indicates that the
+ client is no longer interested in the operation result. It does
+ not cancel the operation. If the server doesn't support this
+ method, it returns ``google.rpc.Code.UNIMPLEMENTED``.
+
+ Args:
+ name (str):
+ The name of the operation resource to
+ be deleted.
+
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create the request object.
+ request = operations_pb2.DeleteOperationRequest(name=name)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.delete_operation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ await rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ async def cancel_operation(
+ self,
+ name: Optional[str] = None,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Starts asynchronous cancellation on a long-running operation.
+ The server makes a best effort to cancel the operation, but
+ success is not guaranteed. If the server doesn't support this
+ method, it returns ``google.rpc.Code.UNIMPLEMENTED``. Clients
+ can use
+ [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation]
+ or other methods to check whether the cancellation succeeded or
+ whether the operation completed despite cancellation. On
+ successful cancellation, the operation is not deleted; instead,
+ it becomes an operation with an
+ [Operation.error][google.api_core.operations_v1.Operation.error] value with
+ a [google.rpc.Status.code][google.rpc.Status.code] of 1,
+ corresponding to ``Code.CANCELLED``.
+
+ Args:
+ name (str):
+ The name of the operation resource to
+ be cancelled.
+
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create the request object.
+ request = operations_pb2.CancelOperationRequest(name=name)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata or ()) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ await rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers.py
new file mode 100644
index 0000000000000000000000000000000000000000..76efd59469f92ced002987db28e9c5b8a5024765
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ Callable,
+ Iterator,
+ Sequence,
+ Tuple,
+)
+
+from google.longrunning import operations_pb2
+from google.api_core.operations_v1.pagers_base import ListOperationsPagerBase
+
+
+class ListOperationsPager(ListOperationsPagerBase):
+ """A pager for iterating through ``list_operations`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.longrunning.operations_pb2.ListOperationsResponse` object, and
+ provides an ``__iter__`` method to iterate through its
+ ``operations`` field.
+
+ If there are more pages, the ``__iter__`` method will make additional
+ ``ListOperations`` requests and continue to iterate
+ through the ``operations`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.longrunning.operations_pb2.ListOperationsResponse`
+ attributes are available on the pager. If multiple requests are made, only
+ the most recent response is retained, and thus used for attribute lookup.
+ """
+
+ def __init__(
+ self,
+ method: Callable[..., operations_pb2.ListOperationsResponse],
+ request: operations_pb2.ListOperationsRequest,
+ response: operations_pb2.ListOperationsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ):
+ super().__init__(
+ method=method, request=request, response=response, metadata=metadata
+ )
+
+ @property
+ def pages(self) -> Iterator[operations_pb2.ListOperationsResponse]:
+ yield self._response
+ while self._response.next_page_token:
+ self._request.page_token = self._response.next_page_token
+ self._response = self._method(self._request, metadata=self._metadata)
+ yield self._response
+
+ def __iter__(self) -> Iterator[operations_pb2.Operation]:
+ for page in self.pages:
+ yield from page.operations
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers_async.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers_async.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bb7f8c7d5dbe5317c23b2f24903fd3319f3dcef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers_async.py
@@ -0,0 +1,71 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ Callable,
+ AsyncIterator,
+ Sequence,
+ Tuple,
+)
+
+from google.longrunning import operations_pb2
+from google.api_core.operations_v1.pagers_base import ListOperationsPagerBase
+
+
+class ListOperationsAsyncPager(ListOperationsPagerBase):
+ """A pager for iterating through ``list_operations`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.longrunning.operations_pb2.ListOperationsResponse` object, and
+ provides an ``__iter__`` method to iterate through its
+ ``operations`` field.
+
+ If there are more pages, the ``__iter__`` method will make additional
+ ``ListOperations`` requests and continue to iterate
+ through the ``operations`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.longrunning.operations_pb2.ListOperationsResponse`
+ attributes are available on the pager. If multiple requests are made, only
+ the most recent response is retained, and thus used for attribute lookup.
+ """
+
+ def __init__(
+ self,
+ method: Callable[..., operations_pb2.ListOperationsResponse],
+ request: operations_pb2.ListOperationsRequest,
+ response: operations_pb2.ListOperationsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ):
+ super().__init__(
+ method=method, request=request, response=response, metadata=metadata
+ )
+
+ @property
+ async def pages(self) -> AsyncIterator[operations_pb2.ListOperationsResponse]:
+ yield self._response
+ while self._response.next_page_token:
+ self._request.page_token = self._response.next_page_token
+ self._response = await self._method(self._request, metadata=self._metadata)
+ yield self._response
+
+ def __aiter__(self) -> AsyncIterator[operations_pb2.Operation]:
+ async def async_generator():
+ async for page in self.pages:
+ for operation in page.operations:
+ yield operation
+
+ return async_generator()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers_base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ef8384efc5c1afa7b0474f63f30ae8d6dbe89c3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/pagers_base.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ Any,
+ Callable,
+ Sequence,
+ Tuple,
+)
+
+from google.longrunning import operations_pb2
+
+
+class ListOperationsPagerBase:
+ """A pager for iterating through ``list_operations`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.longrunning.operations_pb2.ListOperationsResponse` object, and
+ provides an ``__iter__`` method to iterate through its
+ ``operations`` field.
+
+ If there are more pages, the ``__iter__`` method will make additional
+ ``ListOperations`` requests and continue to iterate
+ through the ``operations`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.longrunning.operations_pb2.ListOperationsResponse`
+ attributes are available on the pager. If multiple requests are made, only
+ the most recent response is retained, and thus used for attribute lookup.
+ """
+
+ def __init__(
+ self,
+ method: Callable[..., operations_pb2.ListOperationsResponse],
+ request: operations_pb2.ListOperationsRequest,
+ response: operations_pb2.ListOperationsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (google.longrunning.operations_pb2.ListOperationsRequest):
+ The initial request object.
+ response (google.longrunning.operations_pb2.ListOperationsResponse):
+ The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ self._method = method
+ self._request = request
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c24ce6efa236a846f7315d1ef9febc6b1a27751
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__init__.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from collections import OrderedDict
+from typing import cast, Dict, Tuple
+
+from .base import OperationsTransport
+from .rest import OperationsRestTransport
+
+# Compile a registry of transports.
+_transport_registry: Dict[str, OperationsTransport] = OrderedDict()
+_transport_registry["rest"] = cast(OperationsTransport, OperationsRestTransport)
+
+__all__: Tuple[str, ...] = ("OperationsTransport", "OperationsRestTransport")
+
+try:
+ from .rest_asyncio import AsyncOperationsRestTransport
+
+ __all__ += ("AsyncOperationsRestTransport",)
+ _transport_registry["rest_asyncio"] = cast(
+ OperationsTransport, AsyncOperationsRestTransport
+ )
+except ImportError:
+ # This import requires the `async_rest` extra.
+ # Don't raise an exception if `AsyncOperationsRestTransport` cannot be imported
+ # as other transports are still available.
+ pass
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90dfa084b8fef73c82b98e6e726b596629786543
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29014e28921d97c0753ec3ad4c14afdeaa0f13b6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/base.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef1aa1e7adfc37f9a8d80a01ed0b6939449149a9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest_asyncio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest_asyncio.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d04d4edb63120cf91ac00ce98786c968c14eb08
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest_asyncio.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d78809b15da2b26c60c01d19fa4102a9c7682ad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/base.py
@@ -0,0 +1,303 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import abc
+import re
+from typing import Awaitable, Callable, Optional, Sequence, Union
+import warnings
+
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account # type: ignore
+import google.protobuf
+from google.protobuf import empty_pb2, json_format # type: ignore
+from grpc import Compression
+
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import general_helpers
+from google.api_core import retry as retries # type: ignore
+from google.api_core import version
+
+PROTOBUF_VERSION = google.protobuf.__version__
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=version.__version__,
+)
+
+
+class OperationsTransport(abc.ABC):
+ """Abstract transport class for Operations."""
+
+ AUTH_SCOPES = ()
+
+ DEFAULT_HOST: str = "longrunning.googleapis.com"
+
+ def __init__(
+ self,
+ *,
+ host: str = DEFAULT_HOST,
+ # TODO(https://github.com/googleapis/python-api-core/issues/709): update type hint for credentials to include `google.auth.aio.Credentials`.
+ credentials: Optional[ga_credentials.Credentials] = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
+ url_scheme="https",
+ **kwargs,
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]):
+ The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ credentials_file (Optional[str]): Deprecated. A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials. This argument will be
+ removed in the next major version of `google-api-core`.
+
+ .. warning::
+ Important: If you accept a credential configuration (credential JSON/File/Stream)
+ from an external source for authentication to Google Cloud Platform, you must
+ validate it before providing it to any Google API or client library. Providing an
+ unvalidated credential configuration to Google APIs or libraries can compromise
+ the security of your systems and data. For more information, refer to
+ `Validate credential configurations from external sources`_.
+
+ .. _Validate credential configurations from external sources:
+
+ https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
+ scopes (Optional[Sequence[str]]): A list of scopes.
+ quota_project_id (Optional[str]): An optional project to use for billing
+ and quota.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
+ url_scheme: the protocol scheme for the API endpoint. Normally
+ "https", but for testing or local servers,
+ "http" can be specified.
+ """
+ if credentials_file is not None:
+ warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)
+
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
+ # Save the hostname. Default to port 443 (HTTPS) if none is specified.
+ if ":" not in host:
+ host += ":443" # pragma: NO COVER
+ self._host = host
+
+ # Save the scopes.
+ self._scopes = scopes
+
+ # If no credentials are provided, then determine the appropriate
+ # defaults.
+ if credentials and credentials_file:
+ raise core_exceptions.DuplicateCredentialArgs(
+ "'credentials_file' and 'credentials' are mutually exclusive"
+ )
+
+ if credentials_file is not None:
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ default_scopes=self.AUTH_SCOPES,
+ )
+
+ elif credentials is None:
+ credentials, _ = google.auth.default(
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ default_scopes=self.AUTH_SCOPES,
+ )
+
+ # If the credentials are service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
+ # Save the credentials.
+ self._credentials = credentials
+
+ def _prep_wrapped_messages(self, client_info):
+ # Precompute the wrapped methods.
+ self._wrapped_methods = {
+ self.list_operations: gapic_v1.method.wrap_method(
+ self.list_operations,
+ default_retry=retries.Retry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ default_compression=Compression.NoCompression,
+ client_info=client_info,
+ ),
+ self.get_operation: gapic_v1.method.wrap_method(
+ self.get_operation,
+ default_retry=retries.Retry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ default_compression=Compression.NoCompression,
+ client_info=client_info,
+ ),
+ self.delete_operation: gapic_v1.method.wrap_method(
+ self.delete_operation,
+ default_retry=retries.Retry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ default_compression=Compression.NoCompression,
+ client_info=client_info,
+ ),
+ self.cancel_operation: gapic_v1.method.wrap_method(
+ self.cancel_operation,
+ default_retry=retries.Retry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ default_compression=Compression.NoCompression,
+ client_info=client_info,
+ ),
+ }
+
+ def close(self):
+ """Closes resources associated with the transport.
+
+ .. warning::
+ Only call this method if the transport is NOT shared
+ with other clients - this may cause errors in other clients!
+ """
+ raise NotImplementedError()
+
+ def _convert_protobuf_message_to_dict(
+ self, message: google.protobuf.message.Message
+ ):
+ r"""Converts protobuf message to a dictionary.
+
+ When the dictionary is encoded to JSON, it conforms to proto3 JSON spec.
+
+ Args:
+ message(google.protobuf.message.Message): The protocol buffers message
+ instance to serialize.
+
+ Returns:
+ A dict representation of the protocol buffer message.
+ """
+ # TODO(https://github.com/googleapis/python-api-core/issues/643): For backwards compatibility
+ # with protobuf 3.x 4.x, Remove once support for protobuf 3.x and 4.x is dropped.
+ if PROTOBUF_VERSION[0:2] in ["3.", "4."]:
+ result = json_format.MessageToDict(
+ message,
+ preserving_proto_field_name=True,
+ including_default_value_fields=True, # type: ignore # backward compatibility
+ )
+ else:
+ result = json_format.MessageToDict(
+ message,
+ preserving_proto_field_name=True,
+ always_print_fields_with_no_presence=True,
+ )
+
+ return result
+
+ @property
+ def list_operations(
+ self,
+ ) -> Callable[
+ [operations_pb2.ListOperationsRequest],
+ Union[
+ operations_pb2.ListOperationsResponse,
+ Awaitable[operations_pb2.ListOperationsResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def get_operation(
+ self,
+ ) -> Callable[
+ [operations_pb2.GetOperationRequest],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def delete_operation(
+ self,
+ ) -> Callable[
+ [operations_pb2.DeleteOperationRequest],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def cancel_operation(
+ self,
+ ) -> Callable[
+ [operations_pb2.CancelOperationRequest],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
+ ]:
+ raise NotImplementedError()
+
+
+__all__ = ("OperationsTransport",)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest.py
new file mode 100644
index 0000000000000000000000000000000000000000..62f34d69f0bcc7fdf0fc4203153d14b642b64aff
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest.py
@@ -0,0 +1,492 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
+import warnings
+
+from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.requests import AuthorizedSession # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+import google.protobuf
+from google.protobuf import empty_pb2 # type: ignore
+from google.protobuf import json_format # type: ignore
+import grpc
+from requests import __version__ as requests_version
+
+from google.api_core import exceptions as core_exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import general_helpers
+from google.api_core import path_template # type: ignore
+from google.api_core import rest_helpers # type: ignore
+from google.api_core import retry as retries # type: ignore
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import OperationsTransport
+
+PROTOBUF_VERSION = google.protobuf.__version__
+
+OptionalRetry = Union[retries.Retry, object]
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
+ grpc_version=None,
+ rest_version=f"requests@{requests_version}",
+)
+
+
+class OperationsRestTransport(OperationsTransport):
+ """REST backend transport for Operations.
+
+ Manages long-running operations with an API service.
+
+ When an API method normally takes long time to complete, it can be
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
+ client, and the client can use this interface to receive the real
+ response asynchronously by polling the operation resource, or pass
+ the operation resource to another API (such as Google Cloud Pub/Sub
+ API) to receive the response. Any API service that returns
+ long-running operations should implement the ``Operations``
+ interface so developers can have a consistent client experience.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends JSON representations of protocol buffers over HTTP/1.1
+ """
+
+ def __init__(
+ self,
+ *,
+ host: str = "longrunning.googleapis.com",
+ credentials: Optional[ga_credentials.Credentials] = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
+ quota_project_id: Optional[str] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
+ url_scheme: str = "https",
+ http_options: Optional[Dict] = None,
+ path_prefix: str = "v1",
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]):
+ The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+
+ credentials_file (Optional[str]): Deprecated. A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided. This argument will be
+ removed in the next major version of `google-api-core`.
+
+ .. warning::
+ Important: If you accept a credential configuration (credential JSON/File/Stream)
+ from an external source for authentication to Google Cloud Platform, you must
+ validate it before providing it to any Google API or client library. Providing an
+ unvalidated credential configuration to Google APIs or libraries can compromise
+ the security of your systems and data. For more information, refer to
+ `Validate credential configuration from external sources`_.
+
+ .. _Validate credential configuration from external sources:
+
+ https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
+ ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
+ certificate to configure mutual TLS HTTP channel. It is ignored
+ if ``channel`` is provided.
+ quota_project_id (Optional[str]): An optional project to use for billing
+ and quota.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
+ url_scheme: the protocol scheme for the API endpoint. Normally
+ "https", but for testing or local servers,
+ "http" can be specified.
+ http_options: a dictionary of http_options for transcoding, to override
+ the defaults from operations.proto. Each method has an entry
+ with the corresponding http rules as value.
+ path_prefix: path prefix (usually represents API version). Set to
+ "v1" by default.
+
+ """
+ if credentials_file is not None:
+ warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)
+
+ # Run the base constructor
+ # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
+ # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
+ # credentials object
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
+ self._session = AuthorizedSession(
+ self._credentials, default_host=self.DEFAULT_HOST
+ )
+ if client_cert_source_for_mtls:
+ self._session.configure_mtls_channel(client_cert_source_for_mtls)
+ # TODO(https://github.com/googleapis/python-api-core/issues/720): Add wrap logic directly to the property methods for callables.
+ self._prep_wrapped_messages(client_info)
+ self._http_options = http_options or {}
+ self._path_prefix = path_prefix
+
+ def _list_operations(
+ self,
+ request: operations_pb2.ListOperationsRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operations_pb2.ListOperationsResponse:
+ r"""Call the list operations method over HTTP.
+
+ Args:
+ request (~.operations_pb2.ListOperationsRequest):
+ The request object. The request message for
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operations_pb2.ListOperationsResponse:
+ The response message for
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
+
+ """
+
+ http_options = [
+ {
+ "method": "get",
+ "uri": "/{}/{{name=**}}/operations".format(self._path_prefix),
+ },
+ ]
+ if "google.longrunning.Operations.ListOperations" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.ListOperations"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.ListOperationsRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ )
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ raise core_exceptions.from_http_response(response)
+
+ # Return the response
+ api_response = operations_pb2.ListOperationsResponse()
+ json_format.Parse(response.content, api_response, ignore_unknown_fields=False)
+ return api_response
+
+ def _get_operation(
+ self,
+ request: operations_pb2.GetOperationRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operations_pb2.Operation:
+ r"""Call the get operation method over HTTP.
+
+ Args:
+ request (~.operations_pb2.GetOperationRequest):
+ The request object. The request message for
+ [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation].
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operations_pb2.Operation:
+ This resource represents a long-
+ running operation that is the result of a
+ network API call.
+
+ """
+
+ http_options = [
+ {
+ "method": "get",
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
+ },
+ ]
+ if "google.longrunning.Operations.GetOperation" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.GetOperation"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.GetOperationRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ )
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ raise core_exceptions.from_http_response(response)
+
+ # Return the response
+ api_response = operations_pb2.Operation()
+ json_format.Parse(response.content, api_response, ignore_unknown_fields=False)
+ return api_response
+
+ def _delete_operation(
+ self,
+ request: operations_pb2.DeleteOperationRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> empty_pb2.Empty:
+ r"""Call the delete operation method over HTTP.
+
+ Args:
+ request (~.operations_pb2.DeleteOperationRequest):
+ The request object. The request message for
+ [Operations.DeleteOperation][google.api_core.operations_v1.Operations.DeleteOperation].
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+
+ http_options = [
+ {
+ "method": "delete",
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
+ },
+ ]
+ if "google.longrunning.Operations.DeleteOperation" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.DeleteOperation"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.DeleteOperationRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ )
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ raise core_exceptions.from_http_response(response)
+
+ return empty_pb2.Empty()
+
+ def _cancel_operation(
+ self,
+ request: operations_pb2.CancelOperationRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> empty_pb2.Empty:
+ r"""Call the cancel operation method over HTTP.
+
+ Args:
+ request (~.operations_pb2.CancelOperationRequest):
+ The request object. The request message for
+ [Operations.CancelOperation][google.api_core.operations_v1.Operations.CancelOperation].
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+
+ http_options = [
+ {
+ "method": "post",
+ "uri": "/{}/{{name=**/operations/*}}:cancel".format(self._path_prefix),
+ "body": "*",
+ },
+ ]
+ if "google.longrunning.Operations.CancelOperation" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.CancelOperation"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ # Jsonify the request body
+ body_request = operations_pb2.CancelOperationRequest()
+ json_format.ParseDict(transcoded_request["body"], body_request)
+ body = json_format.MessageToDict(
+ body_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.CancelOperationRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ data=body,
+ )
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ raise core_exceptions.from_http_response(response)
+
+ return empty_pb2.Empty()
+
+ @property
+ def list_operations(
+ self,
+ ) -> Callable[
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
+ ]:
+ return self._list_operations
+
+ @property
+ def get_operation(
+ self,
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
+ return self._get_operation
+
+ @property
+ def delete_operation(
+ self,
+ ) -> Callable[[operations_pb2.DeleteOperationRequest], empty_pb2.Empty]:
+ return self._delete_operation
+
+ @property
+ def cancel_operation(
+ self,
+ ) -> Callable[[operations_pb2.CancelOperationRequest], empty_pb2.Empty]:
+ return self._cancel_operation
+
+
+__all__ = ("OperationsRestTransport",)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest_asyncio.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest_asyncio.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fa9f56aa0cfe99ef56b26d21ca68a484b85d298
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest_asyncio.py
@@ -0,0 +1,581 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import json
+from typing import Any, Callable, Coroutine, Dict, Optional, Sequence, Tuple
+import warnings
+
+from google.auth import __version__ as auth_version
+
+try:
+ from google.auth.aio.transport.sessions import AsyncAuthorizedSession # type: ignore
+except ImportError as e: # pragma: NO COVER
+ raise ImportError(
+ "The `async_rest` extra of `google-api-core` is required to use long-running operations. Install it by running "
+ "`pip install google-api-core[async_rest]`."
+ ) from e
+
+from google.api_core import exceptions as core_exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import general_helpers
+from google.api_core import path_template # type: ignore
+from google.api_core import rest_helpers # type: ignore
+from google.api_core import retry_async as retries_async # type: ignore
+from google.auth.aio import credentials as ga_credentials_async # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+from google.protobuf import json_format # type: ignore
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, OperationsTransport
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
+ grpc_version=None,
+ rest_version=f"google-auth@{auth_version}",
+)
+
+
+class AsyncOperationsRestTransport(OperationsTransport):
+ """Asynchronous REST backend transport for Operations.
+
+ Manages async long-running operations with an API service.
+
+ When an API method normally takes long time to complete, it can be
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
+ client, and the client can use this interface to receive the real
+ response asynchronously by polling the operation resource, or pass
+ the operation resource to another API (such as Google Cloud Pub/Sub
+ API) to receive the response. Any API service that returns
+ long-running operations should implement the ``Operations``
+ interface so developers can have a consistent client experience.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends JSON representations of protocol buffers over HTTP/1.1
+ """
+
+ def __init__(
+ self,
+ *,
+ host: str = "longrunning.googleapis.com",
+ credentials: Optional[ga_credentials_async.Credentials] = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
+ quota_project_id: Optional[str] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
+ url_scheme: str = "https",
+ http_options: Optional[Dict] = None,
+ path_prefix: str = "v1",
+ # TODO(https://github.com/googleapis/python-api-core/issues/715): Add docstring for `credentials_file` to async REST transport.
+ # TODO(https://github.com/googleapis/python-api-core/issues/716): Add docstring for `scopes` to async REST transport.
+ # TODO(https://github.com/googleapis/python-api-core/issues/717): Add docstring for `quota_project_id` to async REST transport.
+ # TODO(https://github.com/googleapis/python-api-core/issues/718): Add docstring for `client_cert_source` to async REST transport.
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]):
+ The hostname to connect to.
+ credentials (Optional[google.auth.aio.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ credentials_file (Optional[str]): Deprecated. A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided. This argument will be
+ removed in the next major version of `google-api-core`.
+
+ .. warning::
+ Important: If you accept a credential configuration (credential JSON/File/Stream)
+ from an external source for authentication to Google Cloud Platform, you must
+ validate it before providing it to any Google API or client library. Providing an
+ unvalidated credential configuration to Google APIs or libraries can compromise
+ the security of your systems and data. For more information, refer to
+ `Validate credential configurations from external sources`_.
+
+ .. _Validate credential configurations from external sources:
+
+ https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
+ url_scheme: the protocol scheme for the API endpoint. Normally
+ "https", but for testing or local servers,
+ "http" can be specified.
+ http_options: a dictionary of http_options for transcoding, to override
+ the defaults from operations.proto. Each method has an entry
+ with the corresponding http rules as value.
+ path_prefix: path prefix (usually represents API version). Set to
+ "v1" by default.
+
+ """
+ if credentials_file is not None:
+ warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)
+
+ unsupported_params = {
+ # TODO(https://github.com/googleapis/python-api-core/issues/715): Add support for `credentials_file` to async REST transport.
+ "google.api_core.client_options.ClientOptions.credentials_file": credentials_file,
+ # TODO(https://github.com/googleapis/python-api-core/issues/716): Add support for `scopes` to async REST transport.
+ "google.api_core.client_options.ClientOptions.scopes": scopes,
+ # TODO(https://github.com/googleapis/python-api-core/issues/717): Add support for `quota_project_id` to async REST transport.
+ "google.api_core.client_options.ClientOptions.quota_project_id": quota_project_id,
+ # TODO(https://github.com/googleapis/python-api-core/issues/718): Add support for `client_cert_source` to async REST transport.
+ "google.api_core.client_options.ClientOptions.client_cert_source": client_cert_source_for_mtls,
+ # TODO(https://github.com/googleapis/python-api-core/issues/718): Add support for `client_cert_source` to async REST transport.
+ "google.api_core.client_options.ClientOptions.client_cert_source": client_cert_source_for_mtls,
+ }
+ provided_unsupported_params = [
+ name for name, value in unsupported_params.items() if value is not None
+ ]
+ if provided_unsupported_params:
+ raise core_exceptions.AsyncRestUnsupportedParameterError(
+ f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}"
+ )
+
+ super().__init__(
+ host=host,
+ # TODO(https://github.com/googleapis/python-api-core/issues/709): Remove `type: ignore` when the linked issue is resolved.
+ credentials=credentials, # type: ignore
+ client_info=client_info,
+ # TODO(https://github.com/googleapis/python-api-core/issues/725): Set always_use_jwt_access token when supported.
+ always_use_jwt_access=False,
+ )
+ # TODO(https://github.com/googleapis/python-api-core/issues/708): add support for
+ # `default_host` in AsyncAuthorizedSession for feature parity with the synchronous
+ # code.
+ # TODO(https://github.com/googleapis/python-api-core/issues/709): Remove `type: ignore` when the linked issue is resolved.
+ self._session = AsyncAuthorizedSession(self._credentials) # type: ignore
+ # TODO(https://github.com/googleapis/python-api-core/issues/720): Add wrap logic directly to the property methods for callables.
+ self._prep_wrapped_messages(client_info)
+ self._http_options = http_options or {}
+ self._path_prefix = path_prefix
+
+ def _prep_wrapped_messages(self, client_info):
+ # Precompute the wrapped methods.
+ self._wrapped_methods = {
+ self.list_operations: gapic_v1.method_async.wrap_method(
+ self.list_operations,
+ default_retry=retries_async.AsyncRetry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries_async.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ kind="rest_asyncio",
+ ),
+ self.get_operation: gapic_v1.method_async.wrap_method(
+ self.get_operation,
+ default_retry=retries_async.AsyncRetry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries_async.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ kind="rest_asyncio",
+ ),
+ self.delete_operation: gapic_v1.method_async.wrap_method(
+ self.delete_operation,
+ default_retry=retries_async.AsyncRetry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries_async.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ kind="rest_asyncio",
+ ),
+ self.cancel_operation: gapic_v1.method_async.wrap_method(
+ self.cancel_operation,
+ default_retry=retries_async.AsyncRetry(
+ initial=0.5,
+ maximum=10.0,
+ multiplier=2.0,
+ predicate=retries_async.if_exception_type(
+ core_exceptions.ServiceUnavailable,
+ ),
+ deadline=10.0,
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ kind="rest_asyncio",
+ ),
+ }
+
+ async def _list_operations(
+ self,
+ request: operations_pb2.ListOperationsRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operations_pb2.ListOperationsResponse:
+ r"""Asynchronously call the list operations method over HTTP.
+
+ Args:
+ request (~.operations_pb2.ListOperationsRequest):
+ The request object. The request message for
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operations_pb2.ListOperationsResponse:
+ The response message for
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
+
+ """
+
+ http_options = [
+ {
+ "method": "get",
+ "uri": "/{}/{{name=**}}/operations".format(self._path_prefix),
+ },
+ ]
+ if "google.longrunning.Operations.ListOperations" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.ListOperations"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.ListOperationsRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = await getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ )
+ content = await response.read()
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ payload = json.loads(content.decode("utf-8"))
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
+
+ # Return the response
+ api_response = operations_pb2.ListOperationsResponse()
+ json_format.Parse(content, api_response, ignore_unknown_fields=False)
+ return api_response
+
+ async def _get_operation(
+ self,
+ request: operations_pb2.GetOperationRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operations_pb2.Operation:
+ r"""Asynchronously call the get operation method over HTTP.
+
+ Args:
+ request (~.operations_pb2.GetOperationRequest):
+ The request object. The request message for
+ [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation].
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operations_pb2.Operation:
+ This resource represents a long-
+ running operation that is the result of a
+ network API call.
+
+ """
+
+ http_options = [
+ {
+ "method": "get",
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
+ },
+ ]
+ if "google.longrunning.Operations.GetOperation" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.GetOperation"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.GetOperationRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = await getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ )
+ content = await response.read()
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ payload = json.loads(content.decode("utf-8"))
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
+
+ # Return the response
+ api_response = operations_pb2.Operation()
+ json_format.Parse(content, api_response, ignore_unknown_fields=False)
+ return api_response
+
+ async def _delete_operation(
+ self,
+ request: operations_pb2.DeleteOperationRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> empty_pb2.Empty:
+ r"""Asynchronously call the delete operation method over HTTP.
+
+ Args:
+ request (~.operations_pb2.DeleteOperationRequest):
+ The request object. The request message for
+ [Operations.DeleteOperation][google.api_core.operations_v1.Operations.DeleteOperation].
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+
+ http_options = [
+ {
+ "method": "delete",
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
+ },
+ ]
+ if "google.longrunning.Operations.DeleteOperation" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.DeleteOperation"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.DeleteOperationRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = await getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ )
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ content = await response.read()
+ payload = json.loads(content.decode("utf-8"))
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
+
+ return empty_pb2.Empty()
+
+ async def _cancel_operation(
+ self,
+ request: operations_pb2.CancelOperationRequest,
+ *,
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
+ # to allow configuring retryable error codes.
+ retry=gapic_v1.method_async.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Add `retry` parameter
+ # to allow configuring retryable error codes.
+ ) -> empty_pb2.Empty:
+ r"""Asynchronously call the cancel operation method over HTTP.
+
+ Args:
+ request (~.operations_pb2.CancelOperationRequest):
+ The request object. The request message for
+ [Operations.CancelOperation][google.api_core.operations_v1.Operations.CancelOperation].
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+
+ http_options = [
+ {
+ "method": "post",
+ "uri": "/{}/{{name=**/operations/*}}:cancel".format(self._path_prefix),
+ "body": "*",
+ },
+ ]
+ if "google.longrunning.Operations.CancelOperation" in self._http_options:
+ http_options = self._http_options[
+ "google.longrunning.Operations.CancelOperation"
+ ]
+
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ # Jsonify the request body
+ body_request = operations_pb2.CancelOperationRequest()
+ json_format.ParseDict(transcoded_request["body"], body_request)
+ body = json_format.MessageToDict(
+ body_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
+
+ # Jsonify the query params
+ query_params_request = operations_pb2.CancelOperationRequest()
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
+ query_params = json_format.MessageToDict(
+ query_params_request,
+ preserving_proto_field_name=False,
+ use_integers_for_enums=False,
+ )
+
+ # Send the request
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
+ response = await getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
+ data=body,
+ )
+
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
+ # subclass.
+ if response.status_code >= 400:
+ content = await response.read()
+ payload = json.loads(content.decode("utf-8"))
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
+
+ return empty_pb2.Empty()
+
+ @property
+ def list_operations(
+ self,
+ ) -> Callable[
+ [operations_pb2.ListOperationsRequest],
+ Coroutine[Any, Any, operations_pb2.ListOperationsResponse],
+ ]:
+ return self._list_operations
+
+ @property
+ def get_operation(
+ self,
+ ) -> Callable[
+ [operations_pb2.GetOperationRequest],
+ Coroutine[Any, Any, operations_pb2.Operation],
+ ]:
+ return self._get_operation
+
+ @property
+ def delete_operation(
+ self,
+ ) -> Callable[
+ [operations_pb2.DeleteOperationRequest], Coroutine[Any, Any, empty_pb2.Empty]
+ ]:
+ return self._delete_operation
+
+ @property
+ def cancel_operation(
+ self,
+ ) -> Callable[
+ [operations_pb2.CancelOperationRequest], Coroutine[Any, Any, empty_pb2.Empty]
+ ]:
+ return self._cancel_operation
+
+
+__all__ = ("AsyncOperationsRestTransport",)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1724fdbd96597bf8e80a1059ae9b94353dbe69d8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__init__.py
@@ -0,0 +1,52 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Retry implementation for Google API client libraries."""
+
+from .retry_base import exponential_sleep_generator
+from .retry_base import if_exception_type
+from .retry_base import if_transient_error
+from .retry_base import build_retry_error
+from .retry_base import RetryFailureReason
+from .retry_unary import Retry
+from .retry_unary import retry_target
+from .retry_unary_async import AsyncRetry
+from .retry_unary_async import retry_target as retry_target_async
+from .retry_streaming import StreamingRetry
+from .retry_streaming import retry_target_stream
+from .retry_streaming_async import AsyncStreamingRetry
+from .retry_streaming_async import retry_target_stream as retry_target_stream_async
+
+# The following imports are for backwards compatibility with https://github.com/googleapis/python-api-core/blob/4d7d2edee2c108d43deb151e6e0fdceb56b73275/google/api_core/retry.py
+#
+# TODO: Revert these imports on the next major version release (https://github.com/googleapis/python-api-core/issues/576)
+from google.api_core import datetime_helpers # noqa: F401
+from google.api_core import exceptions # noqa: F401
+from google.auth import exceptions as auth_exceptions # noqa: F401
+
+__all__ = (
+ "exponential_sleep_generator",
+ "if_exception_type",
+ "if_transient_error",
+ "build_retry_error",
+ "RetryFailureReason",
+ "Retry",
+ "AsyncRetry",
+ "StreamingRetry",
+ "AsyncStreamingRetry",
+ "retry_target",
+ "retry_target_async",
+ "retry_target_stream",
+ "retry_target_stream_async",
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47ee68b253cac9937c27cecb0ee16a7149a5fcfb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9146291ee09e02fc5eb82b1097a69f619879a46
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_base.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_streaming.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_streaming.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d53d93d9d93ee9999f8dceae92ffc7d398c4ad9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_streaming.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_streaming_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_streaming_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..def8fec904c1b053d527947a02533670e1f44166
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_streaming_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_unary.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_unary.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..faa66fc20e2b9442e11e351810d5c431c618f42f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_unary.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_unary_async.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_unary_async.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b25fe5f573259cea57ec84e44725cfbb83c496b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/__pycache__/retry_unary_async.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dd975ed7a0b8302eaaaeaa93bbd79aef9f4aa1b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_base.py
@@ -0,0 +1,372 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Shared classes and functions for retrying requests.
+
+:class:`_BaseRetry` is the base class for :class:`Retry`,
+:class:`AsyncRetry`, :class:`StreamingRetry`, and :class:`AsyncStreamingRetry`.
+"""
+
+from __future__ import annotations
+
+import logging
+import random
+import time
+
+from enum import Enum
+from typing import Any, Callable, Optional, Iterator, TYPE_CHECKING
+
+import requests.exceptions
+
+from google.api_core import exceptions
+from google.auth import exceptions as auth_exceptions
+
+if TYPE_CHECKING:
+ import sys
+
+ if sys.version_info >= (3, 11):
+ from typing import Self
+ else:
+ from typing_extensions import Self
+
+_DEFAULT_INITIAL_DELAY = 1.0 # seconds
+_DEFAULT_MAXIMUM_DELAY = 60.0 # seconds
+_DEFAULT_DELAY_MULTIPLIER = 2.0
+_DEFAULT_DEADLINE = 60.0 * 2.0 # seconds
+
+_LOGGER = logging.getLogger("google.api_core.retry")
+
+
+def if_exception_type(
+ *exception_types: type[Exception],
+) -> Callable[[Exception], bool]:
+ """Creates a predicate to check if the exception is of a given type.
+
+ Args:
+ exception_types (Sequence[:func:`type`]): The exception types to check
+ for.
+
+ Returns:
+ Callable[Exception]: A predicate that returns True if the provided
+ exception is of the given type(s).
+ """
+
+ def if_exception_type_predicate(exception: Exception) -> bool:
+ """Bound predicate for checking an exception type."""
+ return isinstance(exception, exception_types)
+
+ return if_exception_type_predicate
+
+
+# pylint: disable=invalid-name
+# Pylint sees this as a constant, but it is also an alias that should be
+# considered a function.
+if_transient_error = if_exception_type(
+ exceptions.InternalServerError,
+ exceptions.TooManyRequests,
+ exceptions.ServiceUnavailable,
+ requests.exceptions.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ auth_exceptions.TransportError,
+)
+"""A predicate that checks if an exception is a transient API error.
+
+The following server errors are considered transient:
+
+- :class:`google.api_core.exceptions.InternalServerError` - HTTP 500, gRPC
+ ``INTERNAL(13)`` and its subclasses.
+- :class:`google.api_core.exceptions.TooManyRequests` - HTTP 429
+- :class:`google.api_core.exceptions.ServiceUnavailable` - HTTP 503
+- :class:`requests.exceptions.ConnectionError`
+- :class:`requests.exceptions.ChunkedEncodingError` - The server declared
+ chunked encoding but sent an invalid chunk.
+- :class:`google.auth.exceptions.TransportError` - Used to indicate an
+ error occurred during an HTTP request.
+"""
+# pylint: enable=invalid-name
+
+
+def exponential_sleep_generator(
+ initial: float, maximum: float, multiplier: float = _DEFAULT_DELAY_MULTIPLIER
+):
+ """Generates sleep intervals based on the exponential back-off algorithm.
+
+ This implements the `Truncated Exponential Back-off`_ algorithm.
+
+ .. _Truncated Exponential Back-off:
+ https://cloud.google.com/storage/docs/exponential-backoff
+
+ Args:
+ initial (float): The minimum amount of time to delay. This must
+ be greater than 0.
+ maximum (float): The maximum amount of time to delay.
+ multiplier (float): The multiplier applied to the delay.
+
+ Yields:
+ float: successive sleep intervals.
+ """
+ max_delay = min(initial, maximum)
+ while True:
+ yield random.uniform(0.0, max_delay)
+ max_delay = min(max_delay * multiplier, maximum)
+
+
+class RetryFailureReason(Enum):
+ """
+ The cause of a failed retry, used when building exceptions
+ """
+
+ TIMEOUT = 0
+ NON_RETRYABLE_ERROR = 1
+
+
+def build_retry_error(
+ exc_list: list[Exception],
+ reason: RetryFailureReason,
+ timeout_val: float | None,
+ **kwargs: Any,
+) -> tuple[Exception, Exception | None]:
+ """
+ Default exception_factory implementation.
+
+ Returns a RetryError if the failure is due to a timeout, otherwise
+ returns the last exception encountered.
+
+ Args:
+ - exc_list: list of exceptions that occurred during the retry
+ - reason: reason for the retry failure.
+ Can be TIMEOUT or NON_RETRYABLE_ERROR
+ - timeout_val: the original timeout value for the retry (in seconds), for use in the exception message
+
+ Returns:
+ - tuple: a tuple of the exception to be raised, and the cause exception if any
+ """
+ if reason == RetryFailureReason.TIMEOUT:
+ # return RetryError with the most recent exception as the cause
+ src_exc = exc_list[-1] if exc_list else None
+ timeout_val_str = f"of {timeout_val:0.1f}s " if timeout_val is not None else ""
+ return (
+ exceptions.RetryError(
+ f"Timeout {timeout_val_str}exceeded",
+ src_exc,
+ ),
+ src_exc,
+ )
+ elif exc_list:
+ # return most recent exception encountered and its cause
+ final_exc = exc_list[-1]
+ cause = getattr(final_exc, "__cause__", None)
+ return final_exc, cause
+ else:
+ # no exceptions were given in exc_list. Raise generic RetryError
+ return exceptions.RetryError("Unknown error", None), None
+
+
+def _retry_error_helper(
+ exc: Exception,
+ deadline: float | None,
+ sleep_iterator: Iterator[float],
+ error_list: list[Exception],
+ predicate_fn: Callable[[Exception], bool],
+ on_error_fn: Callable[[Exception], None] | None,
+ exc_factory_fn: Callable[
+ [list[Exception], RetryFailureReason, float | None],
+ tuple[Exception, Exception | None],
+ ],
+ original_timeout: float | None,
+) -> float:
+ """
+ Shared logic for handling an error for all retry implementations
+
+ - Raises an error on timeout or non-retryable error
+ - Calls on_error_fn if provided
+ - Logs the error
+
+ Args:
+ - exc: the exception that was raised
+ - deadline: the deadline for the retry, calculated as a diff from time.monotonic()
+ - sleep_iterator: iterator to draw the next backoff value from
+ - error_list: the list of exceptions that have been raised so far
+ - predicate_fn: takes `exc` and returns true if the operation should be retried
+ - on_error_fn: callback to execute when a retryable error occurs
+ - exc_factory_fn: callback used to build the exception to be raised on terminal failure
+ - original_timeout_val: the original timeout value for the retry (in seconds),
+ to be passed to the exception factory for building an error message
+ Returns:
+ - the sleep value chosen before the next attempt
+ """
+ error_list.append(exc)
+ if not predicate_fn(exc):
+ final_exc, source_exc = exc_factory_fn(
+ error_list,
+ RetryFailureReason.NON_RETRYABLE_ERROR,
+ original_timeout,
+ )
+ raise final_exc from source_exc
+ if on_error_fn is not None:
+ on_error_fn(exc)
+ # next_sleep is fetched after the on_error callback, to allow clients
+ # to update sleep_iterator values dynamically in response to errors
+ try:
+ next_sleep = next(sleep_iterator)
+ except StopIteration:
+ raise ValueError("Sleep generator stopped yielding sleep values.") from exc
+ if deadline is not None and time.monotonic() + next_sleep > deadline:
+ final_exc, source_exc = exc_factory_fn(
+ error_list,
+ RetryFailureReason.TIMEOUT,
+ original_timeout,
+ )
+ raise final_exc from source_exc
+ _LOGGER.debug(
+ "Retrying due to {}, sleeping {:.1f}s ...".format(error_list[-1], next_sleep)
+ )
+ return next_sleep
+
+
+class _BaseRetry(object):
+ """
+ Base class for retry configuration objects. This class is intended to capture retry
+ and backoff configuration that is common to both synchronous and asynchronous retries,
+ for both unary and streaming RPCs. It is not intended to be instantiated directly,
+ but rather to be subclassed by the various retry configuration classes.
+ """
+
+ def __init__(
+ self,
+ predicate: Callable[[Exception], bool] = if_transient_error,
+ initial: float = _DEFAULT_INITIAL_DELAY,
+ maximum: float = _DEFAULT_MAXIMUM_DELAY,
+ multiplier: float = _DEFAULT_DELAY_MULTIPLIER,
+ timeout: Optional[float] = _DEFAULT_DEADLINE,
+ on_error: Optional[Callable[[Exception], Any]] = None,
+ **kwargs: Any,
+ ) -> None:
+ self._predicate = predicate
+ self._initial = initial
+ self._multiplier = multiplier
+ self._maximum = maximum
+ self._timeout = kwargs.get("deadline", timeout)
+ self._deadline = self._timeout
+ self._on_error = on_error
+
+ def __call__(self, *args, **kwargs) -> Any:
+ raise NotImplementedError("Not implemented in base class")
+
+ @property
+ def deadline(self) -> float | None:
+ """
+ DEPRECATED: use ``timeout`` instead. Refer to the ``Retry`` class
+ documentation for details.
+ """
+ return self._timeout
+
+ @property
+ def timeout(self) -> float | None:
+ return self._timeout
+
+ def with_deadline(self, deadline: float | None) -> Self:
+ """Return a copy of this retry with the given timeout.
+
+ DEPRECATED: use :meth:`with_timeout` instead. Refer to the ``Retry`` class
+ documentation for details.
+
+ Args:
+ deadline (float|None): How long to keep retrying, in seconds. If None,
+ no timeout is enforced.
+
+ Returns:
+ Retry: A new retry instance with the given timeout.
+ """
+ return self.with_timeout(deadline)
+
+ def with_timeout(self, timeout: float | None) -> Self:
+ """Return a copy of this retry with the given timeout.
+
+ Args:
+ timeout (float): How long to keep retrying, in seconds. If None,
+ no timeout will be enforced.
+
+ Returns:
+ Retry: A new retry instance with the given timeout.
+ """
+ return type(self)(
+ predicate=self._predicate,
+ initial=self._initial,
+ maximum=self._maximum,
+ multiplier=self._multiplier,
+ timeout=timeout,
+ on_error=self._on_error,
+ )
+
+ def with_predicate(self, predicate: Callable[[Exception], bool]) -> Self:
+ """Return a copy of this retry with the given predicate.
+
+ Args:
+ predicate (Callable[Exception]): A callable that should return
+ ``True`` if the given exception is retryable.
+
+ Returns:
+ Retry: A new retry instance with the given predicate.
+ """
+ return type(self)(
+ predicate=predicate,
+ initial=self._initial,
+ maximum=self._maximum,
+ multiplier=self._multiplier,
+ timeout=self._timeout,
+ on_error=self._on_error,
+ )
+
+ def with_delay(
+ self,
+ initial: Optional[float] = None,
+ maximum: Optional[float] = None,
+ multiplier: Optional[float] = None,
+ ) -> Self:
+ """Return a copy of this retry with the given delay options.
+
+ Args:
+ initial (float): The minimum amount of time to delay (in seconds). This must
+ be greater than 0. If None, the current value is used.
+ maximum (float): The maximum amount of time to delay (in seconds). If None, the
+ current value is used.
+ multiplier (float): The multiplier applied to the delay. If None, the current
+ value is used.
+
+ Returns:
+ Retry: A new retry instance with the given delay options.
+ """
+ return type(self)(
+ predicate=self._predicate,
+ initial=initial if initial is not None else self._initial,
+ maximum=maximum if maximum is not None else self._maximum,
+ multiplier=multiplier if multiplier is not None else self._multiplier,
+ timeout=self._timeout,
+ on_error=self._on_error,
+ )
+
+ def __str__(self) -> str:
+ return (
+ "<{} predicate={}, initial={:.1f}, maximum={:.1f}, "
+ "multiplier={:.1f}, timeout={}, on_error={}>".format(
+ type(self).__name__,
+ self._predicate,
+ self._initial,
+ self._maximum,
+ self._multiplier,
+ self._timeout, # timeout can be None, thus no {:.1f}
+ self._on_error,
+ )
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_streaming.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_streaming.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4474c8afdcff233626429c103e96f24c1c3687b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_streaming.py
@@ -0,0 +1,264 @@
+# Copyright 2023 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Generator wrapper for retryable streaming RPCs.
+"""
+from __future__ import annotations
+
+from typing import (
+ Callable,
+ Optional,
+ List,
+ Tuple,
+ Iterable,
+ Generator,
+ TypeVar,
+ Any,
+ TYPE_CHECKING,
+)
+
+import sys
+import time
+import functools
+
+from google.api_core.retry.retry_base import _BaseRetry
+from google.api_core.retry.retry_base import _retry_error_helper
+from google.api_core.retry import exponential_sleep_generator
+from google.api_core.retry import build_retry_error
+from google.api_core.retry import RetryFailureReason
+
+if TYPE_CHECKING:
+ if sys.version_info >= (3, 10):
+ from typing import ParamSpec
+ else:
+ from typing_extensions import ParamSpec
+
+ _P = ParamSpec("_P") # target function call parameters
+ _Y = TypeVar("_Y") # yielded values
+
+
+def retry_target_stream(
+ target: Callable[_P, Iterable[_Y]],
+ predicate: Callable[[Exception], bool],
+ sleep_generator: Iterable[float],
+ timeout: Optional[float] = None,
+ on_error: Optional[Callable[[Exception], None]] = None,
+ exception_factory: Callable[
+ [List[Exception], RetryFailureReason, Optional[float]],
+ Tuple[Exception, Optional[Exception]],
+ ] = build_retry_error,
+ init_args: tuple = (),
+ init_kwargs: dict = {},
+ **kwargs,
+) -> Generator[_Y, Any, None]:
+ """Create a generator wrapper that retries the wrapped stream if it fails.
+
+ This is the lowest-level retry helper. Generally, you'll use the
+ higher-level retry helper :class:`Retry`.
+
+ Args:
+ target: The generator function to call and retry.
+ predicate: A callable used to determine if an
+ exception raised by the target should be considered retryable.
+ It should return True to retry or False otherwise.
+ sleep_generator: An infinite iterator that determines
+ how long to sleep between retries.
+ timeout: How long to keep retrying the target.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error: If given, the on_error callback will be called with each
+ retryable exception raised by the target. Any error raised by this
+ function will *not* be caught.
+ exception_factory: A function that is called when the retryable reaches
+ a terminal failure state, used to construct an exception to be raised.
+ It takes a list of all exceptions encountered, a retry.RetryFailureReason
+ enum indicating the failure cause, and the original timeout value
+ as arguments. It should return a tuple of the exception to be raised,
+ along with the cause exception if any. The default implementation will raise
+ a RetryError on timeout, or the last exception encountered otherwise.
+ init_args: Positional arguments to pass to the target function.
+ init_kwargs: Keyword arguments to pass to the target function.
+
+ Returns:
+ Generator: A retryable generator that wraps the target generator function.
+
+ Raises:
+ ValueError: If the sleep generator stops yielding values.
+ Exception: a custom exception specified by the exception_factory if provided.
+ If no exception_factory is provided:
+ google.api_core.RetryError: If the timeout is exceeded while retrying.
+ Exception: If the target raises an error that isn't retryable.
+ """
+
+ timeout = kwargs.get("deadline", timeout)
+ deadline: Optional[float] = (
+ time.monotonic() + timeout if timeout is not None else None
+ )
+ error_list: list[Exception] = []
+ sleep_iter = iter(sleep_generator)
+
+ # continue trying until an attempt completes, or a terminal exception is raised in _retry_error_helper
+ # TODO: support max_attempts argument: https://github.com/googleapis/python-api-core/issues/535
+ while True:
+ # Start a new retry loop
+ try:
+ # Note: in the future, we can add a ResumptionStrategy object
+ # to generate new args between calls. For now, use the same args
+ # for each attempt.
+ subgenerator = target(*init_args, **init_kwargs)
+ return (yield from subgenerator)
+ # handle exceptions raised by the subgenerator
+ # pylint: disable=broad-except
+ # This function explicitly must deal with broad exceptions.
+ except Exception as exc:
+ # defer to shared logic for handling errors
+ next_sleep = _retry_error_helper(
+ exc,
+ deadline,
+ sleep_iter,
+ error_list,
+ predicate,
+ on_error,
+ exception_factory,
+ timeout,
+ )
+ # if exception not raised, sleep before next attempt
+ time.sleep(next_sleep)
+
+
+class StreamingRetry(_BaseRetry):
+ """Exponential retry decorator for streaming synchronous RPCs.
+
+ This class returns a Generator when called, which wraps the target
+ stream in retry logic. If any exception is raised by the target, the
+ entire stream will be retried within the wrapper.
+
+ Although the default behavior is to retry transient API errors, a
+ different predicate can be provided to retry other exceptions.
+
+ Important Note: when a stream encounters a retryable error, it will
+ silently construct a fresh iterator instance in the background
+ and continue yielding (likely duplicate) values as if no error occurred.
+ This is the most general way to retry a stream, but it often is not the
+ desired behavior. Example: iter([1, 2, 1/0]) -> [1, 2, 1, 2, ...]
+
+ There are two ways to build more advanced retry logic for streams:
+
+ 1. Wrap the target
+ Use a ``target`` that maintains state between retries, and creates a
+ different generator on each retry call. For example, you can wrap a
+ network call in a function that modifies the request based on what has
+ already been returned:
+
+ .. code-block:: python
+
+ def attempt_with_modified_request(target, request, seen_items=[]):
+ # remove seen items from request on each attempt
+ new_request = modify_request(request, seen_items)
+ new_generator = target(new_request)
+ for item in new_generator:
+ yield item
+ seen_items.append(item)
+
+ retry_wrapped_fn = StreamingRetry()(attempt_with_modified_request)
+ retryable_generator = retry_wrapped_fn(target, request)
+
+ 2. Wrap the retry generator
+ Alternatively, you can wrap the retryable generator itself before
+ passing it to the end-user to add a filter on the stream. For
+ example, you can keep track of the items that were successfully yielded
+ in previous retry attempts, and only yield new items when the
+ new attempt surpasses the previous ones:
+
+ .. code-block:: python
+
+ def retryable_with_filter(target):
+ stream_idx = 0
+ # reset stream_idx when the stream is retried
+ def on_error(e):
+ nonlocal stream_idx
+ stream_idx = 0
+ # build retryable
+ retryable_gen = StreamingRetry(...)(target)
+ # keep track of what has been yielded out of filter
+ seen_items = []
+ for item in retryable_gen():
+ if stream_idx >= len(seen_items):
+ seen_items.append(item)
+ yield item
+ elif item != seen_items[stream_idx]:
+ raise ValueError("Stream differs from last attempt")
+ stream_idx += 1
+
+ filter_retry_wrapped = retryable_with_filter(target)
+
+ Args:
+ predicate (Callable[Exception]): A callable that should return ``True``
+ if the given exception is retryable.
+ initial (float): The minimum amount of time to delay in seconds. This
+ must be greater than 0.
+ maximum (float): The maximum amount of time to delay in seconds.
+ multiplier (float): The multiplier applied to the delay.
+ timeout (float): How long to keep retrying, in seconds.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error (Callable[Exception]): A function to call while processing
+ a retryable exception. Any error raised by this function will
+ *not* be caught.
+ deadline (float): DEPRECATED: use `timeout` instead. For backward
+ compatibility, if specified it will override the ``timeout`` parameter.
+ """
+
+ def __call__(
+ self,
+ func: Callable[_P, Iterable[_Y]],
+ on_error: Callable[[Exception], Any] | None = None,
+ ) -> Callable[_P, Generator[_Y, Any, None]]:
+ """Wrap a callable with retry behavior.
+
+ Args:
+ func (Callable): The callable to add retry behavior to.
+ on_error (Optional[Callable[Exception]]): If given, the
+ on_error callback will be called with each retryable exception
+ raised by the wrapped function. Any error raised by this
+ function will *not* be caught. If on_error was specified in the
+ constructor, this value will be ignored.
+
+ Returns:
+ Callable: A callable that will invoke ``func`` with retry
+ behavior.
+ """
+ if self._on_error is not None:
+ on_error = self._on_error
+
+ @functools.wraps(func)
+ def retry_wrapped_func(
+ *args: _P.args, **kwargs: _P.kwargs
+ ) -> Generator[_Y, Any, None]:
+ """A wrapper that calls target function with retry."""
+ sleep_generator = exponential_sleep_generator(
+ self._initial, self._maximum, multiplier=self._multiplier
+ )
+ return retry_target_stream(
+ func,
+ predicate=self._predicate,
+ sleep_generator=sleep_generator,
+ timeout=self._timeout,
+ on_error=on_error,
+ init_args=args,
+ init_kwargs=kwargs,
+ )
+
+ return retry_wrapped_func
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_streaming_async.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_streaming_async.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e5fa2402478c92956600756ed1f48271027f9f6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_streaming_async.py
@@ -0,0 +1,328 @@
+# Copyright 2023 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Generator wrapper for retryable async streaming RPCs.
+"""
+from __future__ import annotations
+
+from typing import (
+ cast,
+ Any,
+ Callable,
+ Iterable,
+ AsyncIterator,
+ AsyncIterable,
+ Awaitable,
+ TypeVar,
+ AsyncGenerator,
+ TYPE_CHECKING,
+)
+
+import asyncio
+import time
+import sys
+import functools
+
+from google.api_core.retry.retry_base import _BaseRetry
+from google.api_core.retry.retry_base import _retry_error_helper
+from google.api_core.retry import exponential_sleep_generator
+from google.api_core.retry import build_retry_error
+from google.api_core.retry import RetryFailureReason
+
+
+if TYPE_CHECKING:
+ if sys.version_info >= (3, 10):
+ from typing import ParamSpec
+ else:
+ from typing_extensions import ParamSpec
+
+ _P = ParamSpec("_P") # target function call parameters
+ _Y = TypeVar("_Y") # yielded values
+
+
+async def retry_target_stream(
+ target: Callable[_P, AsyncIterable[_Y] | Awaitable[AsyncIterable[_Y]]],
+ predicate: Callable[[Exception], bool],
+ sleep_generator: Iterable[float],
+ timeout: float | None = None,
+ on_error: Callable[[Exception], None] | None = None,
+ exception_factory: Callable[
+ [list[Exception], RetryFailureReason, float | None],
+ tuple[Exception, Exception | None],
+ ] = build_retry_error,
+ init_args: tuple = (),
+ init_kwargs: dict = {},
+ **kwargs,
+) -> AsyncGenerator[_Y, None]:
+ """Create a generator wrapper that retries the wrapped stream if it fails.
+
+ This is the lowest-level retry helper. Generally, you'll use the
+ higher-level retry helper :class:`AsyncRetry`.
+
+ Args:
+ target: The generator function to call and retry.
+ predicate: A callable used to determine if an
+ exception raised by the target should be considered retryable.
+ It should return True to retry or False otherwise.
+ sleep_generator: An infinite iterator that determines
+ how long to sleep between retries.
+ timeout: How long to keep retrying the target.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error: If given, the on_error callback will be called with each
+ retryable exception raised by the target. Any error raised by this
+ function will *not* be caught.
+ exception_factory: A function that is called when the retryable reaches
+ a terminal failure state, used to construct an exception to be raised.
+ It takes a list of all exceptions encountered, a retry.RetryFailureReason
+ enum indicating the failure cause, and the original timeout value
+ as arguments. It should return a tuple of the exception to be raised,
+ along with the cause exception if any. The default implementation will raise
+ a RetryError on timeout, or the last exception encountered otherwise.
+ init_args: Positional arguments to pass to the target function.
+ init_kwargs: Keyword arguments to pass to the target function.
+
+ Returns:
+ AsyncGenerator: A retryable generator that wraps the target generator function.
+
+ Raises:
+ ValueError: If the sleep generator stops yielding values.
+ Exception: a custom exception specified by the exception_factory if provided.
+ If no exception_factory is provided:
+ google.api_core.RetryError: If the timeout is exceeded while retrying.
+ Exception: If the target raises an error that isn't retryable.
+ """
+ target_iterator: AsyncIterator[_Y] | None = None
+ timeout = kwargs.get("deadline", timeout)
+ deadline = time.monotonic() + timeout if timeout else None
+ # keep track of retryable exceptions we encounter to pass in to exception_factory
+ error_list: list[Exception] = []
+ sleep_iter = iter(sleep_generator)
+ target_is_generator: bool | None = None
+
+ # continue trying until an attempt completes, or a terminal exception is raised in _retry_error_helper
+ # TODO: support max_attempts argument: https://github.com/googleapis/python-api-core/issues/535
+ while True:
+ # Start a new retry loop
+ try:
+ # Note: in the future, we can add a ResumptionStrategy object
+ # to generate new args between calls. For now, use the same args
+ # for each attempt.
+ target_output: AsyncIterable[_Y] | Awaitable[AsyncIterable[_Y]] = target(
+ *init_args, **init_kwargs
+ )
+ try:
+ # gapic functions return the generator behind an awaitable
+ # unwrap the awaitable so we can work with the generator directly
+ target_output = await target_output # type: ignore
+ except TypeError:
+ # was not awaitable, continue
+ pass
+ target_iterator = cast(AsyncIterable["_Y"], target_output).__aiter__()
+
+ if target_is_generator is None:
+ # Check if target supports generator features (asend, athrow, aclose)
+ target_is_generator = bool(getattr(target_iterator, "asend", None))
+
+ sent_in = None
+ while True:
+ ## Read from target_iterator
+ # If the target is a generator, we will advance it with `asend`
+ # otherwise, we will use `anext`
+ if target_is_generator:
+ next_value = await target_iterator.asend(sent_in) # type: ignore
+ else:
+ next_value = await target_iterator.__anext__()
+ ## Yield from Wrapper to caller
+ try:
+ # yield latest value from target
+ # exceptions from `athrow` and `aclose` are injected here
+ sent_in = yield next_value
+ except GeneratorExit:
+ # if wrapper received `aclose` while waiting on yield,
+ # it will raise GeneratorExit here
+ if target_is_generator:
+ # pass to inner target_iterator for handling
+ await cast(AsyncGenerator["_Y", None], target_iterator).aclose()
+ else:
+ raise
+ return
+ except: # noqa: E722
+ # bare except catches any exception passed to `athrow`
+ if target_is_generator:
+ # delegate error handling to target_iterator
+ await cast(AsyncGenerator["_Y", None], target_iterator).athrow(
+ cast(BaseException, sys.exc_info()[1])
+ )
+ else:
+ raise
+ return
+ except StopAsyncIteration:
+ # if iterator exhausted, return
+ return
+ # handle exceptions raised by the target_iterator
+ # pylint: disable=broad-except
+ # This function explicitly must deal with broad exceptions.
+ except Exception as exc:
+ # defer to shared logic for handling errors
+ next_sleep = _retry_error_helper(
+ exc,
+ deadline,
+ sleep_iter,
+ error_list,
+ predicate,
+ on_error,
+ exception_factory,
+ timeout,
+ )
+ # if exception not raised, sleep before next attempt
+ await asyncio.sleep(next_sleep)
+
+ finally:
+ if target_is_generator and target_iterator is not None:
+ await cast(AsyncGenerator["_Y", None], target_iterator).aclose()
+
+
+class AsyncStreamingRetry(_BaseRetry):
+ """Exponential retry decorator for async streaming rpcs.
+
+ This class returns an AsyncGenerator when called, which wraps the target
+ stream in retry logic. If any exception is raised by the target, the
+ entire stream will be retried within the wrapper.
+
+ Although the default behavior is to retry transient API errors, a
+ different predicate can be provided to retry other exceptions.
+
+ Important Note: when a stream is encounters a retryable error, it will
+ silently construct a fresh iterator instance in the background
+ and continue yielding (likely duplicate) values as if no error occurred.
+ This is the most general way to retry a stream, but it often is not the
+ desired behavior. Example: iter([1, 2, 1/0]) -> [1, 2, 1, 2, ...]
+
+ There are two ways to build more advanced retry logic for streams:
+
+ 1. Wrap the target
+ Use a ``target`` that maintains state between retries, and creates a
+ different generator on each retry call. For example, you can wrap a
+ grpc call in a function that modifies the request based on what has
+ already been returned:
+
+ .. code-block:: python
+
+ async def attempt_with_modified_request(target, request, seen_items=[]):
+ # remove seen items from request on each attempt
+ new_request = modify_request(request, seen_items)
+ new_generator = await target(new_request)
+ async for item in new_generator:
+ yield item
+ seen_items.append(item)
+
+ retry_wrapped = AsyncRetry(is_stream=True,...)(attempt_with_modified_request, target, request, [])
+
+ 2. Wrap the retry generator
+ Alternatively, you can wrap the retryable generator itself before
+ passing it to the end-user to add a filter on the stream. For
+ example, you can keep track of the items that were successfully yielded
+ in previous retry attempts, and only yield new items when the
+ new attempt surpasses the previous ones:
+
+ .. code-block:: python
+
+ async def retryable_with_filter(target):
+ stream_idx = 0
+ # reset stream_idx when the stream is retried
+ def on_error(e):
+ nonlocal stream_idx
+ stream_idx = 0
+ # build retryable
+ retryable_gen = AsyncRetry(is_stream=True, ...)(target)
+ # keep track of what has been yielded out of filter
+ seen_items = []
+ async for item in retryable_gen:
+ if stream_idx >= len(seen_items):
+ yield item
+ seen_items.append(item)
+ elif item != previous_stream[stream_idx]:
+ raise ValueError("Stream differs from last attempt")"
+ stream_idx += 1
+
+ filter_retry_wrapped = retryable_with_filter(target)
+
+ Args:
+ predicate (Callable[Exception]): A callable that should return ``True``
+ if the given exception is retryable.
+ initial (float): The minimum amount of time to delay in seconds. This
+ must be greater than 0.
+ maximum (float): The maximum amount of time to delay in seconds.
+ multiplier (float): The multiplier applied to the delay.
+ timeout (Optional[float]): How long to keep retrying in seconds.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error (Optional[Callable[Exception]]): A function to call while processing
+ a retryable exception. Any error raised by this function will
+ *not* be caught.
+ is_stream (bool): Indicates whether the input function
+ should be treated as a stream function (i.e. an AsyncGenerator,
+ or function or coroutine that returns an AsyncIterable).
+ If True, the iterable will be wrapped with retry logic, and any
+ failed outputs will restart the stream. If False, only the input
+ function call itself will be retried. Defaults to False.
+ To avoid duplicate values, retryable streams should typically be
+ wrapped in additional filter logic before use.
+ deadline (float): DEPRECATED use ``timeout`` instead. If set it will
+ override ``timeout`` parameter.
+ """
+
+ def __call__(
+ self,
+ func: Callable[..., AsyncIterable[_Y] | Awaitable[AsyncIterable[_Y]]],
+ on_error: Callable[[Exception], Any] | None = None,
+ ) -> Callable[_P, Awaitable[AsyncGenerator[_Y, None]]]:
+ """Wrap a callable with retry behavior.
+
+ Args:
+ func (Callable): The callable or stream to add retry behavior to.
+ on_error (Optional[Callable[Exception]]): If given, the
+ on_error callback will be called with each retryable exception
+ raised by the wrapped function. Any error raised by this
+ function will *not* be caught. If on_error was specified in the
+ constructor, this value will be ignored.
+
+ Returns:
+ Callable: A callable that will invoke ``func`` with retry
+ behavior.
+ """
+ if self._on_error is not None:
+ on_error = self._on_error
+
+ @functools.wraps(func)
+ async def retry_wrapped_func(
+ *args: _P.args, **kwargs: _P.kwargs
+ ) -> AsyncGenerator[_Y, None]:
+ """A wrapper that calls target function with retry."""
+ sleep_generator = exponential_sleep_generator(
+ self._initial, self._maximum, multiplier=self._multiplier
+ )
+ return retry_target_stream(
+ func,
+ self._predicate,
+ sleep_generator,
+ self._timeout,
+ on_error,
+ init_args=args,
+ init_kwargs=kwargs,
+ )
+
+ return retry_wrapped_func
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_unary.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_unary.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d36bc7d1a451b3977aeada7aaacd15e76ea08ff
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_unary.py
@@ -0,0 +1,302 @@
+# Copyright 2017 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers for retrying functions with exponential back-off.
+
+The :class:`Retry` decorator can be used to retry functions that raise
+exceptions using exponential backoff. Because a exponential sleep algorithm is
+used, the retry is limited by a `timeout`. The timeout determines the window
+in which retries will be attempted. This is used instead of total number of retries
+because it is difficult to ascertain the amount of time a function can block
+when using total number of retries and exponential backoff.
+
+By default, this decorator will retry transient
+API errors (see :func:`if_transient_error`). For example:
+
+.. code-block:: python
+
+ @retry.Retry()
+ def call_flaky_rpc():
+ return client.flaky_rpc()
+
+ # Will retry flaky_rpc() if it raises transient API errors.
+ result = call_flaky_rpc()
+
+You can pass a custom predicate to retry on different exceptions, such as
+waiting for an eventually consistent item to be available:
+
+.. code-block:: python
+
+ @retry.Retry(predicate=if_exception_type(exceptions.NotFound))
+ def check_if_exists():
+ return client.does_thing_exist()
+
+ is_available = check_if_exists()
+
+Some client library methods apply retry automatically. These methods can accept
+a ``retry`` parameter that allows you to configure the behavior:
+
+.. code-block:: python
+
+ my_retry = retry.Retry(timeout=60)
+ result = client.some_method(retry=my_retry)
+
+"""
+
+from __future__ import annotations
+
+import functools
+import sys
+import time
+import inspect
+import warnings
+from typing import Any, Callable, Iterable, TypeVar, TYPE_CHECKING
+
+from google.api_core.retry.retry_base import _BaseRetry
+from google.api_core.retry.retry_base import _retry_error_helper
+from google.api_core.retry.retry_base import exponential_sleep_generator
+from google.api_core.retry.retry_base import build_retry_error
+from google.api_core.retry.retry_base import RetryFailureReason
+
+
+if TYPE_CHECKING:
+ if sys.version_info >= (3, 10):
+ from typing import ParamSpec
+ else:
+ from typing_extensions import ParamSpec
+
+ _P = ParamSpec("_P") # target function call parameters
+ _R = TypeVar("_R") # target function returned value
+
+_ASYNC_RETRY_WARNING = "Using the synchronous google.api_core.retry.Retry with asynchronous calls may lead to unexpected results. Please use google.api_core.retry_async.AsyncRetry instead."
+
+
+def retry_target(
+ target: Callable[[], _R],
+ predicate: Callable[[Exception], bool],
+ sleep_generator: Iterable[float],
+ timeout: float | None = None,
+ on_error: Callable[[Exception], None] | None = None,
+ exception_factory: Callable[
+ [list[Exception], RetryFailureReason, float | None],
+ tuple[Exception, Exception | None],
+ ] = build_retry_error,
+ **kwargs,
+):
+ """Call a function and retry if it fails.
+
+ This is the lowest-level retry helper. Generally, you'll use the
+ higher-level retry helper :class:`Retry`.
+
+ Args:
+ target(Callable): The function to call and retry. This must be a
+ nullary function - apply arguments with `functools.partial`.
+ predicate (Callable[Exception]): A callable used to determine if an
+ exception raised by the target should be considered retryable.
+ It should return True to retry or False otherwise.
+ sleep_generator (Iterable[float]): An infinite iterator that determines
+ how long to sleep between retries.
+ timeout (Optional[float]): How long to keep retrying the target.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error (Optional[Callable[Exception]]): If given, the on_error
+ callback will be called with each retryable exception raised by the
+ target. Any error raised by this function will *not* be caught.
+ exception_factory: A function that is called when the retryable reaches
+ a terminal failure state, used to construct an exception to be raised.
+ It takes a list of all exceptions encountered, a retry.RetryFailureReason
+ enum indicating the failure cause, and the original timeout value
+ as arguments. It should return a tuple of the exception to be raised,
+ along with the cause exception if any. The default implementation will raise
+ a RetryError on timeout, or the last exception encountered otherwise.
+ deadline (float): DEPRECATED: use ``timeout`` instead. For backward
+ compatibility, if specified it will override ``timeout`` parameter.
+
+ Returns:
+ Any: the return value of the target function.
+
+ Raises:
+ ValueError: If the sleep generator stops yielding values.
+ Exception: a custom exception specified by the exception_factory if provided.
+ If no exception_factory is provided:
+ google.api_core.RetryError: If the timeout is exceeded while retrying.
+ Exception: If the target raises an error that isn't retryable.
+ """
+
+ timeout = kwargs.get("deadline", timeout)
+
+ deadline = time.monotonic() + timeout if timeout is not None else None
+ error_list: list[Exception] = []
+ sleep_iter = iter(sleep_generator)
+
+ # continue trying until an attempt completes, or a terminal exception is raised in _retry_error_helper
+ # TODO: support max_attempts argument: https://github.com/googleapis/python-api-core/issues/535
+ while True:
+ try:
+ result = target()
+ if inspect.isawaitable(result):
+ warnings.warn(_ASYNC_RETRY_WARNING)
+ return result
+
+ # pylint: disable=broad-except
+ # This function explicitly must deal with broad exceptions.
+ except Exception as exc:
+ # defer to shared logic for handling errors
+ next_sleep = _retry_error_helper(
+ exc,
+ deadline,
+ sleep_iter,
+ error_list,
+ predicate,
+ on_error,
+ exception_factory,
+ timeout,
+ )
+ # if exception not raised, sleep before next attempt
+ time.sleep(next_sleep)
+
+
+class Retry(_BaseRetry):
+ """Exponential retry decorator for unary synchronous RPCs.
+
+ This class is a decorator used to add retry or polling behavior to an RPC
+ call.
+
+ Although the default behavior is to retry transient API errors, a
+ different predicate can be provided to retry other exceptions.
+
+ There are two important concepts that retry/polling behavior may operate on,
+ Deadline and Timeout, which need to be properly defined for the correct
+ usage of this class and the rest of the library.
+
+ Deadline: a fixed point in time by which a certain operation must
+ terminate. For example, if a certain operation has a deadline
+ "2022-10-18T23:30:52.123Z" it must terminate (successfully or with an
+ error) by that time, regardless of when it was started or whether it
+ was started at all.
+
+ Timeout: the maximum duration of time after which a certain operation
+ must terminate (successfully or with an error). The countdown begins right
+ after an operation was started. For example, if an operation was started at
+ 09:24:00 with timeout of 75 seconds, it must terminate no later than
+ 09:25:15.
+
+ Unfortunately, in the past this class (and the api-core library as a whole) has not
+ been properly distinguishing the concepts of "timeout" and "deadline", and the
+ ``deadline`` parameter has meant ``timeout``. That is why
+ ``deadline`` has been deprecated and ``timeout`` should be used instead. If the
+ ``deadline`` parameter is set, it will override the ``timeout`` parameter.
+ In other words, ``retry.deadline`` should be treated as just a deprecated alias for
+ ``retry.timeout``.
+
+ Said another way, it is safe to assume that this class and the rest of this
+ library operate in terms of timeouts (not deadlines) unless explicitly
+ noted the usage of deadline semantics.
+
+ It is also important to
+ understand the three most common applications of the Timeout concept in the
+ context of this library.
+
+ Usually the generic Timeout term may stand for one of the following actual
+ timeouts: RPC Timeout, Retry Timeout, or Polling Timeout.
+
+ RPC Timeout: a value supplied by the client to the server so
+ that the server side knows the maximum amount of time it is expected to
+ spend handling that specific RPC. For example, in the case of gRPC transport,
+ RPC Timeout is represented by setting "grpc-timeout" header in the HTTP2
+ request. The `timeout` property of this class normally never represents the
+ RPC Timeout as it is handled separately by the ``google.api_core.timeout``
+ module of this library.
+
+ Retry Timeout: this is the most common meaning of the ``timeout`` property
+ of this class, and defines how long a certain RPC may be retried in case
+ the server returns an error.
+
+ Polling Timeout: defines how long the
+ client side is allowed to call the polling RPC repeatedly to check a status of a
+ long-running operation. Each polling RPC is
+ expected to succeed (its errors are supposed to be handled by the retry
+ logic). The decision as to whether a new polling attempt needs to be made is based
+ not on the RPC status code but on the status of the returned
+ status of an operation. In other words: we will poll a long-running operation until
+ the operation is done or the polling timeout expires. Each poll will inform us of
+ the status of the operation. The poll consists of an RPC to the server that may
+ itself be retried as per the poll-specific retry settings in case of errors. The
+ operation-level retry settings do NOT apply to polling-RPC retries.
+
+ With the actual timeout types being defined above, the client libraries
+ often refer to just Timeout without clarifying which type specifically
+ that is. In that case the actual timeout type (sometimes also referred to as
+ Logical Timeout) can be determined from the context. If it is a unary rpc
+ call (i.e. a regular one) Timeout usually stands for the RPC Timeout (if
+ provided directly as a standalone value) or Retry Timeout (if provided as
+ ``retry.timeout`` property of the unary RPC's retry config). For
+ ``Operation`` or ``PollingFuture`` in general Timeout stands for
+ Polling Timeout.
+
+ Args:
+ predicate (Callable[Exception]): A callable that should return ``True``
+ if the given exception is retryable.
+ initial (float): The minimum amount of time to delay in seconds. This
+ must be greater than 0.
+ maximum (float): The maximum amount of time to delay in seconds.
+ multiplier (float): The multiplier applied to the delay.
+ timeout (Optional[float]): How long to keep retrying, in seconds.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error (Callable[Exception]): A function to call while processing
+ a retryable exception. Any error raised by this function will
+ *not* be caught.
+ deadline (float): DEPRECATED: use `timeout` instead. For backward
+ compatibility, if specified it will override the ``timeout`` parameter.
+ """
+
+ def __call__(
+ self,
+ func: Callable[_P, _R],
+ on_error: Callable[[Exception], Any] | None = None,
+ ) -> Callable[_P, _R]:
+ """Wrap a callable with retry behavior.
+
+ Args:
+ func (Callable): The callable to add retry behavior to.
+ on_error (Optional[Callable[Exception]]): If given, the
+ on_error callback will be called with each retryable exception
+ raised by the wrapped function. Any error raised by this
+ function will *not* be caught. If on_error was specified in the
+ constructor, this value will be ignored.
+
+ Returns:
+ Callable: A callable that will invoke ``func`` with retry
+ behavior.
+ """
+ if self._on_error is not None:
+ on_error = self._on_error
+
+ @functools.wraps(func)
+ def retry_wrapped_func(*args: _P.args, **kwargs: _P.kwargs) -> _R:
+ """A wrapper that calls target function with retry."""
+ target = functools.partial(func, *args, **kwargs)
+ sleep_generator = exponential_sleep_generator(
+ self._initial, self._maximum, multiplier=self._multiplier
+ )
+ return retry_target(
+ target,
+ self._predicate,
+ sleep_generator,
+ timeout=self._timeout,
+ on_error=on_error,
+ )
+
+ return retry_wrapped_func
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_unary_async.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_unary_async.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f72476aff1396dff44a2cf150baf0bee4946079
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/api_core/retry/retry_unary_async.py
@@ -0,0 +1,239 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers for retrying coroutine functions with exponential back-off.
+
+The :class:`AsyncRetry` decorator shares most functionality and behavior with
+:class:`Retry`, but supports coroutine functions. Please refer to description
+of :class:`Retry` for more details.
+
+By default, this decorator will retry transient
+API errors (see :func:`if_transient_error`). For example:
+
+.. code-block:: python
+
+ @retry_async.AsyncRetry()
+ async def call_flaky_rpc():
+ return await client.flaky_rpc()
+
+ # Will retry flaky_rpc() if it raises transient API errors.
+ result = await call_flaky_rpc()
+
+You can pass a custom predicate to retry on different exceptions, such as
+waiting for an eventually consistent item to be available:
+
+.. code-block:: python
+
+ @retry_async.AsyncRetry(predicate=retry_async.if_exception_type(exceptions.NotFound))
+ async def check_if_exists():
+ return await client.does_thing_exist()
+
+ is_available = await check_if_exists()
+
+Some client library methods apply retry automatically. These methods can accept
+a ``retry`` parameter that allows you to configure the behavior:
+
+.. code-block:: python
+
+ my_retry = retry_async.AsyncRetry(timeout=60)
+ result = await client.some_method(retry=my_retry)
+
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+import functools
+from typing import (
+ Awaitable,
+ Any,
+ Callable,
+ Iterable,
+ TypeVar,
+ TYPE_CHECKING,
+)
+
+from google.api_core.retry.retry_base import _BaseRetry
+from google.api_core.retry.retry_base import _retry_error_helper
+from google.api_core.retry.retry_base import exponential_sleep_generator
+from google.api_core.retry.retry_base import build_retry_error
+from google.api_core.retry.retry_base import RetryFailureReason
+
+# for backwards compatibility, expose helpers in this module
+from google.api_core.retry.retry_base import if_exception_type # noqa
+from google.api_core.retry.retry_base import if_transient_error # noqa
+
+if TYPE_CHECKING:
+ import sys
+
+ if sys.version_info >= (3, 10):
+ from typing import ParamSpec
+ else:
+ from typing_extensions import ParamSpec
+
+ _P = ParamSpec("_P") # target function call parameters
+ _R = TypeVar("_R") # target function returned value
+
+_DEFAULT_INITIAL_DELAY = 1.0 # seconds
+_DEFAULT_MAXIMUM_DELAY = 60.0 # seconds
+_DEFAULT_DELAY_MULTIPLIER = 2.0
+_DEFAULT_DEADLINE = 60.0 * 2.0 # seconds
+_DEFAULT_TIMEOUT = 60.0 * 2.0 # seconds
+
+
+async def retry_target(
+ target: Callable[[], Awaitable[_R]],
+ predicate: Callable[[Exception], bool],
+ sleep_generator: Iterable[float],
+ timeout: float | None = None,
+ on_error: Callable[[Exception], None] | None = None,
+ exception_factory: Callable[
+ [list[Exception], RetryFailureReason, float | None],
+ tuple[Exception, Exception | None],
+ ] = build_retry_error,
+ **kwargs,
+):
+ """Await a coroutine and retry if it fails.
+
+ This is the lowest-level retry helper. Generally, you'll use the
+ higher-level retry helper :class:`Retry`.
+
+ Args:
+ target(Callable[[], Any]): The function to call and retry. This must be a
+ nullary function - apply arguments with `functools.partial`.
+ predicate (Callable[Exception]): A callable used to determine if an
+ exception raised by the target should be considered retryable.
+ It should return True to retry or False otherwise.
+ sleep_generator (Iterable[float]): An infinite iterator that determines
+ how long to sleep between retries.
+ timeout (Optional[float]): How long to keep retrying the target, in seconds.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error (Optional[Callable[Exception]]): If given, the on_error
+ callback will be called with each retryable exception raised by the
+ target. Any error raised by this function will *not* be caught.
+ exception_factory: A function that is called when the retryable reaches
+ a terminal failure state, used to construct an exception to be raised.
+ It takes a list of all exceptions encountered, a retry.RetryFailureReason
+ enum indicating the failure cause, and the original timeout value
+ as arguments. It should return a tuple of the exception to be raised,
+ along with the cause exception if any. The default implementation will raise
+ a RetryError on timeout, or the last exception encountered otherwise.
+ deadline (float): DEPRECATED use ``timeout`` instead. For backward
+ compatibility, if set it will override the ``timeout`` parameter.
+
+ Returns:
+ Any: the return value of the target function.
+
+ Raises:
+ ValueError: If the sleep generator stops yielding values.
+ Exception: a custom exception specified by the exception_factory if provided.
+ If no exception_factory is provided:
+ google.api_core.RetryError: If the timeout is exceeded while retrying.
+ Exception: If the target raises an error that isn't retryable.
+ """
+
+ timeout = kwargs.get("deadline", timeout)
+
+ deadline = time.monotonic() + timeout if timeout is not None else None
+ error_list: list[Exception] = []
+ sleep_iter = iter(sleep_generator)
+
+ # continue trying until an attempt completes, or a terminal exception is raised in _retry_error_helper
+ # TODO: support max_attempts argument: https://github.com/googleapis/python-api-core/issues/535
+ while True:
+ try:
+ return await target()
+ # pylint: disable=broad-except
+ # This function explicitly must deal with broad exceptions.
+ except Exception as exc:
+ # defer to shared logic for handling errors
+ next_sleep = _retry_error_helper(
+ exc,
+ deadline,
+ sleep_iter,
+ error_list,
+ predicate,
+ on_error,
+ exception_factory,
+ timeout,
+ )
+ # if exception not raised, sleep before next attempt
+ await asyncio.sleep(next_sleep)
+
+
+class AsyncRetry(_BaseRetry):
+ """Exponential retry decorator for async coroutines.
+
+ This class is a decorator used to add exponential back-off retry behavior
+ to an RPC call.
+
+ Although the default behavior is to retry transient API errors, a
+ different predicate can be provided to retry other exceptions.
+
+ Args:
+ predicate (Callable[Exception]): A callable that should return ``True``
+ if the given exception is retryable.
+ initial (float): The minimum amount of time to delay in seconds. This
+ must be greater than 0.
+ maximum (float): The maximum amount of time to delay in seconds.
+ multiplier (float): The multiplier applied to the delay.
+ timeout (Optional[float]): How long to keep retrying in seconds.
+ Note: timeout is only checked before initiating a retry, so the target may
+ run past the timeout value as long as it is healthy.
+ on_error (Optional[Callable[Exception]]): A function to call while processing
+ a retryable exception. Any error raised by this function will
+ *not* be caught.
+ deadline (float): DEPRECATED use ``timeout`` instead. If set it will
+ override ``timeout`` parameter.
+ """
+
+ def __call__(
+ self,
+ func: Callable[..., Awaitable[_R]],
+ on_error: Callable[[Exception], Any] | None = None,
+ ) -> Callable[_P, Awaitable[_R]]:
+ """Wrap a callable with retry behavior.
+
+ Args:
+ func (Callable): The callable or stream to add retry behavior to.
+ on_error (Optional[Callable[Exception]]): If given, the
+ on_error callback will be called with each retryable exception
+ raised by the wrapped function. Any error raised by this
+ function will *not* be caught. If on_error was specified in the
+ constructor, this value will be ignored.
+
+ Returns:
+ Callable: A callable that will invoke ``func`` with retry
+ behavior.
+ """
+ if self._on_error is not None:
+ on_error = self._on_error
+
+ @functools.wraps(func)
+ async def retry_wrapped_func(*args: _P.args, **kwargs: _P.kwargs) -> _R:
+ """A wrapper that calls target function with retry."""
+ sleep_generator = exponential_sleep_generator(
+ self._initial, self._maximum, multiplier=self._multiplier
+ )
+ return await retry_target(
+ functools.partial(func, *args, **kwargs),
+ predicate=self._predicate,
+ sleep_generator=sleep_generator,
+ timeout=self._timeout,
+ on_error=on_error,
+ )
+
+ return retry_wrapped_func
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d3db51ec921f8ae91405a9133af3a691e957918
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata.proto b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata.proto
new file mode 100644
index 0000000000000000000000000000000000000000..0f2855c15a66716f379115e79c54b2a2a3b88a03
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata.proto
@@ -0,0 +1,98 @@
+// Copyright 2020 Google LLC.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+syntax = "proto3";
+
+package google.gapic.metadata;
+
+option csharp_namespace = "Google.Gapic.Metadata";
+option go_package = "google.golang.org/genproto/googleapis/gapic/metadata;metadata";
+option java_multiple_files = true;
+option java_outer_classname = "GapicMetadataProto";
+option java_package = "com.google.gapic.metadata";
+option php_namespace = "Google\\Gapic\\Metadata";
+option ruby_package = "Google::Gapic::Metadata";
+
+// Metadata about a GAPIC library service for a specific combination of API,
+// version, and computer language.
+message GapicMetadata {
+ // Schema version of this proto. Current value: 1.0
+ string schema = 1;
+
+ // Any human-readable comments to be included in this file.
+ string comment = 2;
+
+ // Computer language of this generated language. This must be
+ // spelled out as it spoken in English, with no capitalization or
+ // separators (e.g. "csharp", "nodejs").
+ string language = 3;
+
+ // The proto package containing the API definition for which this
+ // GAPIC library was generated.
+ string proto_package = 4;
+
+ // The language-specific library package for this GAPIC library.
+ string library_package = 5;
+
+ // A map from each proto-defined service to ServiceForTransports,
+ // which allows listing information about transport-specific
+ // implementations of the service.
+ //
+ // The key is the name of the service as it appears in the .proto
+ // file.
+ map services = 6;
+
+ // A map from a transport name to ServiceAsClient, which allows
+ // listing information about the client objects that implement the
+ // parent RPC service for the specified transport.
+ message ServiceForTransport {
+ // Map of transport name to ServiceAsClient. The key name is the transport,
+ // lower-cased with no separators (e.g. "grpc", "rest").
+ map clients = 1;
+
+ // The API version for the interface definition found in the
+ // `google.api.api_version` annotation of this proto-defined service during
+ // code generation.
+ // This is the value populated by the client in the API version request
+ // parameter as per
+ // [AIP-4236](https://google.aip.dev/client-libraries/4236).
+ string api_version = 2;
+ }
+
+ // Information about a specific client implementing a proto-defined service.
+ message ServiceAsClient {
+ // The name of the library client formatted as it appears in the source code
+ string library_client = 1;
+
+ // A mapping from each proto-defined RPC name to the the list of
+ // methods in library_client that implement it. There can be more
+ // than one library_client method for each RPC. RPCs with no
+ // library_client methods need not be included.
+ //
+ // The key name is the name of the RPC as defined and formatted in
+ // the proto file.
+ map rpcs = 2;
+ }
+
+ // List of GAPIC client methods implementing the proto-defined RPC
+ // for the transport and service specified in the containing
+ // structures.
+ message MethodList {
+ // List of methods for a specific proto-service client in the
+ // GAPIC. These names should be formatted as they appear in the
+ // source code.
+ repeated string methods = 1;
+ }
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata_pb2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8665a4a4aeefe8706fbb093ff07fa6b8655eb8a8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata_pb2.py
@@ -0,0 +1,68 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/gapic/metadata/gapic_metadata.proto
+# Protobuf Python Version: 4.25.3
+"""Generated protocol buffer code."""
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b'\n*google/gapic/metadata/gapic_metadata.proto\x12\x15google.gapic.metadata"\x85\x06\n\rGapicMetadata\x12\x0e\n\x06schema\x18\x01 \x01(\t\x12\x0f\n\x07\x63omment\x18\x02 \x01(\t\x12\x10\n\x08language\x18\x03 \x01(\t\x12\x15\n\rproto_package\x18\x04 \x01(\t\x12\x17\n\x0flibrary_package\x18\x05 \x01(\t\x12\x44\n\x08services\x18\x06 \x03(\x0b\x32\x32.google.gapic.metadata.GapicMetadata.ServicesEntry\x1ai\n\rServicesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12G\n\x05value\x18\x02 \x01(\x0b\x32\x38.google.gapic.metadata.GapicMetadata.ServiceForTransport:\x02\x38\x01\x1a\xe8\x01\n\x13ServiceForTransport\x12V\n\x07\x63lients\x18\x01 \x03(\x0b\x32\x45.google.gapic.metadata.GapicMetadata.ServiceForTransport.ClientsEntry\x12\x13\n\x0b\x61pi_version\x18\x02 \x01(\t\x1a\x64\n\x0c\x43lientsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x43\n\x05value\x18\x02 \x01(\x0b\x32\x34.google.gapic.metadata.GapicMetadata.ServiceAsClient:\x02\x38\x01\x1a\xd5\x01\n\x0fServiceAsClient\x12\x16\n\x0elibrary_client\x18\x01 \x01(\t\x12L\n\x04rpcs\x18\x02 \x03(\x0b\x32>.google.gapic.metadata.GapicMetadata.ServiceAsClient.RpcsEntry\x1a\\\n\tRpcsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12>\n\x05value\x18\x02 \x01(\x0b\x32/.google.gapic.metadata.GapicMetadata.MethodList:\x02\x38\x01\x1a\x1d\n\nMethodList\x12\x0f\n\x07methods\x18\x01 \x03(\tB\xba\x01\n\x19\x63om.google.gapic.metadataB\x12GapicMetadataProtoP\x01Z=google.golang.org/genproto/googleapis/gapic/metadata;metadata\xaa\x02\x15Google.Gapic.Metadata\xca\x02\x15Google\\Gapic\\Metadata\xea\x02\x17Google::Gapic::Metadatab\x06proto3'
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(
+ DESCRIPTOR, "google.gapic.metadata.gapic_metadata_pb2", _globals
+)
+if _descriptor._USE_C_DESCRIPTORS == False:
+ _globals["DESCRIPTOR"]._options = None
+ _globals[
+ "DESCRIPTOR"
+ ]._serialized_options = b"\n\031com.google.gapic.metadataB\022GapicMetadataProtoP\001Z=google.golang.org/genproto/googleapis/gapic/metadata;metadata\252\002\025Google.Gapic.Metadata\312\002\025Google\\Gapic\\Metadata\352\002\027Google::Gapic::Metadata"
+ _globals["_GAPICMETADATA_SERVICESENTRY"]._options = None
+ _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_options = b"8\001"
+ _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._options = None
+ _globals[
+ "_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"
+ ]._serialized_options = b"8\001"
+ _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._options = None
+ _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_options = b"8\001"
+ _globals["_GAPICMETADATA"]._serialized_start = 70
+ _globals["_GAPICMETADATA"]._serialized_end = 843
+ _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_start = 256
+ _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_end = 361
+ _globals["_GAPICMETADATA_SERVICEFORTRANSPORT"]._serialized_start = 364
+ _globals["_GAPICMETADATA_SERVICEFORTRANSPORT"]._serialized_end = 596
+ _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._serialized_start = 496
+ _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._serialized_end = 596
+ _globals["_GAPICMETADATA_SERVICEASCLIENT"]._serialized_start = 599
+ _globals["_GAPICMETADATA_SERVICEASCLIENT"]._serialized_end = 812
+ _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_start = 720
+ _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_end = 812
+ _globals["_GAPICMETADATA_METHODLIST"]._serialized_start = 814
+ _globals["_GAPICMETADATA_METHODLIST"]._serialized_end = 843
+# @@protoc_insertion_point(module_scope)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..aed974f2cf54f3983f200587fb336159e810139f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi
@@ -0,0 +1,125 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import ClassVar as _ClassVar
+from typing import Iterable as _Iterable
+from typing import Mapping as _Mapping
+from typing import Optional as _Optional
+from typing import Union as _Union
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from google.protobuf.internal import containers as _containers
+
+DESCRIPTOR: _descriptor.FileDescriptor
+
+class GapicMetadata(_message.Message):
+ __slots__ = (
+ "schema",
+ "comment",
+ "language",
+ "proto_package",
+ "library_package",
+ "services",
+ )
+
+ class ServicesEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: GapicMetadata.ServiceForTransport
+ def __init__(
+ self,
+ key: _Optional[str] = ...,
+ value: _Optional[_Union[GapicMetadata.ServiceForTransport, _Mapping]] = ...,
+ ) -> None: ...
+
+ class ServiceForTransport(_message.Message):
+ __slots__ = ("clients", "api_version")
+
+ class ClientsEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: GapicMetadata.ServiceAsClient
+ def __init__(
+ self,
+ key: _Optional[str] = ...,
+ value: _Optional[_Union[GapicMetadata.ServiceAsClient, _Mapping]] = ...,
+ ) -> None: ...
+
+ CLIENTS_FIELD_NUMBER: _ClassVar[int]
+ API_VERSION_FIELD_NUMBER: _ClassVar[int]
+ clients: _containers.MessageMap[str, GapicMetadata.ServiceAsClient]
+ api_version: str
+ def __init__(
+ self,
+ clients: _Optional[_Mapping[str, GapicMetadata.ServiceAsClient]] = ...,
+ api_version: _Optional[str] = ...,
+ ) -> None: ...
+
+ class ServiceAsClient(_message.Message):
+ __slots__ = ("library_client", "rpcs")
+
+ class RpcsEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: GapicMetadata.MethodList
+ def __init__(
+ self,
+ key: _Optional[str] = ...,
+ value: _Optional[_Union[GapicMetadata.MethodList, _Mapping]] = ...,
+ ) -> None: ...
+
+ LIBRARY_CLIENT_FIELD_NUMBER: _ClassVar[int]
+ RPCS_FIELD_NUMBER: _ClassVar[int]
+ library_client: str
+ rpcs: _containers.MessageMap[str, GapicMetadata.MethodList]
+ def __init__(
+ self,
+ library_client: _Optional[str] = ...,
+ rpcs: _Optional[_Mapping[str, GapicMetadata.MethodList]] = ...,
+ ) -> None: ...
+
+ class MethodList(_message.Message):
+ __slots__ = ("methods",)
+ METHODS_FIELD_NUMBER: _ClassVar[int]
+ methods: _containers.RepeatedScalarFieldContainer[str]
+ def __init__(self, methods: _Optional[_Iterable[str]] = ...) -> None: ...
+
+ SCHEMA_FIELD_NUMBER: _ClassVar[int]
+ COMMENT_FIELD_NUMBER: _ClassVar[int]
+ LANGUAGE_FIELD_NUMBER: _ClassVar[int]
+ PROTO_PACKAGE_FIELD_NUMBER: _ClassVar[int]
+ LIBRARY_PACKAGE_FIELD_NUMBER: _ClassVar[int]
+ SERVICES_FIELD_NUMBER: _ClassVar[int]
+ schema: str
+ comment: str
+ language: str
+ proto_package: str
+ library_package: str
+ services: _containers.MessageMap[str, GapicMetadata.ServiceForTransport]
+ def __init__(
+ self,
+ schema: _Optional[str] = ...,
+ comment: _Optional[str] = ...,
+ language: _Optional[str] = ...,
+ proto_package: _Optional[str] = ...,
+ library_package: _Optional[str] = ...,
+ services: _Optional[_Mapping[str, GapicMetadata.ServiceForTransport]] = ...,
+ ) -> None: ...
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5ccbdaad51f31131d2ad0f3bb9847e414b1bc38
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f365317dd6788612a3fdc4489c4265c7bf9612a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/constants.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_create.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_create.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba3880f790eafde8b181e7e46e95e69a49e371fc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_create.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_create_custom_url.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_create_custom_url.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa3cc16bad2596153f05bea14c2ea4dba0ef8357
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_create_custom_url.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_delete.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_delete.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..025d1d367fc7a27704c7d2b689785ed0d281f95d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_delete.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_get.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_get.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eee3b851798078f43b66db1290e7e8cf295a0a7f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_get.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_get_custom_url.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_get_custom_url.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cd4d844d996967e8e157179b24428675b567750
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_get_custom_url.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_list.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_list.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..685ad622ef5c4df23af061941a56d736fe2e68c2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_list.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_update.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_update.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e92f8afda141ab4611e2f8bb914ff30c9608ee5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_update.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_update_custom_url.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_update_custom_url.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc327f85f6f4dce5c06ba734c50193ccf03c6fb6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/caches/__pycache__/test_update_custom_url.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbf11e1ea9db099859b256962240f5c82a2f904c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_get_history.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_get_history.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da2d96ae6140a23fbd0376eccd0a61a12d6bdd38
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_get_history.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_send_message.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_send_message.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00865df41fb2f560d9d1c821b9dfd38056576b32
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_send_message.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_validate_response.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_validate_response.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..466e1f0ada5eef2b86f5246b891d1ff587d15521
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/chats/__pycache__/test_validate_response.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36669783d657aca709263bbfeddff5d804a8fc1f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_async_stream.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_async_stream.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5da5931a56558043043a73597c40caa380696a7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_async_stream.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_close.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_close.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef83ca0bfcc9893f9d9dcd3202f9ae2446a95c24
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_close.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_initialization.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_initialization.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99375725eefc7cc1265a39aa24e0780ec0c56c52
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_initialization.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_requests.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_requests.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..354b60ede0b28701264315ae201acf3cd7fccebc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_client_requests.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_custom_client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_custom_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a115fa3e1c6ef3d680f01dcf67fb38b5acb7e92c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_custom_client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_http_options.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_http_options.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0832141e643f134d9d778c441f76c04158df03a2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_http_options.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_replay_client_equality.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_replay_client_equality.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a84a397544c905662cc994e7a783d56809770fe4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_replay_client_equality.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_retries.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_retries.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b55b3251c6b589b767e9fdc3b80fd45b55c375da
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_retries.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_upload_errors.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_upload_errors.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b6ed129aa11e349446c210a09502be2ad29bc2e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/client/__pycache__/test_upload_errors.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/errors/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/errors/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..287b35321115b0f84bf31091a2f6facc425dc99d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/errors/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/errors/__pycache__/test_api_error.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/errors/__pycache__/test_api_error.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58039b1aa0c5b6d1b92b7d4bb60e40afdacd31bb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/errors/__pycache__/test_api_error.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a63b5b59dfb3115c2c6627559a9b8ab30b0371d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_delete.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_delete.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88695ab6dd450e4721be721f81257f715d8194ad
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_delete.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_download.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_download.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1cd4ee95ef90d26b99d8ca087bc946089164683
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_download.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_get.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_get.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8076789b608701c1e99a79f5cb9de5b1e26353fc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_get.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_list.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_list.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7c403ace630176675380068e8324586ab6b47f6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_list.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_register.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_register.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2dbc8607c088dd5c360f064d47459f2f56e7bc17
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_register.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_register_table.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_register_table.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..082b20fa229f1fc757adc52418dbfba5f010ed60
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_register_table.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_upload.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_upload.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..254b6490b24318d93fba761d7272f6ea8705d993
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/files/__pycache__/test_upload.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/imports/__pycache__/test_no_optional_imports.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/imports/__pycache__/test_no_optional_imports.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e1e5ff1ff48a94a3e640f5e5b76b54044ced1c3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/imports/__pycache__/test_no_optional_imports.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cad5b9c611a643af6dfac174931ab057f5b1c309
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_auth.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_auth.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..95d9a8dd9a9f59cdcb34a1c9fb668134ed26a450
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_auth.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_integration.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_integration.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c13d4e78ec36df721d50d82116ac0d3792a7b993
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_integration.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_paths.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_paths.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fcbebe0be1299dd97f66c9143ba4a93a26879c6e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/interactions/__pycache__/test_paths.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4214832ee2d795ae6d9ae03aee39a057e780778f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea1a80f20c8fc48dec5d11c7a436af534b53345f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer_loader.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer_loader.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b114a951dd64b8baa64be7e159b60e9419ba78d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer_loader.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc54f01341df9b33bfae71202438afb5a89b8e35
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd3cc4f1b108bf172b89bc86ae2ce6ccd2530063
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/constants.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_compute_tokens.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_compute_tokens.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e87b368d58a5750d9e801fffc7b1d71becec17e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_compute_tokens.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_count_tokens.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_count_tokens.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..272ba11b30c90eec50dce4e99b58318452100950
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_count_tokens.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_delete.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_delete.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd6a179f794020f59c37a113ab53e036c31ec79f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_delete.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_edit_image.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_edit_image.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..459508b3950cb19b9b9ed6206dc6d937d16e20d7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_edit_image.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_embed_content.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_embed_content.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eac985de72d3ba75a1a59589518ee9141c82d364
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_embed_content.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_function_call_streaming.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_function_call_streaming.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11b3141fe8c9ea9bab948a01ad7c3ff3b3323f7f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_function_call_streaming.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fc6a6c44e9552923c914a87d80425d04ef0cb1b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_cached_content.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_cached_content.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b0d469c90d5472a781fce6130ae084d06f5837e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_cached_content.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_config_zero_value.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_config_zero_value.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f82f4ebe5f0decdd13a355c4625f823fa9e5135
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_config_zero_value.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_from_apikey.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_from_apikey.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a7cee08dafd5d604faa8261dadb1a647be06bd3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_from_apikey.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_http_options.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_http_options.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4373a4603f538799a315a7713fabdd4baa0334d8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_http_options.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_image_generation.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_image_generation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a47ca96a2dda2e41613d0f0e0a01b3b97566209d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_image_generation.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_mcp.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_mcp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..08e7e9728314a5e3192080059163622d969e221f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_mcp.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_media_resolution.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_media_resolution.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6189c0d101ce68833fbd5ecf84521b78edb4c9af
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_media_resolution.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_model.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_model.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..177bde99c2f9da9ad40ed21f2e599ec051f64885
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_model.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_part.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_part.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e82eda52e22a838a12d66203a6baf9673f4bb3f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_part.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_thought.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_thought.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53602ddd7b2a3a395b16b9a58ebe1fc88b0fcdd6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_thought.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_tools.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_tools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53bbd29fb92b94ce70e8c614305ebfd408d55d7d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_content_tools.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_images.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_images.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94ead56fd633c73a9b9ac59dce60dee38ce0ebcb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_images.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_videos.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_videos.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffb3eda4fbec05d38fa9ad30f2662d7af2872c63
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_generate_videos.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_get.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_get.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ffef23ef3a2103917ae4f90f44f720277805ffa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_get.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_list.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_list.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7582a41d07619f0988e97d6e0210caec7e602972
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_list.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_recontext_image.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_recontext_image.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b71e44431e3593b24e05d5eb3239695d7fc9c17d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_recontext_image.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_segment_image.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_segment_image.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b158feeba1e067bf3334f0c9c8b89393acc5d7a7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_segment_image.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_update.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_update.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26f4e321b62149692831d2c39295196bb55a0294
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_update.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_upscale_image.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_upscale_image.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01374af140b33ffff08b988f7b5e43ab5f7fa13f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/models/__pycache__/test_upscale_image.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/operations/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/operations/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69e149f8da86fc94f5c22d8ed9af71dd26c9af57
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/operations/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/operations/__pycache__/test_get.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/operations/__pycache__/test_get.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1390408e762d9b6148d9da80ceb52dba6f2853cc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/operations/__pycache__/test_get.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/tokens/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/tokens/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7293d27c6a3042de3e2e5f7ecf17a42bec906032
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/tokens/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/tokens/__pycache__/test_create.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/tokens/__pycache__/test_create.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f5e25cdbaee7fa8a275fea256022353faca191d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/tokens/__pycache__/test_create.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ed5e056708ce19203b360e72f2858b17c34ac29
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_blobs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_blobs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8795cc9e5fcd7f0dc4aa1410c653cd938e3f6652
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_blobs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_bytes.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_bytes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27bac22b187b3da6566b150b5c3c2be6d158849b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_bytes.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_function_responses.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_function_responses.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45f9edacb609bf8329e6b5614619b8f869effb24
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_function_responses.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04d4fe2122f621ce93433ec1159193eea77114df
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_schema.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_batch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_batch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d28408aa5e10aeb7a3fa642d902eec96d408aded
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_batch.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_content.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_content.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f9dd9e01440066e01e60671cabc1696c71a47ab
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_content.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_contents.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_contents.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..396a9723a8a3712aa8c86b413d03fee8e05a5d9d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_contents.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_part.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_part.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4743cb4ba891e050e78b0a8831315304ac322d60
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_part.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_parts.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_parts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8737eac60a254d2f71d7ea25d52762d97233c813
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_parts.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_tool.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_tool.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f571b7de7e52c92596e1f367c957ae92c813d2a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_tool.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_tools.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_tools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f83cad03c60a09ce6fce6f2e6c149e7131c1e924
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/transformers/__pycache__/test_t_tools.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce1be071a7525df7a4b3f51dd2a41629f37b238e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_bytes_internal.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_bytes_internal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40cbfdf81560bb2402007c8f6bd3b1d8a985a086
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_bytes_internal.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_bytes_type.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_bytes_type.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cf59a86bdbac6f767d7044117f3b0e943d43646
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_bytes_type.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_future.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_future.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d16d690e1d61bc2fc192f4cde3b4d4a7aff2547d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_future.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_optional_types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_optional_types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53f5ec83a33ebfb4f5f1368c27060a76c26dff02
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_optional_types.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_part_type.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_part_type.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cda817c274732a7779cc05755e59c3e4a829406
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_part_type.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_schema_from_json_schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_schema_from_json_schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e1fc3b9806c49998a4f50dad49bc4f4df2bf0ab
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_schema_from_json_schema.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_schema_json_schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_schema_json_schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d18653daef53c992eb6e76aa0f067fcb23afcaa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/genai/tests/types/__pycache__/test_schema_json_schema.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/__pycache__/http_request_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/__pycache__/http_request_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c41de202c57d138a33409d1f243b67aefce2899
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/__pycache__/http_request_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/__pycache__/log_severity_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/__pycache__/log_severity_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..154099753f3c107858556c8885e70830e6605f4c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/__pycache__/log_severity_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request.proto b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request.proto
new file mode 100644
index 0000000000000000000000000000000000000000..b31522b69c7c292d855bb806cc80aa7b1b57362b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request.proto
@@ -0,0 +1,95 @@
+// Copyright 2025 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto3";
+
+package google.logging.type;
+
+import "google/protobuf/duration.proto";
+
+option csharp_namespace = "Google.Cloud.Logging.Type";
+option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype";
+option java_multiple_files = true;
+option java_outer_classname = "HttpRequestProto";
+option java_package = "com.google.logging.type";
+option php_namespace = "Google\\Cloud\\Logging\\Type";
+option ruby_package = "Google::Cloud::Logging::Type";
+
+// A common proto for logging HTTP requests. Only contains semantics
+// defined by the HTTP specification. Product-specific logging
+// information MUST be defined in a separate message.
+message HttpRequest {
+ // The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`.
+ string request_method = 1;
+
+ // The scheme (http, https), the host name, the path and the query
+ // portion of the URL that was requested.
+ // Example: `"http://example.com/some/info?color=red"`.
+ string request_url = 2;
+
+ // The size of the HTTP request message in bytes, including the request
+ // headers and the request body.
+ int64 request_size = 3;
+
+ // The response code indicating the status of response.
+ // Examples: 200, 404.
+ int32 status = 4;
+
+ // The size of the HTTP response message sent back to the client, in bytes,
+ // including the response headers and the response body.
+ int64 response_size = 5;
+
+ // The user agent sent by the client. Example:
+ // `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET
+ // CLR 1.0.3705)"`.
+ string user_agent = 6;
+
+ // The IP address (IPv4 or IPv6) of the client that issued the HTTP
+ // request. This field can include port information. Examples:
+ // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`.
+ string remote_ip = 7;
+
+ // The IP address (IPv4 or IPv6) of the origin server that the request was
+ // sent to. This field can include port information. Examples:
+ // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`.
+ string server_ip = 13;
+
+ // The referer URL of the request, as defined in
+ // [HTTP/1.1 Header Field
+ // Definitions](https://datatracker.ietf.org/doc/html/rfc2616#section-14.36).
+ string referer = 8;
+
+ // The request processing latency on the server, from the time the request was
+ // received until the response was sent.
+ google.protobuf.Duration latency = 14;
+
+ // Whether or not a cache lookup was attempted.
+ bool cache_lookup = 11;
+
+ // Whether or not an entity was served from cache
+ // (with or without validation).
+ bool cache_hit = 9;
+
+ // Whether or not the response was validated with the origin server before
+ // being served from cache. This field is only meaningful if `cache_hit` is
+ // True.
+ bool cache_validated_with_origin_server = 10;
+
+ // The number of HTTP response bytes inserted into cache. Set only when a
+ // cache fill was attempted.
+ int64 cache_fill_bytes = 12;
+
+ // Protocol used for the request. Examples: "HTTP/1.1", "HTTP/2", "websocket"
+ string protocol = 15;
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request_pb2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..521a91f1e9afff03f6097be8f2ed8c80ee2daea9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request_pb2.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/logging/type/http_request.proto
+# Protobuf Python Version: 4.25.3
+"""Generated protocol buffer code."""
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b'\n&google/logging/type/http_request.proto\x12\x13google.logging.type\x1a\x1egoogle/protobuf/duration.proto"\xef\x02\n\x0bHttpRequest\x12\x16\n\x0erequest_method\x18\x01 \x01(\t\x12\x13\n\x0brequest_url\x18\x02 \x01(\t\x12\x14\n\x0crequest_size\x18\x03 \x01(\x03\x12\x0e\n\x06status\x18\x04 \x01(\x05\x12\x15\n\rresponse_size\x18\x05 \x01(\x03\x12\x12\n\nuser_agent\x18\x06 \x01(\t\x12\x11\n\tremote_ip\x18\x07 \x01(\t\x12\x11\n\tserver_ip\x18\r \x01(\t\x12\x0f\n\x07referer\x18\x08 \x01(\t\x12*\n\x07latency\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x14\n\x0c\x63\x61\x63he_lookup\x18\x0b \x01(\x08\x12\x11\n\tcache_hit\x18\t \x01(\x08\x12*\n"cache_validated_with_origin_server\x18\n \x01(\x08\x12\x18\n\x10\x63\x61\x63he_fill_bytes\x18\x0c \x01(\x03\x12\x10\n\x08protocol\x18\x0f \x01(\tB\xbe\x01\n\x17\x63om.google.logging.typeB\x10HttpRequestProtoP\x01Z8google.golang.org/genproto/googleapis/logging/type;ltype\xaa\x02\x19Google.Cloud.Logging.Type\xca\x02\x19Google\\Cloud\\Logging\\Type\xea\x02\x1cGoogle::Cloud::Logging::Typeb\x06proto3'
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(
+ DESCRIPTOR, "google.logging.type.http_request_pb2", _globals
+)
+if _descriptor._USE_C_DESCRIPTORS == False:
+ _globals["DESCRIPTOR"]._options = None
+ _globals[
+ "DESCRIPTOR"
+ ]._serialized_options = b"\n\027com.google.logging.typeB\020HttpRequestProtoP\001Z8google.golang.org/genproto/googleapis/logging/type;ltype\252\002\031Google.Cloud.Logging.Type\312\002\031Google\\Cloud\\Logging\\Type\352\002\034Google::Cloud::Logging::Type"
+ _globals["_HTTPREQUEST"]._serialized_start = 96
+ _globals["_HTTPREQUEST"]._serialized_end = 463
+# @@protoc_insertion_point(module_scope)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request_pb2.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request_pb2.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..b808ded1359f6c9b5722ef553a923efa59761ef5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/http_request_pb2.pyi
@@ -0,0 +1,91 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import ClassVar as _ClassVar
+from typing import Mapping as _Mapping
+from typing import Optional as _Optional
+from typing import Union as _Union
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import duration_pb2 as _duration_pb2
+from google.protobuf import message as _message
+
+DESCRIPTOR: _descriptor.FileDescriptor
+
+class HttpRequest(_message.Message):
+ __slots__ = (
+ "request_method",
+ "request_url",
+ "request_size",
+ "status",
+ "response_size",
+ "user_agent",
+ "remote_ip",
+ "server_ip",
+ "referer",
+ "latency",
+ "cache_lookup",
+ "cache_hit",
+ "cache_validated_with_origin_server",
+ "cache_fill_bytes",
+ "protocol",
+ )
+ REQUEST_METHOD_FIELD_NUMBER: _ClassVar[int]
+ REQUEST_URL_FIELD_NUMBER: _ClassVar[int]
+ REQUEST_SIZE_FIELD_NUMBER: _ClassVar[int]
+ STATUS_FIELD_NUMBER: _ClassVar[int]
+ RESPONSE_SIZE_FIELD_NUMBER: _ClassVar[int]
+ USER_AGENT_FIELD_NUMBER: _ClassVar[int]
+ REMOTE_IP_FIELD_NUMBER: _ClassVar[int]
+ SERVER_IP_FIELD_NUMBER: _ClassVar[int]
+ REFERER_FIELD_NUMBER: _ClassVar[int]
+ LATENCY_FIELD_NUMBER: _ClassVar[int]
+ CACHE_LOOKUP_FIELD_NUMBER: _ClassVar[int]
+ CACHE_HIT_FIELD_NUMBER: _ClassVar[int]
+ CACHE_VALIDATED_WITH_ORIGIN_SERVER_FIELD_NUMBER: _ClassVar[int]
+ CACHE_FILL_BYTES_FIELD_NUMBER: _ClassVar[int]
+ PROTOCOL_FIELD_NUMBER: _ClassVar[int]
+ request_method: str
+ request_url: str
+ request_size: int
+ status: int
+ response_size: int
+ user_agent: str
+ remote_ip: str
+ server_ip: str
+ referer: str
+ latency: _duration_pb2.Duration
+ cache_lookup: bool
+ cache_hit: bool
+ cache_validated_with_origin_server: bool
+ cache_fill_bytes: int
+ protocol: str
+ def __init__(
+ self,
+ request_method: _Optional[str] = ...,
+ request_url: _Optional[str] = ...,
+ request_size: _Optional[int] = ...,
+ status: _Optional[int] = ...,
+ response_size: _Optional[int] = ...,
+ user_agent: _Optional[str] = ...,
+ remote_ip: _Optional[str] = ...,
+ server_ip: _Optional[str] = ...,
+ referer: _Optional[str] = ...,
+ latency: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ...,
+ cache_lookup: bool = ...,
+ cache_hit: bool = ...,
+ cache_validated_with_origin_server: bool = ...,
+ cache_fill_bytes: _Optional[int] = ...,
+ protocol: _Optional[str] = ...,
+ ) -> None: ...
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity.proto b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity.proto
new file mode 100644
index 0000000000000000000000000000000000000000..406b8173a3aa056d8dab749db0ae731811d681c1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity.proto
@@ -0,0 +1,71 @@
+// Copyright 2025 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto3";
+
+package google.logging.type;
+
+option csharp_namespace = "Google.Cloud.Logging.Type";
+option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype";
+option java_multiple_files = true;
+option java_outer_classname = "LogSeverityProto";
+option java_package = "com.google.logging.type";
+option objc_class_prefix = "GLOG";
+option php_namespace = "Google\\Cloud\\Logging\\Type";
+option ruby_package = "Google::Cloud::Logging::Type";
+
+// The severity of the event described in a log entry, expressed as one of the
+// standard severity levels listed below. For your reference, the levels are
+// assigned the listed numeric values. The effect of using numeric values other
+// than those listed is undefined.
+//
+// You can filter for log entries by severity. For example, the following
+// filter expression will match log entries with severities `INFO`, `NOTICE`,
+// and `WARNING`:
+//
+// severity > DEBUG AND severity <= WARNING
+//
+// If you are writing log entries, you should map other severity encodings to
+// one of these standard levels. For example, you might map all of Java's FINE,
+// FINER, and FINEST levels to `LogSeverity.DEBUG`. You can preserve the
+// original severity level in the log entry payload if you wish.
+enum LogSeverity {
+ // (0) The log entry has no assigned severity level.
+ DEFAULT = 0;
+
+ // (100) Debug or trace information.
+ DEBUG = 100;
+
+ // (200) Routine information, such as ongoing status or performance.
+ INFO = 200;
+
+ // (300) Normal but significant events, such as start up, shut down, or
+ // a configuration change.
+ NOTICE = 300;
+
+ // (400) Warning events might cause problems.
+ WARNING = 400;
+
+ // (500) Error events are likely to cause problems.
+ ERROR = 500;
+
+ // (600) Critical events cause more severe problems or outages.
+ CRITICAL = 600;
+
+ // (700) A person must take an action immediately.
+ ALERT = 700;
+
+ // (800) One or more systems are unusable.
+ EMERGENCY = 800;
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity_pb2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..67958a4084ca9206c55e8b62efb78ef4b22e33be
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity_pb2.py
@@ -0,0 +1,48 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/logging/type/log_severity.proto
+# Protobuf Python Version: 4.25.3
+"""Generated protocol buffer code."""
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b"\n&google/logging/type/log_severity.proto\x12\x13google.logging.type*\x82\x01\n\x0bLogSeverity\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x00\x12\t\n\x05\x44\x45\x42UG\x10\x64\x12\t\n\x04INFO\x10\xc8\x01\x12\x0b\n\x06NOTICE\x10\xac\x02\x12\x0c\n\x07WARNING\x10\x90\x03\x12\n\n\x05\x45RROR\x10\xf4\x03\x12\r\n\x08\x43RITICAL\x10\xd8\x04\x12\n\n\x05\x41LERT\x10\xbc\x05\x12\x0e\n\tEMERGENCY\x10\xa0\x06\x42\xc5\x01\n\x17\x63om.google.logging.typeB\x10LogSeverityProtoP\x01Z8google.golang.org/genproto/googleapis/logging/type;ltype\xa2\x02\x04GLOG\xaa\x02\x19Google.Cloud.Logging.Type\xca\x02\x19Google\\Cloud\\Logging\\Type\xea\x02\x1cGoogle::Cloud::Logging::Typeb\x06proto3"
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(
+ DESCRIPTOR, "google.logging.type.log_severity_pb2", _globals
+)
+if _descriptor._USE_C_DESCRIPTORS == False:
+ _globals["DESCRIPTOR"]._options = None
+ _globals[
+ "DESCRIPTOR"
+ ]._serialized_options = b"\n\027com.google.logging.typeB\020LogSeverityProtoP\001Z8google.golang.org/genproto/googleapis/logging/type;ltype\242\002\004GLOG\252\002\031Google.Cloud.Logging.Type\312\002\031Google\\Cloud\\Logging\\Type\352\002\034Google::Cloud::Logging::Type"
+ _globals["_LOGSEVERITY"]._serialized_start = 64
+ _globals["_LOGSEVERITY"]._serialized_end = 194
+# @@protoc_insertion_point(module_scope)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity_pb2.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity_pb2.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..eeafb8ed88df6bb1c6012341973a172fc2d90165
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/logging/type/log_severity_pb2.pyi
@@ -0,0 +1,42 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import ClassVar as _ClassVar
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
+
+DESCRIPTOR: _descriptor.FileDescriptor
+
+class LogSeverity(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
+ __slots__ = ()
+ DEFAULT: _ClassVar[LogSeverity]
+ DEBUG: _ClassVar[LogSeverity]
+ INFO: _ClassVar[LogSeverity]
+ NOTICE: _ClassVar[LogSeverity]
+ WARNING: _ClassVar[LogSeverity]
+ ERROR: _ClassVar[LogSeverity]
+ CRITICAL: _ClassVar[LogSeverity]
+ ALERT: _ClassVar[LogSeverity]
+ EMERGENCY: _ClassVar[LogSeverity]
+
+DEFAULT: LogSeverity
+DEBUG: LogSeverity
+INFO: LogSeverity
+NOTICE: LogSeverity
+WARNING: LogSeverity
+ERROR: LogSeverity
+CRITICAL: LogSeverity
+ALERT: LogSeverity
+EMERGENCY: LogSeverity
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_grpc.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_grpc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b6de9d4aa2d61f16a63448ad2ff3a79c24daec2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_grpc.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff7af5b166503d249271abca74164ac1a626f4a5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb062d38149cb4fd93c879bf8db51d159481de03
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73507aa89f42c2ecc5f9332c9a9a5501d0760c1c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_proto.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_proto.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c113d6119dadaed4f5bcad94cf5dacc9ba370547
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_proto.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4586d8bb1d61ce21fce22e5d38a87201dfb9bdf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/code_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/code_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a24698d3d3cd33db7beefd6d31cef3924ec4f587
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/code_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d85b9a0ea54977138170819934597de6c45a7123
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/http_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/http_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c16bdc5400132a87492bdf3b3a2f0c293564021
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/http_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/status_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/status_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..849eab962d505edac49d810dffd6688dbf8459e0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/__pycache__/status_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/__pycache__/attribute_context_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/__pycache__/attribute_context_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c632d7cdb392ee6eb1439da7cf6b034d296f916
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/__pycache__/attribute_context_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/__pycache__/audit_context_pb2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/__pycache__/audit_context_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb2054e8d62ffcf5f5e6f405ce1892fdbc54efa4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/__pycache__/audit_context_pb2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context.proto b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context.proto
new file mode 100644
index 0000000000000000000000000000000000000000..55f95f844e74ac98185515a9f84cff941d8de188
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context.proto
@@ -0,0 +1,350 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto3";
+
+package google.rpc.context;
+
+import "google/protobuf/any.proto";
+import "google/protobuf/duration.proto";
+import "google/protobuf/struct.proto";
+import "google/protobuf/timestamp.proto";
+
+option go_package = "google.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_context";
+option java_multiple_files = true;
+option java_outer_classname = "AttributeContextProto";
+option java_package = "com.google.rpc.context";
+
+// This message defines the standard attribute vocabulary for Google APIs.
+//
+// An attribute is a piece of metadata that describes an activity on a network
+// service. For example, the size of an HTTP request, or the status code of
+// an HTTP response.
+//
+// Each attribute has a type and a name, which is logically defined as
+// a proto message field in `AttributeContext`. The field type becomes the
+// attribute type, and the field path becomes the attribute name. For example,
+// the attribute `source.ip` maps to field `AttributeContext.source.ip`.
+//
+// This message definition is guaranteed not to have any wire breaking change.
+// So you can use it directly for passing attributes across different systems.
+//
+// NOTE: Different system may generate different subset of attributes. Please
+// verify the system specification before relying on an attribute generated
+// a system.
+message AttributeContext {
+ // This message defines attributes for a node that handles a network request.
+ // The node can be either a service or an application that sends, forwards,
+ // or receives the request. Service peers should fill in
+ // `principal` and `labels` as appropriate.
+ message Peer {
+ // The IP address of the peer.
+ string ip = 1;
+
+ // The network port of the peer.
+ int64 port = 2;
+
+ // The labels associated with the peer.
+ map labels = 6;
+
+ // The identity of this peer. Similar to `Request.auth.principal`, but
+ // relative to the peer instead of the request. For example, the
+ // identity associated with a load balancer that forwarded the request.
+ string principal = 7;
+
+ // The CLDR country/region code associated with the above IP address.
+ // If the IP address is private, the `region_code` should reflect the
+ // physical location where this peer is running.
+ string region_code = 8;
+ }
+
+ // This message defines attributes associated with API operations, such as
+ // a network API request. The terminology is based on the conventions used
+ // by Google APIs, Istio, and OpenAPI.
+ message Api {
+ // The API service name. It is a logical identifier for a networked API,
+ // such as "pubsub.googleapis.com". The naming syntax depends on the
+ // API management system being used for handling the request.
+ string service = 1;
+
+ // The API operation name. For gRPC requests, it is the fully qualified API
+ // method name, such as "google.pubsub.v1.Publisher.Publish". For OpenAPI
+ // requests, it is the `operationId`, such as "getPet".
+ string operation = 2;
+
+ // The API protocol used for sending the request, such as "http", "https",
+ // "grpc", or "internal".
+ string protocol = 3;
+
+ // The API version associated with the API operation above, such as "v1" or
+ // "v1alpha1".
+ string version = 4;
+ }
+
+ // This message defines request authentication attributes. Terminology is
+ // based on the JSON Web Token (JWT) standard, but the terms also
+ // correlate to concepts in other standards.
+ message Auth {
+ // The authenticated principal. Reflects the issuer (`iss`) and subject
+ // (`sub`) claims within a JWT. The issuer and subject should be `/`
+ // delimited, with `/` percent-encoded within the subject fragment. For
+ // Google accounts, the principal format is:
+ // "https://accounts.google.com/{id}"
+ string principal = 1;
+
+ // The intended audience(s) for this authentication information. Reflects
+ // the audience (`aud`) claim within a JWT. The audience
+ // value(s) depends on the `issuer`, but typically include one or more of
+ // the following pieces of information:
+ //
+ // * The services intended to receive the credential. For example,
+ // ["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"].
+ // * A set of service-based scopes. For example,
+ // ["https://www.googleapis.com/auth/cloud-platform"].
+ // * The client id of an app, such as the Firebase project id for JWTs
+ // from Firebase Auth.
+ //
+ // Consult the documentation for the credential issuer to determine the
+ // information provided.
+ repeated string audiences = 2;
+
+ // The authorized presenter of the credential. Reflects the optional
+ // Authorized Presenter (`azp`) claim within a JWT or the
+ // OAuth client id. For example, a Google Cloud Platform client id looks
+ // as follows: "123456789012.apps.googleusercontent.com".
+ string presenter = 3;
+
+ // Structured claims presented with the credential. JWTs include
+ // `{key: value}` pairs for standard and private claims. The following
+ // is a subset of the standard required and optional claims that would
+ // typically be presented for a Google-based JWT:
+ //
+ // {'iss': 'accounts.google.com',
+ // 'sub': '113289723416554971153',
+ // 'aud': ['123456789012', 'pubsub.googleapis.com'],
+ // 'azp': '123456789012.apps.googleusercontent.com',
+ // 'email': 'jsmith@example.com',
+ // 'iat': 1353601026,
+ // 'exp': 1353604926}
+ //
+ // SAML assertions are similarly specified, but with an identity provider
+ // dependent structure.
+ google.protobuf.Struct claims = 4;
+
+ // A list of access level resource names that allow resources to be
+ // accessed by authenticated requester. It is part of Secure GCP processing
+ // for the incoming request. An access level string has the format:
+ // "//{api_service_name}/accessPolicies/{policy_id}/accessLevels/{short_name}"
+ //
+ // Example:
+ // "//accesscontextmanager.googleapis.com/accessPolicies/MY_POLICY_ID/accessLevels/MY_LEVEL"
+ repeated string access_levels = 5;
+ }
+
+ // This message defines attributes for an HTTP request. If the actual
+ // request is not an HTTP request, the runtime system should try to map
+ // the actual request to an equivalent HTTP request.
+ message Request {
+ // The unique ID for a request, which can be propagated to downstream
+ // systems. The ID should have low probability of collision
+ // within a single day for a specific service.
+ string id = 1;
+
+ // The HTTP request method, such as `GET`, `POST`.
+ string method = 2;
+
+ // The HTTP request headers. If multiple headers share the same key, they
+ // must be merged according to the HTTP spec. All header keys must be
+ // lowercased, because HTTP header keys are case-insensitive.
+ map headers = 3;
+
+ // The HTTP URL path, excluding the query parameters.
+ string path = 4;
+
+ // The HTTP request `Host` header value.
+ string host = 5;
+
+ // The HTTP URL scheme, such as `http` and `https`.
+ string scheme = 6;
+
+ // The HTTP URL query in the format of `name1=value1&name2=value2`, as it
+ // appears in the first line of the HTTP request. No decoding is performed.
+ string query = 7;
+
+ // The timestamp when the `destination` service receives the last byte of
+ // the request.
+ google.protobuf.Timestamp time = 9;
+
+ // The HTTP request size in bytes. If unknown, it must be -1.
+ int64 size = 10;
+
+ // The network protocol used with the request, such as "http/1.1",
+ // "spdy/3", "h2", "h2c", "webrtc", "tcp", "udp", "quic". See
+ // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
+ // for details.
+ string protocol = 11;
+
+ // A special parameter for request reason. It is used by security systems
+ // to associate auditing information with a request.
+ string reason = 12;
+
+ // The request authentication. May be absent for unauthenticated requests.
+ // Derived from the HTTP request `Authorization` header or equivalent.
+ Auth auth = 13;
+
+ // The values from Origin header from the HTTP request, such as
+ // "https://console.cloud.google.com". Modern browsers can only have one
+ // origin. Special browsers and/or HTTP clients may require multiple
+ // origins.
+ string origin = 14;
+ }
+
+ // This message defines attributes for a typical network response. It
+ // generally models semantics of an HTTP response.
+ message Response {
+ // The HTTP response status code, such as `200` and `404`.
+ int64 code = 1;
+
+ // The HTTP response size in bytes. If unknown, it must be -1.
+ int64 size = 2;
+
+ // The HTTP response headers. If multiple headers share the same key, they
+ // must be merged according to HTTP spec. All header keys must be
+ // lowercased, because HTTP header keys are case-insensitive.
+ map headers = 3;
+
+ // The timestamp when the `destination` service sends the last byte of
+ // the response.
+ google.protobuf.Timestamp time = 4;
+
+ // The amount of time it takes the backend service to fully respond to a
+ // request. Measured from when the destination service starts to send the
+ // request to the backend until when the destination service receives the
+ // complete response from the backend.
+ google.protobuf.Duration backend_latency = 5;
+ }
+
+ // This message defines core attributes for a resource. A resource is an
+ // addressable (named) entity provided by the destination service. For
+ // example, a file stored on a network storage service.
+ message Resource {
+ // The name of the service that this resource belongs to, such as
+ // `pubsub.googleapis.com`. The service may be different from the DNS
+ // hostname that actually serves the request.
+ string service = 1;
+
+ // The stable identifier (name) of a resource on the `service`. A resource
+ // can be logically identified as "//{resource.service}/{resource.name}".
+ // The differences between a resource name and a URI are:
+ //
+ // * Resource name is a logical identifier, independent of network
+ // protocol and API version. For example,
+ // `//pubsub.googleapis.com/projects/123/topics/news-feed`.
+ // * URI often includes protocol and version information, so it can
+ // be used directly by applications. For example,
+ // `https://pubsub.googleapis.com/v1/projects/123/topics/news-feed`.
+ //
+ // See https://cloud.google.com/apis/design/resource_names for details.
+ string name = 2;
+
+ // The type of the resource. The syntax is platform-specific because
+ // different platforms define their resources differently.
+ //
+ // For Google APIs, the type format must be "{service}/{kind}", such as
+ // "pubsub.googleapis.com/Topic".
+ string type = 3;
+
+ // The labels or tags on the resource, such as AWS resource tags and
+ // Kubernetes resource labels.
+ map labels = 4;
+
+ // The unique identifier of the resource. UID is unique in the time
+ // and space for this resource within the scope of the service. It is
+ // typically generated by the server on successful creation of a resource
+ // and must not be changed. UID is used to uniquely identify resources
+ // with resource name reuses. This should be a UUID4.
+ string uid = 5;
+
+ // Annotations is an unstructured key-value map stored with a resource that
+ // may be set by external tools to store and retrieve arbitrary metadata.
+ // They are not queryable and should be preserved when modifying objects.
+ //
+ // More info:
+ // https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/
+ map annotations = 6;
+
+ // Mutable. The display name set by clients. Must be <= 63 characters.
+ string display_name = 7;
+
+ // Output only. The timestamp when the resource was created. This may
+ // be either the time creation was initiated or when it was completed.
+ google.protobuf.Timestamp create_time = 8;
+
+ // Output only. The timestamp when the resource was last updated. Any
+ // change to the resource made by users must refresh this value.
+ // Changes to a resource made by the service should refresh this value.
+ google.protobuf.Timestamp update_time = 9;
+
+ // Output only. The timestamp when the resource was deleted.
+ // If the resource is not deleted, this must be empty.
+ google.protobuf.Timestamp delete_time = 10;
+
+ // Output only. An opaque value that uniquely identifies a version or
+ // generation of a resource. It can be used to confirm that the client
+ // and server agree on the ordering of a resource being written.
+ string etag = 11;
+
+ // Immutable. The location of the resource. The location encoding is
+ // specific to the service provider, and new encoding may be introduced
+ // as the service evolves.
+ //
+ // For Google Cloud products, the encoding is what is used by Google Cloud
+ // APIs, such as `us-east1`, `aws-us-east-1`, and `azure-eastus2`. The
+ // semantics of `location` is identical to the
+ // `cloud.googleapis.com/location` label used by some Google Cloud APIs.
+ string location = 12;
+ }
+
+ // The origin of a network activity. In a multi hop network activity,
+ // the origin represents the sender of the first hop. For the first hop,
+ // the `source` and the `origin` must have the same content.
+ Peer origin = 7;
+
+ // The source of a network activity, such as starting a TCP connection.
+ // In a multi hop network activity, the source represents the sender of the
+ // last hop.
+ Peer source = 1;
+
+ // The destination of a network activity, such as accepting a TCP connection.
+ // In a multi hop network activity, the destination represents the receiver of
+ // the last hop.
+ Peer destination = 2;
+
+ // Represents a network request, such as an HTTP request.
+ Request request = 3;
+
+ // Represents a network response, such as an HTTP response.
+ Response response = 4;
+
+ // Represents a target resource that is involved with a network activity.
+ // If multiple resources are involved with an activity, this must be the
+ // primary one.
+ Resource resource = 5;
+
+ // Represents an API operation that is involved to a network activity.
+ Api api = 6;
+
+ // Supports extensions for advanced use cases, such as logs and metrics.
+ repeated google.protobuf.Any extensions = 8;
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context_pb2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d1064fb76f61fde3bd9f6260134b408fcc9777f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context_pb2.py
@@ -0,0 +1,87 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/rpc/context/attribute_context.proto
+# Protobuf Python Version: 4.25.3
+"""Generated protocol buffer code."""
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2
+from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2
+from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
+from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b"\n*google/rpc/context/attribute_context.proto\x12\x12google.rpc.context\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x93\x10\n\x10\x41ttributeContext\x12\x39\n\x06origin\x18\x07 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12\x39\n\x06source\x18\x01 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12>\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12=\n\x07request\x18\x03 \x01(\x0b\x32,.google.rpc.context.AttributeContext.Request\x12?\n\x08response\x18\x04 \x01(\x0b\x32-.google.rpc.context.AttributeContext.Response\x12?\n\x08resource\x18\x05 \x01(\x0b\x32-.google.rpc.context.AttributeContext.Resource\x12\x35\n\x03\x61pi\x18\x06 \x01(\x0b\x32(.google.rpc.context.AttributeContext.Api\x12(\n\nextensions\x18\x08 \x03(\x0b\x32\x14.google.protobuf.Any\x1a\xbe\x01\n\x04Peer\x12\n\n\x02ip\x18\x01 \x01(\t\x12\x0c\n\x04port\x18\x02 \x01(\x03\x12\x45\n\x06labels\x18\x06 \x03(\x0b\x32\x35.google.rpc.context.AttributeContext.Peer.LabelsEntry\x12\x11\n\tprincipal\x18\x07 \x01(\t\x12\x13\n\x0bregion_code\x18\x08 \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1aL\n\x03\x41pi\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x11\n\toperation\x18\x02 \x01(\t\x12\x10\n\x08protocol\x18\x03 \x01(\t\x12\x0f\n\x07version\x18\x04 \x01(\t\x1a\x7f\n\x04\x41uth\x12\x11\n\tprincipal\x18\x01 \x01(\t\x12\x11\n\taudiences\x18\x02 \x03(\t\x12\x11\n\tpresenter\x18\x03 \x01(\t\x12'\n\x06\x63laims\x18\x04 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x15\n\raccess_levels\x18\x05 \x03(\t\x1a\xff\x02\n\x07Request\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0e\n\x06method\x18\x02 \x01(\t\x12J\n\x07headers\x18\x03 \x03(\x0b\x32\x39.google.rpc.context.AttributeContext.Request.HeadersEntry\x12\x0c\n\x04path\x18\x04 \x01(\t\x12\x0c\n\x04host\x18\x05 \x01(\t\x12\x0e\n\x06scheme\x18\x06 \x01(\t\x12\r\n\x05query\x18\x07 \x01(\t\x12(\n\x04time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04size\x18\n \x01(\x03\x12\x10\n\x08protocol\x18\x0b \x01(\t\x12\x0e\n\x06reason\x18\x0c \x01(\t\x12\x37\n\x04\x61uth\x18\r \x01(\x0b\x32).google.rpc.context.AttributeContext.Auth\x12\x0e\n\x06origin\x18\x0e \x01(\t\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x81\x02\n\x08Response\x12\x0c\n\x04\x63ode\x18\x01 \x01(\x03\x12\x0c\n\x04size\x18\x02 \x01(\x03\x12K\n\x07headers\x18\x03 \x03(\x0b\x32:.google.rpc.context.AttributeContext.Response.HeadersEntry\x12(\n\x04time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x32\n\x0f\x62\x61\x63kend_latency\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x90\x04\n\x08Resource\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04type\x18\x03 \x01(\t\x12I\n\x06labels\x18\x04 \x03(\x0b\x32\x39.google.rpc.context.AttributeContext.Resource.LabelsEntry\x12\x0b\n\x03uid\x18\x05 \x01(\t\x12S\n\x0b\x61nnotations\x18\x06 \x03(\x0b\x32>.google.rpc.context.AttributeContext.Resource.AnnotationsEntry\x12\x14\n\x0c\x64isplay_name\x18\x07 \x01(\t\x12/\n\x0b\x63reate_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x64\x65lete_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04\x65tag\x18\x0b \x01(\t\x12\x10\n\x08location\x18\x0c \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x32\n\x10\x41nnotationsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x88\x01\n\x16\x63om.google.rpc.contextB\x15\x41ttributeContextProtoP\x01ZUgoogle.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_contextb\x06proto3"
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(
+ DESCRIPTOR, "google.rpc.context.attribute_context_pb2", _globals
+)
+if _descriptor._USE_C_DESCRIPTORS == False:
+ _globals["DESCRIPTOR"]._options = None
+ _globals[
+ "DESCRIPTOR"
+ ]._serialized_options = b"\n\026com.google.rpc.contextB\025AttributeContextProtoP\001ZUgoogle.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_context"
+ _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._options = None
+ _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_options = b"8\001"
+ _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._options = None
+ _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_options = b"8\001"
+ _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._options = None
+ _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_options = b"8\001"
+ _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._options = None
+ _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_options = b"8\001"
+ _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._options = None
+ _globals[
+ "_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"
+ ]._serialized_options = b"8\001"
+ _globals["_ATTRIBUTECONTEXT"]._serialized_start = 189
+ _globals["_ATTRIBUTECONTEXT"]._serialized_end = 2256
+ _globals["_ATTRIBUTECONTEXT_PEER"]._serialized_start = 682
+ _globals["_ATTRIBUTECONTEXT_PEER"]._serialized_end = 872
+ _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_start = 827
+ _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_end = 872
+ _globals["_ATTRIBUTECONTEXT_API"]._serialized_start = 874
+ _globals["_ATTRIBUTECONTEXT_API"]._serialized_end = 950
+ _globals["_ATTRIBUTECONTEXT_AUTH"]._serialized_start = 952
+ _globals["_ATTRIBUTECONTEXT_AUTH"]._serialized_end = 1079
+ _globals["_ATTRIBUTECONTEXT_REQUEST"]._serialized_start = 1082
+ _globals["_ATTRIBUTECONTEXT_REQUEST"]._serialized_end = 1465
+ _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_start = 1419
+ _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_end = 1465
+ _globals["_ATTRIBUTECONTEXT_RESPONSE"]._serialized_start = 1468
+ _globals["_ATTRIBUTECONTEXT_RESPONSE"]._serialized_end = 1725
+ _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_start = 1419
+ _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_end = 1465
+ _globals["_ATTRIBUTECONTEXT_RESOURCE"]._serialized_start = 1728
+ _globals["_ATTRIBUTECONTEXT_RESOURCE"]._serialized_end = 2256
+ _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_start = 827
+ _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_end = 872
+ _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._serialized_start = 2206
+ _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._serialized_end = 2256
+# @@protoc_insertion_point(module_scope)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context_pb2.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context_pb2.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..a068b06626f7e2fc85513eed6c0d782ac0e00783
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/attribute_context_pb2.pyi
@@ -0,0 +1,313 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import ClassVar as _ClassVar
+from typing import Iterable as _Iterable
+from typing import Mapping as _Mapping
+from typing import Optional as _Optional
+from typing import Union as _Union
+
+from google.protobuf import any_pb2 as _any_pb2
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import duration_pb2 as _duration_pb2
+from google.protobuf import message as _message
+from google.protobuf import struct_pb2 as _struct_pb2
+from google.protobuf import timestamp_pb2 as _timestamp_pb2
+from google.protobuf.internal import containers as _containers
+
+DESCRIPTOR: _descriptor.FileDescriptor
+
+class AttributeContext(_message.Message):
+ __slots__ = (
+ "origin",
+ "source",
+ "destination",
+ "request",
+ "response",
+ "resource",
+ "api",
+ "extensions",
+ )
+ class Peer(_message.Message):
+ __slots__ = ("ip", "port", "labels", "principal", "region_code")
+ class LabelsEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: str
+ def __init__(
+ self, key: _Optional[str] = ..., value: _Optional[str] = ...
+ ) -> None: ...
+
+ IP_FIELD_NUMBER: _ClassVar[int]
+ PORT_FIELD_NUMBER: _ClassVar[int]
+ LABELS_FIELD_NUMBER: _ClassVar[int]
+ PRINCIPAL_FIELD_NUMBER: _ClassVar[int]
+ REGION_CODE_FIELD_NUMBER: _ClassVar[int]
+ ip: str
+ port: int
+ labels: _containers.ScalarMap[str, str]
+ principal: str
+ region_code: str
+ def __init__(
+ self,
+ ip: _Optional[str] = ...,
+ port: _Optional[int] = ...,
+ labels: _Optional[_Mapping[str, str]] = ...,
+ principal: _Optional[str] = ...,
+ region_code: _Optional[str] = ...,
+ ) -> None: ...
+
+ class Api(_message.Message):
+ __slots__ = ("service", "operation", "protocol", "version")
+ SERVICE_FIELD_NUMBER: _ClassVar[int]
+ OPERATION_FIELD_NUMBER: _ClassVar[int]
+ PROTOCOL_FIELD_NUMBER: _ClassVar[int]
+ VERSION_FIELD_NUMBER: _ClassVar[int]
+ service: str
+ operation: str
+ protocol: str
+ version: str
+ def __init__(
+ self,
+ service: _Optional[str] = ...,
+ operation: _Optional[str] = ...,
+ protocol: _Optional[str] = ...,
+ version: _Optional[str] = ...,
+ ) -> None: ...
+
+ class Auth(_message.Message):
+ __slots__ = ("principal", "audiences", "presenter", "claims", "access_levels")
+ PRINCIPAL_FIELD_NUMBER: _ClassVar[int]
+ AUDIENCES_FIELD_NUMBER: _ClassVar[int]
+ PRESENTER_FIELD_NUMBER: _ClassVar[int]
+ CLAIMS_FIELD_NUMBER: _ClassVar[int]
+ ACCESS_LEVELS_FIELD_NUMBER: _ClassVar[int]
+ principal: str
+ audiences: _containers.RepeatedScalarFieldContainer[str]
+ presenter: str
+ claims: _struct_pb2.Struct
+ access_levels: _containers.RepeatedScalarFieldContainer[str]
+ def __init__(
+ self,
+ principal: _Optional[str] = ...,
+ audiences: _Optional[_Iterable[str]] = ...,
+ presenter: _Optional[str] = ...,
+ claims: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...,
+ access_levels: _Optional[_Iterable[str]] = ...,
+ ) -> None: ...
+
+ class Request(_message.Message):
+ __slots__ = (
+ "id",
+ "method",
+ "headers",
+ "path",
+ "host",
+ "scheme",
+ "query",
+ "time",
+ "size",
+ "protocol",
+ "reason",
+ "auth",
+ "origin",
+ )
+ class HeadersEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: str
+ def __init__(
+ self, key: _Optional[str] = ..., value: _Optional[str] = ...
+ ) -> None: ...
+
+ ID_FIELD_NUMBER: _ClassVar[int]
+ METHOD_FIELD_NUMBER: _ClassVar[int]
+ HEADERS_FIELD_NUMBER: _ClassVar[int]
+ PATH_FIELD_NUMBER: _ClassVar[int]
+ HOST_FIELD_NUMBER: _ClassVar[int]
+ SCHEME_FIELD_NUMBER: _ClassVar[int]
+ QUERY_FIELD_NUMBER: _ClassVar[int]
+ TIME_FIELD_NUMBER: _ClassVar[int]
+ SIZE_FIELD_NUMBER: _ClassVar[int]
+ PROTOCOL_FIELD_NUMBER: _ClassVar[int]
+ REASON_FIELD_NUMBER: _ClassVar[int]
+ AUTH_FIELD_NUMBER: _ClassVar[int]
+ ORIGIN_FIELD_NUMBER: _ClassVar[int]
+ id: str
+ method: str
+ headers: _containers.ScalarMap[str, str]
+ path: str
+ host: str
+ scheme: str
+ query: str
+ time: _timestamp_pb2.Timestamp
+ size: int
+ protocol: str
+ reason: str
+ auth: AttributeContext.Auth
+ origin: str
+ def __init__(
+ self,
+ id: _Optional[str] = ...,
+ method: _Optional[str] = ...,
+ headers: _Optional[_Mapping[str, str]] = ...,
+ path: _Optional[str] = ...,
+ host: _Optional[str] = ...,
+ scheme: _Optional[str] = ...,
+ query: _Optional[str] = ...,
+ time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...,
+ size: _Optional[int] = ...,
+ protocol: _Optional[str] = ...,
+ reason: _Optional[str] = ...,
+ auth: _Optional[_Union[AttributeContext.Auth, _Mapping]] = ...,
+ origin: _Optional[str] = ...,
+ ) -> None: ...
+
+ class Response(_message.Message):
+ __slots__ = ("code", "size", "headers", "time", "backend_latency")
+ class HeadersEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: str
+ def __init__(
+ self, key: _Optional[str] = ..., value: _Optional[str] = ...
+ ) -> None: ...
+
+ CODE_FIELD_NUMBER: _ClassVar[int]
+ SIZE_FIELD_NUMBER: _ClassVar[int]
+ HEADERS_FIELD_NUMBER: _ClassVar[int]
+ TIME_FIELD_NUMBER: _ClassVar[int]
+ BACKEND_LATENCY_FIELD_NUMBER: _ClassVar[int]
+ code: int
+ size: int
+ headers: _containers.ScalarMap[str, str]
+ time: _timestamp_pb2.Timestamp
+ backend_latency: _duration_pb2.Duration
+ def __init__(
+ self,
+ code: _Optional[int] = ...,
+ size: _Optional[int] = ...,
+ headers: _Optional[_Mapping[str, str]] = ...,
+ time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...,
+ backend_latency: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ...,
+ ) -> None: ...
+
+ class Resource(_message.Message):
+ __slots__ = (
+ "service",
+ "name",
+ "type",
+ "labels",
+ "uid",
+ "annotations",
+ "display_name",
+ "create_time",
+ "update_time",
+ "delete_time",
+ "etag",
+ "location",
+ )
+ class LabelsEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: str
+ def __init__(
+ self, key: _Optional[str] = ..., value: _Optional[str] = ...
+ ) -> None: ...
+
+ class AnnotationsEntry(_message.Message):
+ __slots__ = ("key", "value")
+ KEY_FIELD_NUMBER: _ClassVar[int]
+ VALUE_FIELD_NUMBER: _ClassVar[int]
+ key: str
+ value: str
+ def __init__(
+ self, key: _Optional[str] = ..., value: _Optional[str] = ...
+ ) -> None: ...
+
+ SERVICE_FIELD_NUMBER: _ClassVar[int]
+ NAME_FIELD_NUMBER: _ClassVar[int]
+ TYPE_FIELD_NUMBER: _ClassVar[int]
+ LABELS_FIELD_NUMBER: _ClassVar[int]
+ UID_FIELD_NUMBER: _ClassVar[int]
+ ANNOTATIONS_FIELD_NUMBER: _ClassVar[int]
+ DISPLAY_NAME_FIELD_NUMBER: _ClassVar[int]
+ CREATE_TIME_FIELD_NUMBER: _ClassVar[int]
+ UPDATE_TIME_FIELD_NUMBER: _ClassVar[int]
+ DELETE_TIME_FIELD_NUMBER: _ClassVar[int]
+ ETAG_FIELD_NUMBER: _ClassVar[int]
+ LOCATION_FIELD_NUMBER: _ClassVar[int]
+ service: str
+ name: str
+ type: str
+ labels: _containers.ScalarMap[str, str]
+ uid: str
+ annotations: _containers.ScalarMap[str, str]
+ display_name: str
+ create_time: _timestamp_pb2.Timestamp
+ update_time: _timestamp_pb2.Timestamp
+ delete_time: _timestamp_pb2.Timestamp
+ etag: str
+ location: str
+ def __init__(
+ self,
+ service: _Optional[str] = ...,
+ name: _Optional[str] = ...,
+ type: _Optional[str] = ...,
+ labels: _Optional[_Mapping[str, str]] = ...,
+ uid: _Optional[str] = ...,
+ annotations: _Optional[_Mapping[str, str]] = ...,
+ display_name: _Optional[str] = ...,
+ create_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...,
+ update_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...,
+ delete_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...,
+ etag: _Optional[str] = ...,
+ location: _Optional[str] = ...,
+ ) -> None: ...
+
+ ORIGIN_FIELD_NUMBER: _ClassVar[int]
+ SOURCE_FIELD_NUMBER: _ClassVar[int]
+ DESTINATION_FIELD_NUMBER: _ClassVar[int]
+ REQUEST_FIELD_NUMBER: _ClassVar[int]
+ RESPONSE_FIELD_NUMBER: _ClassVar[int]
+ RESOURCE_FIELD_NUMBER: _ClassVar[int]
+ API_FIELD_NUMBER: _ClassVar[int]
+ EXTENSIONS_FIELD_NUMBER: _ClassVar[int]
+ origin: AttributeContext.Peer
+ source: AttributeContext.Peer
+ destination: AttributeContext.Peer
+ request: AttributeContext.Request
+ response: AttributeContext.Response
+ resource: AttributeContext.Resource
+ api: AttributeContext.Api
+ extensions: _containers.RepeatedCompositeFieldContainer[_any_pb2.Any]
+ def __init__(
+ self,
+ origin: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ...,
+ source: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ...,
+ destination: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ...,
+ request: _Optional[_Union[AttributeContext.Request, _Mapping]] = ...,
+ response: _Optional[_Union[AttributeContext.Response, _Mapping]] = ...,
+ resource: _Optional[_Union[AttributeContext.Resource, _Mapping]] = ...,
+ api: _Optional[_Union[AttributeContext.Api, _Mapping]] = ...,
+ extensions: _Optional[_Iterable[_Union[_any_pb2.Any, _Mapping]]] = ...,
+ ) -> None: ...
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context.proto b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context.proto
new file mode 100644
index 0000000000000000000000000000000000000000..03c5ab9a508659be37500885a137c071f73f565c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context.proto
@@ -0,0 +1,48 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto3";
+
+package google.rpc.context;
+
+import "google/protobuf/struct.proto";
+
+option go_package = "google.golang.org/genproto/googleapis/rpc/context;context";
+option java_multiple_files = true;
+option java_outer_classname = "AuditContextProto";
+option java_package = "com.google.rpc.context";
+
+// `AuditContext` provides information that is needed for audit logging.
+message AuditContext {
+ // Serialized audit log.
+ bytes audit_log = 1;
+
+ // An API request message that is scrubbed based on the method annotation.
+ // This field should only be filled if audit_log field is present.
+ // Service Control will use this to assemble a complete log for Cloud Audit
+ // Logs and Google internal audit logs.
+ google.protobuf.Struct scrubbed_request = 2;
+
+ // An API response message that is scrubbed based on the method annotation.
+ // This field should only be filled if audit_log field is present.
+ // Service Control will use this to assemble a complete log for Cloud Audit
+ // Logs and Google internal audit logs.
+ google.protobuf.Struct scrubbed_response = 3;
+
+ // Number of scrubbed response items.
+ int32 scrubbed_response_item_count = 4;
+
+ // Audit resource name which is scrubbed.
+ string target_resource = 5;
+}
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context_pb2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d52ec1220582eeb9d77a0aa7bf52d6c11901045
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context_pb2.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/rpc/context/audit_context.proto
+# Protobuf Python Version: 4.25.3
+"""Generated protocol buffer code."""
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b'\n&google/rpc/context/audit_context.proto\x12\x12google.rpc.context\x1a\x1cgoogle/protobuf/struct.proto"\xc7\x01\n\x0c\x41uditContext\x12\x11\n\taudit_log\x18\x01 \x01(\x0c\x12\x31\n\x10scrubbed_request\x18\x02 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x32\n\x11scrubbed_response\x18\x03 \x01(\x0b\x32\x17.google.protobuf.Struct\x12$\n\x1cscrubbed_response_item_count\x18\x04 \x01(\x05\x12\x17\n\x0ftarget_resource\x18\x05 \x01(\tBh\n\x16\x63om.google.rpc.contextB\x11\x41uditContextProtoP\x01Z9google.golang.org/genproto/googleapis/rpc/context;contextb\x06proto3'
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(
+ DESCRIPTOR, "google.rpc.context.audit_context_pb2", _globals
+)
+if _descriptor._USE_C_DESCRIPTORS == False:
+ _globals["DESCRIPTOR"]._options = None
+ _globals[
+ "DESCRIPTOR"
+ ]._serialized_options = b"\n\026com.google.rpc.contextB\021AuditContextProtoP\001Z9google.golang.org/genproto/googleapis/rpc/context;context"
+ _globals["_AUDITCONTEXT"]._serialized_start = 93
+ _globals["_AUDITCONTEXT"]._serialized_end = 292
+# @@protoc_insertion_point(module_scope)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context_pb2.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context_pb2.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..8583ec169fb2cfc55a23053e4942c9601061a571
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/rpc/context/audit_context_pb2.pyi
@@ -0,0 +1,51 @@
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import ClassVar as _ClassVar
+from typing import Mapping as _Mapping
+from typing import Optional as _Optional
+from typing import Union as _Union
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from google.protobuf import struct_pb2 as _struct_pb2
+
+DESCRIPTOR: _descriptor.FileDescriptor
+
+class AuditContext(_message.Message):
+ __slots__ = (
+ "audit_log",
+ "scrubbed_request",
+ "scrubbed_response",
+ "scrubbed_response_item_count",
+ "target_resource",
+ )
+ AUDIT_LOG_FIELD_NUMBER: _ClassVar[int]
+ SCRUBBED_REQUEST_FIELD_NUMBER: _ClassVar[int]
+ SCRUBBED_RESPONSE_FIELD_NUMBER: _ClassVar[int]
+ SCRUBBED_RESPONSE_ITEM_COUNT_FIELD_NUMBER: _ClassVar[int]
+ TARGET_RESOURCE_FIELD_NUMBER: _ClassVar[int]
+ audit_log: bytes
+ scrubbed_request: _struct_pb2.Struct
+ scrubbed_response: _struct_pb2.Struct
+ scrubbed_response_item_count: int
+ target_resource: str
+ def __init__(
+ self,
+ audit_log: _Optional[bytes] = ...,
+ scrubbed_request: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...,
+ scrubbed_response: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ...,
+ scrubbed_response_item_count: _Optional[int] = ...,
+ target_resource: _Optional[str] = ...,
+ ) -> None: ...
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..90eb44b85492bf210333122b3f93bf26cefdd475
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__init__.py
@@ -0,0 +1,3 @@
+from langgraph.pregel.main import NodeBuilder, Pregel
+
+__all__ = ("Pregel", "NodeBuilder")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_algo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_algo.py
new file mode 100644
index 0000000000000000000000000000000000000000..103f6cce01757d6db94ad113a50528909d78c6f7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_algo.py
@@ -0,0 +1,1460 @@
+from __future__ import annotations
+
+import binascii
+import itertools
+import sys
+import threading
+from collections import defaultdict, deque
+from collections.abc import Callable, Iterable, Mapping, Sequence
+from copy import copy
+from functools import partial
+from hashlib import sha1
+from typing import (
+ Any,
+ Literal,
+ NamedTuple,
+ Protocol,
+ cast,
+ overload,
+)
+
+from langchain_core.callbacks import Callbacks
+from langchain_core.callbacks.manager import AsyncParentRunManager, ParentRunManager
+from langchain_core.runnables.config import RunnableConfig
+from langgraph.checkpoint.base import (
+ BaseCheckpointSaver,
+ ChannelVersions,
+ Checkpoint,
+ PendingWrite,
+ V,
+)
+from langgraph.store.base import BaseStore
+from xxhash import xxh3_128_hexdigest
+
+from langgraph._internal._config import merge_configs, patch_config
+from langgraph._internal._constants import (
+ CACHE_NS_WRITES,
+ CONF,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_CHECKPOINTER,
+ CONFIG_KEY_NODE_ERROR,
+ CONFIG_KEY_READ,
+ CONFIG_KEY_RESUME_MAP,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SCRATCHPAD,
+ CONFIG_KEY_SEND,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ INTERRUPT,
+ NO_WRITES,
+ NS_END,
+ NS_SEP,
+ NULL_TASK_ID,
+ PREVIOUS,
+ PULL,
+ PUSH,
+ RESERVED,
+ RESUME,
+ RETURN,
+ TASKS,
+)
+from langgraph._internal._scratchpad import PregelScratchpad
+from langgraph._internal._typing import EMPTY_SEQ, MISSING
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.topic import Topic
+from langgraph.channels.untracked_value import UntrackedValue
+from langgraph.constants import TAG_HIDDEN
+from langgraph.errors import NodeError
+from langgraph.managed.base import ManagedValueMapping
+from langgraph.pregel._call import get_runnable_for_task, identifier
+from langgraph.pregel._io import read_channels
+from langgraph.pregel._log import logger
+from langgraph.pregel._read import INPUT_CACHE_KEY_TYPE, PregelNode
+from langgraph.runtime import DEFAULT_RUNTIME, ExecutionInfo, Runtime
+from langgraph.types import (
+ All,
+ CacheKey,
+ CachePolicy,
+ PregelExecutableTask,
+ PregelTask,
+ RetryPolicy,
+ Send,
+ TimeoutPolicy,
+)
+
+GetNextVersion = Callable[[V | None, None], V]
+SUPPORTS_EXC_NOTES = sys.version_info >= (3, 11)
+
+
+class WritesProtocol(Protocol):
+ """Protocol for objects containing writes to be applied to checkpoint.
+ Implemented by PregelTaskWrites and PregelExecutableTask."""
+
+ @property
+ def path(self) -> tuple[str | int | tuple, ...]: ...
+
+ @property
+ def name(self) -> str: ...
+
+ @property
+ def writes(self) -> Sequence[tuple[str, Any]]: ...
+
+ @property
+ def triggers(self) -> Sequence[str]: ...
+
+
+class PregelTaskWrites(NamedTuple):
+ """Simplest implementation of WritesProtocol, for usage with writes that
+ don't originate from a runnable task, eg. graph input, update_state, etc."""
+
+ path: tuple[str | int | tuple, ...]
+ name: str
+ writes: Sequence[tuple[str, Any]]
+ triggers: Sequence[str]
+
+
+class Call:
+ __slots__ = (
+ "func",
+ "input",
+ "retry_policy",
+ "cache_policy",
+ "callbacks",
+ "timeout",
+ )
+
+ func: Callable
+ input: tuple[tuple[Any, ...], dict[str, Any]]
+ retry_policy: Sequence[RetryPolicy] | None
+ cache_policy: CachePolicy | None
+ callbacks: Callbacks
+ timeout: TimeoutPolicy | None
+
+ def __init__(
+ self,
+ func: Callable,
+ input: tuple[tuple[Any, ...], dict[str, Any]],
+ *,
+ retry_policy: Sequence[RetryPolicy] | None,
+ cache_policy: CachePolicy | None,
+ callbacks: Callbacks,
+ timeout: TimeoutPolicy | None = None,
+ ) -> None:
+ self.func = func
+ self.input = input
+ self.retry_policy = retry_policy
+ self.cache_policy = cache_policy
+ self.callbacks = callbacks
+ self.timeout = timeout
+
+
+def should_interrupt(
+ checkpoint: Checkpoint,
+ interrupt_nodes: All | Sequence[str],
+ tasks: Iterable[PregelExecutableTask],
+) -> list[PregelExecutableTask]:
+ """Check if the graph should be interrupted based on current state."""
+ version_type = type(next(iter(checkpoint["channel_versions"].values()), None))
+ null_version = version_type() # type: ignore[misc]
+ seen = checkpoint["versions_seen"].get(INTERRUPT, {})
+ # interrupt if any channel has been updated since last interrupt
+ any_updates_since_prev_interrupt = any(
+ version > seen.get(chan, null_version) # type: ignore[operator]
+ for chan, version in checkpoint["channel_versions"].items()
+ )
+ # and any triggered node is in interrupt_nodes list
+ return (
+ [
+ task
+ for task in tasks
+ if (
+ (
+ not task.config
+ or TAG_HIDDEN not in task.config.get("tags", EMPTY_SEQ)
+ )
+ if interrupt_nodes == "*"
+ else task.name in interrupt_nodes
+ )
+ ]
+ if any_updates_since_prev_interrupt
+ else []
+ )
+
+
+def local_read(
+ scratchpad: PregelScratchpad,
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ task: WritesProtocol,
+ select: list[str] | str,
+ fresh: bool = False,
+) -> dict[str, Any] | Any:
+ """Function injected under CONFIG_KEY_READ in task config, to read current state.
+ Used by conditional edges to read a copy of the state with reflecting the writes
+ from that node only."""
+ updated: dict[str, list[Any]] = defaultdict(list)
+ if isinstance(select, str):
+ managed_keys = []
+ for c, v in task.writes:
+ if c == select:
+ updated[c].append(v)
+ else:
+ managed_keys = [k for k in select if k in managed]
+ select = [k for k in select if k not in managed]
+ for c, v in task.writes:
+ if c in select:
+ updated[c].append(v)
+ if fresh:
+ # apply writes
+ local_channels: dict[str, BaseChannel] = {}
+ for k in channels:
+ cc = channels[k].copy()
+ cc.update(updated[k])
+ local_channels[k] = cc
+ # read fresh values
+ values = read_channels(local_channels, select)
+ else:
+ values = read_channels(channels, select)
+ if managed_keys:
+ values.update({k: managed[k].get(scratchpad) for k in managed_keys})
+ return values
+
+
+def increment(current: int | None, channel: None) -> int:
+ """Default channel versioning function, increments the current int version."""
+ return current + 1 if current is not None else 1
+
+
+def apply_writes(
+ checkpoint: Checkpoint,
+ channels: Mapping[str, BaseChannel],
+ tasks: Iterable[WritesProtocol],
+ get_next_version: GetNextVersion | None,
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+) -> set[str]:
+ """Apply writes from a set of tasks (usually the tasks from a Pregel step)
+ to the checkpoint and channels, and return managed values writes to be applied
+ externally.
+
+ Args:
+ checkpoint: The checkpoint to update.
+ channels: The channels to update.
+ tasks: The tasks to apply writes from.
+ get_next_version: Optional function to determine the next version of a channel.
+ trigger_to_nodes: Mapping of channel names to the set of nodes that can be triggered by updates to that channel.
+
+ Returns:
+ Set of channels that were updated in this step.
+ """
+ # sort tasks on path, to ensure deterministic order for update application
+ # any path parts after the 3rd are ignored for sorting
+ # (we use them for eg. task ids which aren't good for sorting)
+ tasks = sorted(tasks, key=lambda t: task_path_str(t.path[:3]))
+ # if no task has triggers this is applying writes from the null task only
+ # so we don't do anything other than update the channels written to
+ bump_step = any(t.triggers for t in tasks)
+
+ # update seen versions
+ for task in tasks:
+ checkpoint["versions_seen"].setdefault(task.name, {}).update(
+ {
+ chan: checkpoint["channel_versions"][chan]
+ for chan in task.triggers
+ if chan in checkpoint["channel_versions"]
+ }
+ )
+
+ # Find the highest version of all channels
+ if get_next_version is None:
+ next_version = None
+ else:
+ next_version = get_next_version(
+ (
+ max(checkpoint["channel_versions"].values())
+ if checkpoint["channel_versions"]
+ else None
+ ),
+ None,
+ )
+
+ # Consume all channels that were read
+ for chan in {
+ chan
+ for task in tasks
+ for chan in task.triggers
+ if chan not in RESERVED and chan in channels
+ }:
+ if channels[chan].consume() and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+
+ # Group writes by channel
+ pending_writes_by_channel: dict[str, list[Any]] = defaultdict(list)
+ for task in tasks:
+ for chan, val in task.writes:
+ if chan in (
+ NO_WRITES,
+ PUSH,
+ RESUME,
+ INTERRUPT,
+ RETURN,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ ):
+ pass
+ elif chan in channels:
+ pending_writes_by_channel[chan].append(val)
+ else:
+ logger.warning(
+ f"Task {task.name} with path {task.path} wrote to unknown channel {chan}, ignoring it."
+ )
+
+ # Apply writes to channels
+ updated_channels: set[str] = set()
+ for chan, vals in pending_writes_by_channel.items():
+ if chan in channels:
+ if channels[chan].update(vals) and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+ # unavailable channels can't trigger tasks, so don't add them
+ if channels[chan].is_available():
+ updated_channels.add(chan)
+
+ # Channels that weren't updated in this step are notified of a new step
+ if bump_step:
+ for chan in channels:
+ if channels[chan].is_available() and chan not in updated_channels:
+ if channels[chan].update(EMPTY_SEQ) and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+ # unavailable channels can't trigger tasks, so don't add them
+ if channels[chan].is_available():
+ updated_channels.add(chan)
+
+ # If this is (tentatively) the last superstep, notify all channels of finish
+ if bump_step and updated_channels.isdisjoint(trigger_to_nodes):
+ for chan in channels:
+ if channels[chan].finish() and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+ # unavailable channels can't trigger tasks, so don't add them
+ if channels[chan].is_available():
+ updated_channels.add(chan)
+
+ # Return managed values writes to be applied externally
+ return updated_channels
+
+
+@overload
+def prepare_next_tasks(
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ *,
+ for_execution: Literal[False],
+ store: Literal[None] = None,
+ checkpointer: Literal[None] = None,
+ manager: Literal[None] = None,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ updated_channels: set[str] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: Literal[None] = None,
+) -> dict[str, PregelTask]: ...
+
+
+@overload
+def prepare_next_tasks(
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ *,
+ for_execution: Literal[True],
+ store: BaseStore | None,
+ checkpointer: BaseCheckpointSaver | None,
+ manager: None | ParentRunManager | AsyncParentRunManager,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ updated_channels: set[str] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+) -> dict[str, PregelExecutableTask]: ...
+
+
+def prepare_next_tasks(
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ *,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ updated_channels: set[str] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+) -> dict[str, PregelTask] | dict[str, PregelExecutableTask]:
+ """Prepare the set of tasks that will make up the next Pregel step.
+
+ Args:
+ checkpoint: The current checkpoint.
+ pending_writes: The list of pending writes.
+ processes: The mapping of process names to PregelNode instances.
+ channels: The mapping of channel names to BaseChannel instances.
+ managed: The mapping of managed value names to functions.
+ config: The `Runnable` configuration.
+ step: The current step.
+ for_execution: Whether the tasks are being prepared for execution.
+ store: An instance of BaseStore to make it available for usage within tasks.
+ checkpointer: `Checkpointer` instance used for saving checkpoints.
+ manager: The parent run manager to use for the tasks.
+ trigger_to_nodes: Optional: Mapping of channel names to the set of nodes
+ that are can be triggered by that channel.
+ updated_channels: Optional. Set of channel names that have been updated during
+ the previous step. Using in conjunction with trigger_to_nodes to speed
+ up the process of determining which nodes should be triggered in the next
+ step.
+
+ Returns:
+ A dictionary of tasks to be executed. The keys are the task ids and the values
+ are the tasks themselves. This is the union of all PUSH tasks (Sends)
+ and PULL tasks (nodes triggered by edges).
+ """
+ input_cache: dict[INPUT_CACHE_KEY_TYPE, Any] = {}
+ checkpoint_id_bytes = binascii.unhexlify(checkpoint["id"].replace("-", ""))
+ null_version = checkpoint_null_version(checkpoint)
+ tasks: list[PregelTask | PregelExecutableTask] = []
+ # Consume pending tasks
+ tasks_channel = cast(Topic[Send] | None, channels.get(TASKS))
+ if tasks_channel and tasks_channel.is_available():
+ for idx, _ in enumerate(tasks_channel.get()):
+ if task := prepare_single_task(
+ (PUSH, idx),
+ None,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ checkpoint_null_version=null_version,
+ pending_writes=pending_writes,
+ processes=processes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ input_cache=input_cache,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ ):
+ tasks.append(task)
+
+ # This section is an optimization that allows which nodes will be active
+ # during the next step.
+ # When there's information about:
+ # 1. Which channels were updated in the previous step
+ # 2. Which nodes are triggered by which channels
+ # Then we can determine which nodes should be triggered in the next step
+ # without having to cycle through all nodes.
+ if updated_channels and trigger_to_nodes:
+ triggered_nodes: set[str] = set()
+ # Get all nodes that have triggers associated with an updated channel
+ for channel in updated_channels:
+ if node_ids := trigger_to_nodes.get(channel):
+ triggered_nodes.update(node_ids)
+ # Sort the nodes to ensure deterministic order
+ candidate_nodes: Iterable[str] = sorted(triggered_nodes)
+ elif not checkpoint["channel_versions"]:
+ candidate_nodes = ()
+ else:
+ candidate_nodes = processes.keys()
+
+ # Check if any processes should be run in next step
+ # If so, prepare the values to be passed to them
+ for name in candidate_nodes:
+ if task := prepare_single_task(
+ (PULL, name),
+ None,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ checkpoint_null_version=null_version,
+ pending_writes=pending_writes,
+ processes=processes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ input_cache=input_cache,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ ):
+ tasks.append(task)
+ return {t.id: t for t in tasks}
+
+
+PUSH_TRIGGER = (PUSH,)
+
+
+class _TaskIDFn(Protocol):
+ def __call__(self, namespace: bytes, *parts: str | bytes) -> str:
+ pass
+
+
+def prepare_single_task(
+ task_path: tuple[Any, ...],
+ task_id_checksum: str | None,
+ *,
+ checkpoint: Checkpoint,
+ checkpoint_id_bytes: bytes,
+ checkpoint_null_version: V | None,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ input_cache: dict[INPUT_CACHE_KEY_TYPE, Any] | None = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+) -> None | PregelTask | PregelExecutableTask:
+ """Prepares a single task for the next Pregel step, given a task path, which
+ uniquely identifies a PUSH or PULL task within the graph."""
+ configurable = config.get(CONF, {})
+ parent_ns = configurable.get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_id_func = _xxhash_str if checkpoint["v"] > 1 else _uuid5_str
+
+ if task_path[0] == PUSH and isinstance(task_path[-1], Call):
+ return prepare_push_task_functional(
+ cast(tuple[str, tuple, int, str, Call], task_path),
+ task_id_checksum,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ pending_writes=pending_writes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ parent_ns=parent_ns,
+ task_id_func=task_id_func,
+ )
+
+ elif task_path[0] == PUSH:
+ return prepare_push_task_send(
+ cast(tuple[str, tuple], task_path),
+ task_id_checksum,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ pending_writes=pending_writes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ processes=processes,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ parent_ns=parent_ns,
+ task_id_func=task_id_func,
+ )
+
+ elif task_path[0] == PULL:
+ # (PULL, node name)
+ name = cast(str, task_path[1])
+ if name not in processes:
+ return
+ proc = processes[name]
+ if checkpoint_null_version is None:
+ return
+ # If any of the channels read by this process were updated
+ if _triggers(
+ channels,
+ checkpoint["channel_versions"],
+ checkpoint["versions_seen"].get(name),
+ checkpoint_null_version,
+ proc,
+ ):
+ triggers = tuple(sorted(proc.triggers))
+ # create task id
+ checkpoint_ns = f"{parent_ns}{NS_SEP}{name}" if parent_ns else name
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ name,
+ PULL,
+ *triggers,
+ )
+ task_checkpoint_ns = f"{checkpoint_ns}{NS_END}{task_id}"
+ # create scratchpad
+ scratchpad = _scratchpad(
+ config[CONF].get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ config[CONF].get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ # create task input
+ try:
+ val = _proc_input(
+ proc,
+ managed,
+ channels,
+ for_execution=for_execution,
+ input_cache=input_cache,
+ scratchpad=scratchpad,
+ )
+ if val is MISSING:
+ return
+ except Exception as exc:
+ if SUPPORTS_EXC_NOTES:
+ exc.add_note(
+ f"Before task with name '{name}' and path '{task_path[:3]}'"
+ )
+ raise
+
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": name,
+ "langgraph_triggers": triggers,
+ "langgraph_path": task_path[:3],
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if task_id_checksum is not None:
+ assert task_id == task_id_checksum, f"{task_id} != {task_id_checksum}"
+ if for_execution:
+ if node := proc.node:
+ if proc.metadata:
+ metadata.update(proc.metadata)
+ writes: deque[tuple[str, Any]] = deque()
+ cache_policy = proc.cache_policy or cache_policy
+ if cache_policy:
+ args_key = cache_policy.key_func(val)
+ cache_key = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(proc) or "__dynamic__"),
+ name,
+ ),
+ xxh3_128_hexdigest(
+ (
+ args_key.encode()
+ if isinstance(args_key, str)
+ else args_key
+ ),
+ ),
+ cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+ runtime = cast(
+ Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
+ )
+ runtime = runtime.override(
+ previous=checkpoint["channel_values"].get(PREVIOUS, None),
+ store=store,
+ execution_info=ExecutionInfo(
+ checkpoint_id=checkpoint["id"],
+ checkpoint_ns=task_checkpoint_ns,
+ task_id=task_id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+ additional_config = {
+ "metadata": metadata,
+ "tags": proc.tags,
+ }
+ return PregelExecutableTask(
+ name,
+ val,
+ node,
+ writes,
+ patch_config(
+ merge_configs(
+ config, cast(RunnableConfig, additional_config)
+ ),
+ run_name=name,
+ callbacks=(
+ manager.get_child(f"graph:step:{step}")
+ if manager
+ else None
+ ),
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(
+ task_path[:3],
+ name,
+ writes,
+ triggers,
+ ),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer
+ or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ },
+ ),
+ triggers,
+ proc.retry_policy or retry_policy,
+ cache_key,
+ task_id,
+ task_path[:3],
+ writers=proc.flat_writers,
+ subgraphs=proc.subgraphs,
+ timeout=proc.timeout,
+ )
+ else:
+ return PregelTask(task_id, name, task_path[:3])
+
+
+def _coerce_pending_error(value: Any) -> BaseException:
+ if isinstance(value, BaseException):
+ return value
+ return Exception(str(value))
+
+
+def _read_errors_from_pending_writes(
+ pending_writes: list[PendingWrite],
+) -> list[BaseException]:
+ errors: list[BaseException] = []
+ for _, channel, value in pending_writes:
+ if channel == ERROR:
+ errors.append(_coerce_pending_error(value))
+ return errors
+
+
+def _read_error_for_task_id_from_pending_writes(
+ pending_writes: list[PendingWrite], task_id: str
+) -> BaseException | None:
+ for pending_task_id, channel, value in reversed(pending_writes):
+ if pending_task_id == task_id and channel == ERROR:
+ return _coerce_pending_error(value)
+ return None
+
+
+def _read_error_source_node_from_pending_writes(
+ pending_writes: list[PendingWrite], task_id: str
+) -> str | None:
+ for pending_task_id, channel, value in reversed(pending_writes):
+ if pending_task_id == task_id and channel == ERROR_SOURCE_NODE:
+ if isinstance(value, str):
+ return value
+ return str(value)
+ return None
+
+
+def prepare_push_task_functional(
+ task_path: tuple[str, tuple, int, str, Call],
+ # (PUSH, parent task path, idx of PUSH write, id of parent task, Call)
+ task_id_checksum: str | None,
+ *,
+ checkpoint: Checkpoint,
+ checkpoint_id_bytes: bytes,
+ pending_writes: list[PendingWrite],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ parent_ns: str,
+ # namespace: bytes, *parts: str | bytes
+ task_id_func: _TaskIDFn,
+) -> PregelTask | PregelExecutableTask:
+ """Prepare a push task with an attached caller. Used for the functional API."""
+ configurable = config.get(CONF, {})
+
+ call = task_path[-1]
+ proc_ = get_runnable_for_task(call.func)
+ name = proc_.name
+ if name is None:
+ raise ValueError("`call` functions must have a `__name__` attribute")
+ # create task id
+ triggers: Sequence[str] = PUSH_TRIGGER
+ checkpoint_ns = f"{parent_ns}{NS_SEP}{name}" if parent_ns else name
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ name,
+ PUSH,
+ task_path_str(task_path[1]),
+ str(task_path[2]),
+ )
+ task_checkpoint_ns = f"{checkpoint_ns}:{task_id}"
+ # we append True to the task path to indicate that a call is being
+ # made, so we should not return interrupts from this task (responsibility lies with the parent)
+ in_progress_task_path = (*task_path[:3], True)
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": name,
+ "langgraph_triggers": triggers,
+ "langgraph_path": in_progress_task_path,
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if task_id_checksum is not None:
+ assert task_id == task_id_checksum, f"{task_id} != {task_id_checksum}"
+ if for_execution:
+ writes: deque[tuple[str, Any]] = deque()
+ cache_policy = call.cache_policy or cache_policy
+ if cache_policy:
+ args_key = cache_policy.key_func(*call.input[0], **call.input[1])
+ cache_key: CacheKey | None = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(call.func) or "__dynamic__"),
+ ),
+ xxh3_128_hexdigest(
+ args_key.encode() if isinstance(args_key, str) else args_key,
+ ),
+ cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+ scratchpad = _scratchpad(
+ configurable.get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ configurable.get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
+ runtime = runtime.override(
+ store=store,
+ execution_info=ExecutionInfo(
+ checkpoint_id=checkpoint["id"],
+ checkpoint_ns=task_checkpoint_ns,
+ task_id=task_id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+ return PregelExecutableTask(
+ name,
+ call.input,
+ proc_,
+ writes,
+ patch_config(
+ merge_configs(config, {"metadata": metadata}),
+ run_name=name,
+ callbacks=call.callbacks
+ or (manager.get_child(f"graph:step:{step}") if manager else None),
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(in_progress_task_path, name, writes, triggers),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ },
+ ),
+ triggers,
+ call.retry_policy or retry_policy,
+ cache_key,
+ task_id,
+ in_progress_task_path,
+ timeout=call.timeout,
+ )
+ else:
+ return PregelTask(task_id, name, in_progress_task_path)
+
+
+def prepare_push_task_send(
+ task_path: tuple[str, tuple],
+ # (PUSH, parent task path)
+ task_id_checksum: str | None,
+ *,
+ checkpoint: Checkpoint,
+ checkpoint_id_bytes: bytes,
+ pending_writes: list[PendingWrite],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ parent_ns: str,
+ task_id_func: _TaskIDFn,
+ processes: Mapping[str, PregelNode],
+) -> PregelTask | PregelExecutableTask | None:
+ if len(task_path) == 2:
+ # SEND tasks, executed in superstep n+1
+ # (PUSH, idx of pending send)
+ idx = cast(int, task_path[1])
+ if not channels[TASKS].is_available():
+ return
+ sends: Sequence[Send] = channels[TASKS].get()
+ if idx < 0 or idx >= len(sends):
+ return
+ packet = sends[idx]
+ if not isinstance(packet, Send):
+ logger.warning(
+ f"Ignoring invalid packet type {type(packet)} in pending sends"
+ )
+ return
+
+ if packet.node not in processes:
+ logger.warning(f"Ignoring unknown node name {packet.node} in pending sends")
+ return
+ # find process
+ proc = processes[packet.node]
+ proc_node = proc.node
+ if proc_node is None:
+ return
+ # create task id
+ triggers = PUSH_TRIGGER
+ checkpoint_ns = (
+ f"{parent_ns}{NS_SEP}{packet.node}" if parent_ns else packet.node
+ )
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ packet.node,
+ PUSH,
+ str(idx),
+ )
+ else:
+ logger.warning(f"Ignoring invalid PUSH task path {task_path}")
+ return
+ configurable = config.get(CONF, {})
+ task_checkpoint_ns = f"{checkpoint_ns}:{task_id}"
+ # we append False to the task path to indicate that a call is not being made
+ # so we should return interrupts from this task
+ translated_task_path = (*task_path[:3], False)
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": packet.node,
+ "langgraph_triggers": triggers,
+ "langgraph_path": translated_task_path,
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if task_id_checksum is not None:
+ assert task_id == task_id_checksum, f"{task_id} != {task_id_checksum}"
+ if for_execution:
+ if proc.metadata:
+ metadata.update(proc.metadata)
+ writes: deque[tuple[str, Any]] = deque()
+ cache_policy = proc.cache_policy or cache_policy
+ if cache_policy:
+ args_key = cache_policy.key_func(packet.arg)
+ cache_key = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(proc) or "__dynamic__"),
+ packet.node,
+ ),
+ xxh3_128_hexdigest(
+ args_key.encode() if isinstance(args_key, str) else args_key,
+ ),
+ cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+ scratchpad = _scratchpad(
+ config[CONF].get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ config[CONF].get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
+ runtime = runtime.override(
+ store=store,
+ previous=checkpoint["channel_values"].get(PREVIOUS, None),
+ execution_info=ExecutionInfo(
+ checkpoint_id=checkpoint["id"],
+ checkpoint_ns=task_checkpoint_ns,
+ task_id=task_id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+ additional_config: RunnableConfig = {
+ "metadata": metadata,
+ "tags": proc.tags,
+ }
+ return PregelExecutableTask(
+ packet.node,
+ packet.arg,
+ proc_node,
+ writes,
+ patch_config(
+ merge_configs(config, additional_config),
+ run_name=packet.node,
+ callbacks=(
+ manager.get_child(f"graph:step:{step}") if manager else None
+ ),
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(
+ translated_task_path, packet.node, writes, triggers
+ ),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ },
+ ),
+ triggers,
+ proc.retry_policy or retry_policy,
+ cache_key,
+ task_id,
+ translated_task_path,
+ writers=proc.flat_writers,
+ subgraphs=proc.subgraphs,
+ timeout=packet.timeout if packet.timeout is not None else proc.timeout,
+ )
+ else:
+ return PregelTask(task_id, packet.node, translated_task_path)
+
+
+def prepare_node_error_handler_task(
+ failed_task: PregelExecutableTask,
+ *,
+ handler_node_name: str,
+ failed_error: BaseException,
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+) -> PregelExecutableTask | None:
+ """Prepare an immediate node-level error handler task for a failed task."""
+ if handler_node_name not in processes:
+ return None
+ proc = processes[handler_node_name]
+ proc_node = proc.node
+ if proc_node is None:
+ return None
+
+ checkpoint_id_bytes = binascii.unhexlify(checkpoint["id"].replace("-", ""))
+ task_id_func = _xxhash_str if checkpoint["v"] > 1 else _uuid5_str
+ configurable = config.get(CONF, {})
+ parent_ns = configurable.get(CONFIG_KEY_CHECKPOINT_NS, "")
+ checkpoint_ns = (
+ f"{parent_ns}{NS_SEP}{handler_node_name}" if parent_ns else handler_node_name
+ )
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ handler_node_name,
+ PUSH,
+ "node_error_handler",
+ failed_task.id,
+ )
+ task_checkpoint_ns = f"{checkpoint_ns}:{task_id}"
+ translated_task_path = (*failed_task.path[:3], "node_error_handler", False)
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": handler_node_name,
+ "langgraph_triggers": PUSH_TRIGGER,
+ "langgraph_path": translated_task_path,
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if proc.metadata:
+ metadata.update(proc.metadata)
+ writes: deque[tuple[str, Any]] = deque()
+
+ effective_retry_policy = proc.retry_policy or retry_policy
+ effective_cache_policy = proc.cache_policy or cache_policy
+ if effective_cache_policy:
+ args_key = effective_cache_policy.key_func(failed_task.input)
+ cache_key = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(proc) or "__dynamic__"),
+ handler_node_name,
+ ),
+ xxh3_128_hexdigest(
+ args_key.encode() if isinstance(args_key, str) else args_key
+ ),
+ effective_cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+
+ scratchpad = _scratchpad(
+ config[CONF].get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ config[CONF].get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
+ runtime = runtime.override(
+ store=store, previous=checkpoint["channel_values"].get(PREVIOUS, None)
+ )
+ additional_config: RunnableConfig = {
+ "metadata": metadata,
+ "tags": proc.tags,
+ }
+ return PregelExecutableTask(
+ handler_node_name,
+ failed_task.input,
+ proc_node,
+ writes,
+ patch_config(
+ merge_configs(config, additional_config),
+ run_name=handler_node_name,
+ callbacks=manager.get_child(f"graph:step:{step}") if manager else None,
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(
+ translated_task_path,
+ handler_node_name,
+ writes,
+ PUSH_TRIGGER,
+ ),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ CONFIG_KEY_NODE_ERROR: NodeError(
+ node=failed_task.name, error=failed_error
+ ),
+ },
+ ),
+ PUSH_TRIGGER,
+ effective_retry_policy,
+ cache_key,
+ task_id,
+ translated_task_path,
+ writers=proc.flat_writers,
+ subgraphs=proc.subgraphs,
+ )
+
+
+def checkpoint_null_version(
+ checkpoint: Checkpoint,
+) -> V | None:
+ """Get the null version for the checkpoint, if available."""
+ for version in checkpoint["channel_versions"].values():
+ return type(version)()
+ return None
+
+
+def _triggers(
+ channels: Mapping[str, BaseChannel],
+ versions: ChannelVersions,
+ seen: ChannelVersions | None,
+ null_version: V,
+ proc: PregelNode,
+) -> bool:
+ if seen is None:
+ for chan in proc.triggers:
+ if channels[chan].is_available():
+ return True
+ else:
+ for chan in proc.triggers:
+ if channels[chan].is_available() and versions.get( # type: ignore[operator]
+ chan, null_version
+ ) > seen.get(chan, null_version):
+ return True
+ return False
+
+
+def _scratchpad(
+ parent_scratchpad: PregelScratchpad | None,
+ pending_writes: list[PendingWrite],
+ task_id: str,
+ namespace_hash: str,
+ resume_map: dict[str, Any] | None,
+ step: int,
+ stop: int,
+) -> PregelScratchpad:
+ if len(pending_writes) > 0:
+ # find global resume value
+ for w in pending_writes:
+ if w[0] == NULL_TASK_ID and w[1] == RESUME:
+ null_resume_write = w
+ break
+ else:
+ # None cannot be used as a resume value, because it would be difficult to
+ # distinguish from missing when used over http
+ null_resume_write = None
+
+ # find task-specific resume value
+ for w in pending_writes:
+ if w[0] == task_id and w[1] == RESUME:
+ task_resume_write = w[2]
+ if not isinstance(task_resume_write, list):
+ task_resume_write = [task_resume_write]
+ break
+ else:
+ task_resume_write = []
+ del w
+
+ # find namespace and task-specific resume value
+ if resume_map and namespace_hash in resume_map:
+ mapped_resume_write = resume_map[namespace_hash]
+ task_resume_write.append(mapped_resume_write)
+
+ else:
+ null_resume_write = None
+ task_resume_write = []
+
+ def get_null_resume(consume: bool = False) -> Any:
+ if null_resume_write is None:
+ if parent_scratchpad is not None:
+ return parent_scratchpad.get_null_resume(consume)
+ return None
+ if consume:
+ try:
+ pending_writes.remove(null_resume_write)
+ return null_resume_write[2]
+ except ValueError:
+ return None
+ return null_resume_write[2]
+
+ # using itertools.count as an atomic counter (+= 1 is not thread-safe)
+ return PregelScratchpad(
+ step=step,
+ stop=stop,
+ # call
+ call_counter=LazyAtomicCounter(),
+ # interrupt
+ interrupt_counter=LazyAtomicCounter(),
+ resume=task_resume_write,
+ get_null_resume=get_null_resume,
+ # subgraph
+ subgraph_counter=LazyAtomicCounter(),
+ )
+
+
+def _proc_input(
+ proc: PregelNode,
+ managed: ManagedValueMapping,
+ channels: Mapping[str, BaseChannel],
+ *,
+ for_execution: bool,
+ scratchpad: PregelScratchpad,
+ input_cache: dict[INPUT_CACHE_KEY_TYPE, Any] | None,
+) -> Any:
+ """Prepare input for a PULL task, based on the process's channels and triggers."""
+ # if in cache return shallow copy
+ if input_cache is not None and proc.input_cache_key in input_cache:
+ return copy(input_cache[proc.input_cache_key])
+ # If all trigger channels subscribed by this process are not empty
+ # then invoke the process with the values of all non-empty channels
+ if isinstance(proc.channels, list):
+ val: dict[str, Any] = {}
+ for chan in proc.channels:
+ if chan in channels:
+ if channels[chan].is_available():
+ val[chan] = channels[chan].get()
+ else:
+ val[chan] = managed[chan].get(scratchpad)
+ elif isinstance(proc.channels, str):
+ if proc.channels in channels:
+ if channels[proc.channels].is_available():
+ val = channels[proc.channels].get()
+ else:
+ return MISSING
+ else:
+ return MISSING
+ else:
+ raise RuntimeError(
+ f"Invalid channels type, expected list or dict, got {proc.channels}"
+ )
+
+ # If the process has a mapper, apply it to the value
+ if for_execution and proc.mapper is not None:
+ val = proc.mapper(val)
+
+ # Cache the input value
+ if input_cache is not None:
+ input_cache[proc.input_cache_key] = val
+
+ return val
+
+
+def _uuid5_str(namespace: bytes, *parts: str | bytes) -> str:
+ """Generate a UUID from the SHA-1 hash of a namespace and str parts."""
+
+ sha = sha1(namespace, usedforsecurity=False)
+ sha.update(b"".join(p.encode() if isinstance(p, str) else p for p in parts))
+ hex = sha.hexdigest()
+ return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:32]}"
+
+
+def _xxhash_str(namespace: bytes, *parts: str | bytes) -> str:
+ """Generate a UUID from the XXH3 hash of a namespace and str parts."""
+ hex = xxh3_128_hexdigest(
+ namespace + b"".join(p.encode() if isinstance(p, str) else p for p in parts)
+ )
+ return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:32]}"
+
+
+def task_path_str(tup: str | int | tuple) -> str:
+ """Generate a string representation of the task path."""
+ return (
+ f"~{', '.join(task_path_str(x) for x in tup)}"
+ if isinstance(tup, (tuple, list))
+ else f"{tup:010d}"
+ if isinstance(tup, int)
+ else str(tup)
+ )
+
+
+LAZY_ATOMIC_COUNTER_LOCK = threading.Lock()
+
+
+class LazyAtomicCounter:
+ __slots__ = ("_counter",)
+
+ _counter: Callable[[], int] | None
+
+ def __init__(self) -> None:
+ self._counter = None
+
+ def __call__(self) -> int:
+ if self._counter is None:
+ with LAZY_ATOMIC_COUNTER_LOCK:
+ if self._counter is None:
+ self._counter = itertools.count(0).__next__
+ return self._counter()
+
+
+def sanitize_untracked_values_in_send(
+ packet: Send, channels: Mapping[str, BaseChannel]
+) -> Send:
+ """Pop any values belonging to UntrackedValue channels in Send.arg for safe checkpointing.
+
+ Send is often called with state to be passed to the dest node, which may contain
+ UntrackedValues at the top level. Send is not typed and arg may be a nested dict."""
+
+ if not isinstance(packet.arg, dict):
+ # Command
+ return packet
+
+ # top level keys should be the channel names
+ sanitized_arg = {
+ k: v
+ for k, v in packet.arg.items()
+ if not isinstance(channels.get(k), UntrackedValue)
+ }
+ return Send(node=packet.node, arg=sanitized_arg, timeout=packet.timeout)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_call.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_call.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c3fb385668850fc9d3a626823849fc576fe7a2a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_call.py
@@ -0,0 +1,298 @@
+"""Utility to convert a user provided function into a Runnable with a ChannelWrite."""
+
+from __future__ import annotations
+
+import concurrent.futures
+import functools
+import inspect
+import sys
+import types
+from collections.abc import Awaitable, Callable, Generator, Sequence
+from datetime import timedelta
+from typing import Any, Generic, TypeVar, cast
+
+from langchain_core.runnables import Runnable
+from typing_extensions import ParamSpec
+
+from langgraph._internal._constants import CONF, CONFIG_KEY_CALL, RETURN
+from langgraph._internal._runnable import (
+ RunnableCallable,
+ RunnableSeq,
+ is_async_callable,
+ run_in_executor,
+)
+from langgraph._internal._timeout import (
+ coerce_timeout_policy,
+ sync_timeout_unsupported,
+)
+from langgraph.config import get_config
+from langgraph.pregel._write import ChannelWrite, ChannelWriteEntry
+from langgraph.types import CachePolicy, RetryPolicy, TimeoutPolicy
+
+##
+# Utilities borrowed from cloudpickle.
+# https://github.com/cloudpipe/cloudpickle/blob/6220b0ce83ffee5e47e06770a1ee38ca9e47c850/cloudpickle/cloudpickle.py#L265
+
+
+def _getattribute(obj: Any, name: str) -> Any:
+ parent = None
+ for subpath in name.split("."):
+ if subpath == "":
+ raise AttributeError(f"Can't get local attribute {name!r} on {obj!r}")
+ try:
+ parent = obj
+ obj = getattr(obj, subpath)
+ except AttributeError:
+ raise AttributeError(f"Can't get attribute {name!r} on {obj!r}") from None
+ return obj, parent
+
+
+def _whichmodule(obj: Any, name: str) -> str | None:
+ """Find the module an object belongs to.
+
+ This function differs from ``pickle.whichmodule`` in two ways:
+ - it does not mangle the cases where obj's module is __main__ and obj was
+ not found in any module.
+ - Errors arising during module introspection are ignored, as those errors
+ are considered unwanted side effects.
+ """
+ module_name = getattr(obj, "__module__", None)
+
+ if module_name is not None:
+ return module_name
+ # Protect the iteration by using a copy of sys.modules against dynamic
+ # modules that trigger imports of other modules upon calls to getattr or
+ # other threads importing at the same time.
+ for module_name, module in sys.modules.copy().items():
+ # Some modules such as coverage can inject non-module objects inside
+ # sys.modules
+ if (
+ module_name == "__main__"
+ or module_name == "__mp_main__"
+ or module is None
+ or not isinstance(module, types.ModuleType)
+ ):
+ continue
+ try:
+ if _getattribute(module, name)[0] is obj:
+ return module_name
+ except Exception:
+ pass
+ return None
+
+
+def identifier(obj: Any, name: str | None = None) -> str | None:
+ """Return the module and name of an object."""
+ from langgraph._internal._runnable import RunnableCallable, RunnableSeq
+ from langgraph.pregel._read import PregelNode
+
+ if isinstance(obj, PregelNode):
+ obj = obj.bound
+ if isinstance(obj, RunnableSeq):
+ obj = obj.steps[0]
+ if isinstance(obj, RunnableCallable):
+ obj = obj.func
+ if name is None:
+ name = getattr(obj, "__qualname__", None)
+ if name is None: # pragma: no cover
+ # This used to be needed for Python 2.7 support but is probably not
+ # needed anymore. However we keep the __name__ introspection in case
+ # users of cloudpickle rely on this old behavior for unknown reasons.
+ name = getattr(obj, "__name__", None)
+ if name is None:
+ return None
+
+ module_name = getattr(obj, "__module__", None)
+ if module_name is None:
+ # In this case, obj.__module__ is None. obj is thus treated as dynamic.
+ return None
+
+ return f"{module_name}.{name}"
+
+
+def _lookup_module_and_qualname(
+ obj: Any, name: str | None = None
+) -> tuple[types.ModuleType, str] | None:
+ if name is None:
+ name = getattr(obj, "__qualname__", None)
+ if name is None: # pragma: no cover
+ # This used to be needed for Python 2.7 support but is probably not
+ # needed anymore. However we keep the __name__ introspection in case
+ # users of cloudpickle rely on this old behavior for unknown reasons.
+ name = getattr(obj, "__name__", None)
+ if name is None:
+ return None
+
+ module_name = _whichmodule(obj, name)
+
+ if module_name is None:
+ # In this case, obj.__module__ is None AND obj was not found in any
+ # imported module. obj is thus treated as dynamic.
+ return None
+
+ if module_name == "__main__":
+ return None
+
+ # Note: if module_name is in sys.modules, the corresponding module is
+ # assumed importable at unpickling time. See #357
+ module = sys.modules.get(module_name, None)
+ if module is None:
+ # The main reason why obj's module would not be imported is that this
+ # module has been dynamically created, using for example
+ # types.ModuleType. The other possibility is that module was removed
+ # from sys.modules after obj was created/imported. But this case is not
+ # supported, as the standard pickle does not support it either.
+ return None
+
+ try:
+ obj2, parent = _getattribute(module, name)
+ except AttributeError:
+ # obj was not found inside the module it points to
+ return None
+ if obj2 is not obj:
+ return None
+ return module, name
+
+
+def _explode_args_trace_inputs(
+ sig: inspect.Signature, input: tuple[tuple[Any, ...], dict[str, Any]]
+) -> dict[str, Any]:
+ args, kwargs = input
+ bound = sig.bind_partial(*args, **kwargs)
+ bound.apply_defaults()
+ arguments = dict(bound.arguments)
+ arguments.pop("self", None)
+ arguments.pop("cls", None)
+ for param_name, param in sig.parameters.items():
+ if param.kind == inspect.Parameter.VAR_KEYWORD:
+ # Update with the **kwargs, and remove the original entry
+ # This is to help flatten out keyword arguments
+ if param_name in arguments:
+ arguments.update(arguments.pop(param_name))
+ return arguments
+
+
+def get_runnable_for_entrypoint(func: Callable[..., Any]) -> Runnable:
+ key = (func, False)
+ if key in CACHE:
+ return CACHE[key]
+ else:
+ if is_async_callable(func):
+ run = RunnableCallable(
+ None, func, name=func.__name__, trace=False, recurse=False
+ )
+ else:
+ afunc = functools.update_wrapper(
+ functools.partial(run_in_executor, None, func), func
+ )
+ run = RunnableCallable(
+ func,
+ afunc,
+ name=func.__name__,
+ trace=False,
+ recurse=False,
+ )
+ if not _lookup_module_and_qualname(func):
+ return run
+ return CACHE.setdefault(key, run)
+
+
+def get_runnable_for_task(func: Callable[..., Any]) -> Runnable:
+ key = (func, True)
+ if key in CACHE:
+ return CACHE[key]
+ else:
+ if hasattr(func, "__name__"):
+ name = func.__name__
+ elif hasattr(func, "func"):
+ name = func.func.__name__
+ elif hasattr(func, "__class__"):
+ name = func.__class__.__name__
+ else:
+ name = str(func)
+
+ if is_async_callable(func):
+ run = RunnableCallable(
+ None,
+ func,
+ explode_args=True,
+ name=name,
+ trace=False,
+ recurse=False,
+ )
+ else:
+ run = RunnableCallable(
+ func,
+ functools.wraps(func)(functools.partial(run_in_executor, None, func)),
+ explode_args=True,
+ name=name,
+ trace=False,
+ recurse=False,
+ )
+ seq = RunnableSeq(
+ run,
+ ChannelWrite([ChannelWriteEntry(RETURN)]),
+ name=name,
+ trace_inputs=functools.partial(
+ _explode_args_trace_inputs, inspect.signature(func)
+ ),
+ )
+ if not _lookup_module_and_qualname(func):
+ return seq
+ return CACHE.setdefault(key, seq)
+
+
+CACHE: dict[tuple[Callable[..., Any], bool], Runnable] = {}
+
+
+P = ParamSpec("P")
+P1 = TypeVar("P1")
+T = TypeVar("T")
+
+
+class SyncAsyncFuture(Generic[T], concurrent.futures.Future[T]):
+ def __await__(self) -> Generator[T, None, T]:
+ yield cast(T, ...)
+
+
+def call(
+ func: Callable[P, Awaitable[T]] | Callable[P, T],
+ *args: Any,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Any,
+) -> SyncAsyncFuture[T]:
+ return _call_with_options(
+ func,
+ args,
+ kwargs,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ timeout=coerce_timeout_policy(timeout),
+ )
+
+
+def _call_with_options(
+ func: Callable[P, Awaitable[T]] | Callable[P, T],
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+) -> SyncAsyncFuture[T]:
+ if timeout is not None and not is_async_callable(func):
+ name = getattr(func, "__name__", func.__class__.__name__)
+ raise sync_timeout_unsupported(name, kind="Task")
+ config = get_config()
+ impl = config[CONF][CONFIG_KEY_CALL]
+ fut = impl(
+ func,
+ (args, kwargs),
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ callbacks=config["callbacks"],
+ timeout=timeout,
+ )
+ return fut
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_checkpoint.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..081bc69bf2ffa528299b52492ecc0258f952ee60
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_checkpoint.py
@@ -0,0 +1,238 @@
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
+from datetime import datetime, timezone
+from typing import Any, cast
+
+from langchain_core.runnables import RunnableConfig
+from langgraph.checkpoint.base import (
+ BaseCheckpointSaver,
+ Checkpoint,
+)
+from langgraph.checkpoint.base.id import uuid6
+from langgraph.checkpoint.serde.types import _DeltaSnapshot
+
+from langgraph._internal._config import DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.delta import DeltaChannel
+from langgraph.managed.base import ManagedValueMapping, ManagedValueSpec
+
+LATEST_VERSION = 4
+
+GetNextVersion = Callable[[Any, None], Any]
+
+
+def empty_checkpoint() -> Checkpoint:
+ return Checkpoint(
+ v=LATEST_VERSION,
+ id=str(uuid6(clock_seq=-2)),
+ ts=datetime.now(timezone.utc).isoformat(),
+ channel_values={},
+ channel_versions={},
+ versions_seen={},
+ )
+
+
+def delta_channels_to_snapshot(
+ channels: Mapping[str, BaseChannel],
+ counters_since_delta_snapshot: Mapping[str, tuple[int, int]],
+) -> set[str]:
+ """Return the set of DeltaChannel names that should snapshot now.
+
+ A channel snapshots when EITHER its accumulated update count reaches
+ `snapshot_frequency` OR the total supersteps since its last snapshot
+ reaches `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. This is a pure
+ predicate — no mutation.
+ """
+ result: set[str] = set()
+ for name, ch in channels.items():
+ if not isinstance(ch, DeltaChannel) or not ch.is_available():
+ continue
+ updates, supersteps = counters_since_delta_snapshot.get(name, (0, 0))
+ if (
+ updates >= ch.snapshot_frequency
+ or supersteps >= DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT
+ ):
+ result.add(name)
+ return result
+
+
+def create_checkpoint(
+ checkpoint: Checkpoint,
+ channels: Mapping[str, BaseChannel] | None,
+ step: int,
+ *,
+ id: str | None = None,
+ updated_channels: set[str] | None = None,
+ get_next_version: GetNextVersion | None = None,
+ channels_to_snapshot: set[str] | None = None,
+) -> Checkpoint:
+ """Build a new Checkpoint from the previous one and live channel state.
+
+ For each name in `channels_to_snapshot`, a `_DeltaSnapshot(value)` blob
+ is written into `channel_values[k]`. Other delta channels are omitted
+ from `channel_values` — the ancestor walk reconstructs their state
+ from `checkpoint_writes`. Callers compute the set via
+ `delta_channels_to_snapshot(channels, counters)`; defaults to empty
+ (no snapshots) when not provided.
+ """
+ ts = datetime.now(timezone.utc).isoformat()
+ channels_to_snapshot = channels_to_snapshot or set()
+ if channels is None:
+ values = checkpoint["channel_values"]
+ channel_versions = checkpoint["channel_versions"]
+ else:
+ values = {}
+ channel_versions = dict(checkpoint["channel_versions"])
+ for k in channels:
+ if k not in channel_versions:
+ continue
+ ch = channels[k]
+ if k in channels_to_snapshot:
+ # In exit mode, the snapshot decision is deferred to exit
+ # time (intermediate steps have do_checkpoint=False). The
+ # channel's count may have reached snapshot_frequency over
+ # several supersteps, but the LAST superstep may not have
+ # written to this channel. In that case apply_writes()
+ # (in _algo.py) didn't bump this channel's version, so
+ # saver.put() wouldn't include it in new_versions and
+ # the snapshot blob would be silently dropped. The manual
+ # bump below closes the gap. In sync/async durability this
+ # branch is effectively dead code (the step that pushes
+ # the count to freq always writes the channel).
+ if get_next_version is not None and (
+ updated_channels is None or k not in updated_channels
+ ):
+ channel_versions[k] = get_next_version(channel_versions[k], None)
+ values[k] = _DeltaSnapshot(ch.get())
+ else:
+ v = ch.checkpoint()
+ if v is not MISSING:
+ values[k] = v
+ return Checkpoint(
+ v=LATEST_VERSION,
+ ts=ts,
+ id=id or str(uuid6(clock_seq=step)),
+ channel_values=values,
+ channel_versions=channel_versions,
+ versions_seen=checkpoint["versions_seen"],
+ updated_channels=None if updated_channels is None else sorted(updated_channels),
+ )
+
+
+def _needs_replay(spec: BaseChannel, stored: object) -> bool:
+ """True if `spec` is a `DeltaChannel` and no value is stored at this
+ checkpoint, requiring an ancestor walk to reconstruct.
+
+ `_DeltaSnapshot` blobs and plain values (migration) resolve directly via
+ `from_checkpoint` — only absence (`MISSING`) triggers replay.
+ """
+ if not isinstance(spec, DeltaChannel):
+ return False
+ return stored is MISSING
+
+
+def channels_from_checkpoint(
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ checkpoint: Checkpoint,
+ *,
+ saver: BaseCheckpointSaver | None = None,
+ config: RunnableConfig | None = None,
+) -> tuple[Mapping[str, BaseChannel], ManagedValueMapping]:
+ """Hydrate channels from a checkpoint.
+
+ For most channels, `spec.from_checkpoint(checkpoint["channel_values"][k])`
+ is sufficient. `DeltaChannel` is the exception: when the channel is
+ absent from `channel_values`, an ancestor walk via
+ `saver.get_delta_channel_history` is required to find the nearest seed
+ (`_DeltaSnapshot` blob or pre-migration plain value) and accumulate
+ the writes between it and the target. All delta channels needing
+ replay are batched into a single saver call.
+ """
+ channel_specs: dict[str, BaseChannel] = {}
+ managed_specs: dict[str, ManagedValueSpec] = {}
+ for k, v in specs.items():
+ if isinstance(v, BaseChannel):
+ channel_specs[k] = v
+ else:
+ managed_specs[k] = v
+
+ delta_channels: list[str] = [
+ k
+ for k, spec in channel_specs.items()
+ if _needs_replay(spec, checkpoint["channel_values"].get(k, MISSING))
+ ]
+ histories: Mapping[str, Any] = {}
+ if delta_channels and saver is not None and config is not None:
+ histories = saver.get_delta_channel_history(
+ config=config, channels=delta_channels
+ )
+
+ channels: dict[str, BaseChannel] = {}
+ for k, spec in channel_specs.items():
+ ch: BaseChannel
+ if k in histories:
+ delta_spec = cast(DeltaChannel, spec)
+ history = histories[k]
+ replay_ch = delta_spec.from_checkpoint(history.get("seed", MISSING))
+ replay_ch.replay_writes(history["writes"])
+ ch = replay_ch
+ else:
+ ch = spec.from_checkpoint(checkpoint["channel_values"].get(k, MISSING))
+ channels[k] = ch
+ return channels, managed_specs
+
+
+async def achannels_from_checkpoint(
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ checkpoint: Checkpoint,
+ *,
+ saver: BaseCheckpointSaver | None = None,
+ config: RunnableConfig | None = None,
+) -> tuple[Mapping[str, BaseChannel], ManagedValueMapping]:
+ """Async version of `channels_from_checkpoint`. See docstring there."""
+ channel_specs: dict[str, BaseChannel] = {}
+ managed_specs: dict[str, ManagedValueSpec] = {}
+ for k, v in specs.items():
+ if isinstance(v, BaseChannel):
+ channel_specs[k] = v
+ else:
+ managed_specs[k] = v
+
+ delta_channels: list[str] = [
+ k
+ for k, spec in channel_specs.items()
+ if _needs_replay(spec, checkpoint["channel_values"].get(k, MISSING))
+ ]
+ histories: Mapping[str, Any] = {}
+ if delta_channels and saver is not None and config is not None:
+ histories = await saver.aget_delta_channel_history(
+ config=config, channels=delta_channels
+ )
+
+ channels: dict[str, BaseChannel] = {}
+ for k, spec in channel_specs.items():
+ ch: BaseChannel
+ if k in histories:
+ delta_spec = cast(DeltaChannel, spec)
+ history = histories[k]
+ replay_ch = delta_spec.from_checkpoint(history.get("seed", MISSING))
+ replay_ch.replay_writes(history["writes"])
+ ch = replay_ch
+ else:
+ ch = spec.from_checkpoint(checkpoint["channel_values"].get(k, MISSING))
+ channels[k] = ch
+ return channels, managed_specs
+
+
+def copy_checkpoint(checkpoint: Checkpoint) -> Checkpoint:
+ return Checkpoint(
+ v=checkpoint["v"],
+ ts=checkpoint["ts"],
+ id=checkpoint["id"],
+ channel_values=checkpoint["channel_values"].copy(),
+ channel_versions=checkpoint["channel_versions"].copy(),
+ versions_seen={k: v.copy() for k, v in checkpoint["versions_seen"].items()},
+ updated_channels=checkpoint.get("updated_channels", None),
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_executor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..10a43cf2b3cb8e20030bec5f5526b4546089bf8f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_executor.py
@@ -0,0 +1,223 @@
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import time
+from collections.abc import Awaitable, Callable, Coroutine
+from contextlib import AbstractAsyncContextManager, AbstractContextManager, ExitStack
+from contextvars import copy_context
+from types import TracebackType
+from typing import (
+ Protocol,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.runnables import RunnableConfig
+from langchain_core.runnables.config import get_executor_for_config
+from typing_extensions import ParamSpec
+
+from langgraph._internal._future import CONTEXT_NOT_SUPPORTED, run_coroutine_threadsafe
+from langgraph.errors import GraphBubbleUp
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+class Submit(Protocol[P, T]):
+ def __call__( # type: ignore[valid-type]
+ self,
+ fn: Callable[P, T],
+ *args: P.args,
+ __name__: str | None = None,
+ __cancel_on_exit__: bool = False,
+ __reraise_on_exit__: bool = True,
+ __next_tick__: bool = False,
+ **kwargs: P.kwargs,
+ ) -> concurrent.futures.Future[T]: ...
+
+
+class BackgroundExecutor(AbstractContextManager):
+ """A context manager that runs sync tasks in the background.
+ Uses a thread pool executor to delegate tasks to separate threads.
+ On exit,
+ - cancels any (not yet started) tasks with `__cancel_on_exit__=True`
+ - waits for all tasks to finish
+ - re-raises the first exception from tasks with `__reraise_on_exit__=True`"""
+
+ def __init__(self, config: RunnableConfig) -> None:
+ self.stack = ExitStack()
+ self.executor = self.stack.enter_context(get_executor_for_config(config))
+ # mapping of Future to (__cancel_on_exit__, __reraise_on_exit__) flags
+ self.tasks: dict[concurrent.futures.Future, tuple[bool, bool]] = {}
+
+ def submit( # type: ignore[valid-type]
+ self,
+ fn: Callable[P, T],
+ *args: P.args,
+ __name__: str | None = None, # currently not used in sync version
+ __cancel_on_exit__: bool = False, # for sync, can cancel only if not started
+ __reraise_on_exit__: bool = True,
+ __next_tick__: bool = False,
+ **kwargs: P.kwargs,
+ ) -> concurrent.futures.Future[T]:
+ ctx = copy_context()
+ if __next_tick__:
+ task = cast(
+ concurrent.futures.Future[T],
+ self.executor.submit(next_tick, ctx.run, fn, *args, **kwargs), # type: ignore[arg-type]
+ )
+ else:
+ task = self.executor.submit(ctx.run, fn, *args, **kwargs)
+ self.tasks[task] = (__cancel_on_exit__, __reraise_on_exit__)
+ # add a callback to remove the task from the tasks dict when it's done
+ task.add_done_callback(self.done)
+ return task
+
+ def done(self, task: concurrent.futures.Future) -> None:
+ """Remove the task from the tasks dict when it's done."""
+ try:
+ task.result()
+ except GraphBubbleUp:
+ # This exception is an interruption signal, not an error
+ # so we don't want to re-raise it on exit
+ self.tasks.pop(task)
+ except BaseException:
+ pass
+ else:
+ self.tasks.pop(task)
+
+ def __enter__(self) -> Submit:
+ return self.submit
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # copy the tasks as done() callback may modify the dict
+ tasks = self.tasks.copy()
+ # cancel all tasks that should be cancelled
+ for task, (cancel, _) in tasks.items():
+ if cancel:
+ task.cancel()
+ # wait for all tasks to finish
+ if pending := {t for t in tasks if not t.done()}:
+ concurrent.futures.wait(pending)
+ # shutdown the executor
+ self.stack.__exit__(exc_type, exc_value, traceback)
+ # if there's already an exception being raised, don't raise another one
+ if exc_type is None:
+ # re-raise the first exception that occurred in a task
+ for task, (_, reraise) in tasks.items():
+ if not reraise:
+ continue
+ try:
+ task.result()
+ except concurrent.futures.CancelledError:
+ pass
+
+
+class AsyncBackgroundExecutor(AbstractAsyncContextManager):
+ """A context manager that runs async tasks in the background.
+ Uses the current event loop to delegate tasks to asyncio tasks.
+ On exit,
+ - cancels any tasks with `__cancel_on_exit__=True`
+ - waits for all tasks to finish
+ - re-raises the first exception from tasks with `__reraise_on_exit__=True`
+ ignoring CancelledError"""
+
+ def __init__(self, config: RunnableConfig) -> None:
+ self.tasks: dict[asyncio.Future, tuple[bool, bool]] = {}
+ self.sentinel = object()
+ self.loop = asyncio.get_running_loop()
+ if max_concurrency := config.get("max_concurrency"):
+ self.semaphore: asyncio.Semaphore | None = asyncio.Semaphore(
+ max_concurrency
+ )
+ else:
+ self.semaphore = None
+
+ def submit( # type: ignore[valid-type]
+ self,
+ fn: Callable[P, Awaitable[T]],
+ *args: P.args,
+ __name__: str | None = None,
+ __cancel_on_exit__: bool = False,
+ __reraise_on_exit__: bool = True,
+ __next_tick__: bool = False, # noop in async (always True)
+ **kwargs: P.kwargs,
+ ) -> asyncio.Future[T]:
+ coro = cast(Coroutine[None, None, T], fn(*args, **kwargs))
+ if self.semaphore:
+ coro = gated(self.semaphore, coro)
+ if CONTEXT_NOT_SUPPORTED:
+ task = run_coroutine_threadsafe(
+ coro, self.loop, name=__name__, lazy=__next_tick__
+ )
+ else:
+ task = run_coroutine_threadsafe(
+ coro,
+ self.loop,
+ name=__name__,
+ context=copy_context(),
+ lazy=__next_tick__,
+ )
+ self.tasks[task] = (__cancel_on_exit__, __reraise_on_exit__)
+ task.add_done_callback(self.done)
+ return task
+
+ def done(self, task: asyncio.Future) -> None:
+ try:
+ if exc := task.exception():
+ # This exception is an interruption signal, not an error
+ # so we don't want to re-raise it on exit
+ if isinstance(exc, GraphBubbleUp):
+ self.tasks.pop(task)
+ else:
+ self.tasks.pop(task)
+ except asyncio.CancelledError:
+ self.tasks.pop(task)
+
+ async def __aenter__(self) -> Submit:
+ return self.submit
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ # copy the tasks as done() callback may modify the dict
+ tasks = self.tasks.copy()
+ # cancel all tasks that should be cancelled
+ for task, (cancel, _) in tasks.items():
+ if cancel:
+ task.cancel(self.sentinel)
+ # wait for all tasks to finish
+ if tasks:
+ await asyncio.wait(tasks)
+ # if there's already an exception being raised, don't raise another one
+ if exc_type is None:
+ # re-raise the first exception that occurred in a task
+ for task, (_, reraise) in tasks.items():
+ if not reraise:
+ continue
+ try:
+ if exc := task.exception():
+ raise exc
+ except asyncio.CancelledError:
+ pass
+
+
+async def gated(semaphore: asyncio.Semaphore, coro: Coroutine[None, None, T]) -> T:
+ """A coroutine that waits for a semaphore before running another coroutine."""
+ async with semaphore:
+ return await coro
+
+
+def next_tick(fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
+ """A function that yields control to other threads before running another function."""
+ time.sleep(0)
+ return fn(*args, **kwargs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_io.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c05dbda70ed04f1038268a201000d5141535832
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_io.py
@@ -0,0 +1,174 @@
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Any, Literal
+
+from langgraph._internal._constants import (
+ ERROR,
+ INTERRUPT,
+ NULL_TASK_ID,
+ RESUME,
+ RETURN,
+ TASKS,
+)
+from langgraph._internal._typing import EMPTY_SEQ, MISSING
+from langgraph.channels.base import BaseChannel, EmptyChannelError
+from langgraph.constants import START, TAG_HIDDEN
+from langgraph.errors import InvalidUpdateError
+from langgraph.pregel._log import logger
+from langgraph.types import Command, PregelExecutableTask, Send
+
+
+def read_channel(
+ channels: Mapping[str, BaseChannel],
+ chan: str,
+ *,
+ catch: bool = True,
+) -> Any:
+ try:
+ return channels[chan].get()
+ except EmptyChannelError:
+ if catch:
+ return None
+ else:
+ raise
+
+
+def read_channels(
+ channels: Mapping[str, BaseChannel],
+ select: Sequence[str] | str,
+ *,
+ skip_empty: bool = True,
+) -> dict[str, Any] | Any:
+ if isinstance(select, str):
+ return read_channel(channels, select)
+ else:
+ values: dict[str, Any] = {}
+ for k in select:
+ try:
+ values[k] = read_channel(channels, k, catch=not skip_empty)
+ except EmptyChannelError:
+ pass
+ return values
+
+
+def map_command(cmd: Command) -> Iterator[tuple[str, str, Any]]:
+ """Map input chunk to a sequence of pending writes in the form (channel, value)."""
+ if cmd.graph == Command.PARENT:
+ raise InvalidUpdateError("There is no parent graph")
+ if cmd.goto:
+ if isinstance(cmd.goto, (tuple, list)):
+ sends = cmd.goto
+ else:
+ sends = [cmd.goto]
+ for send in sends:
+ if isinstance(send, Send):
+ yield (NULL_TASK_ID, TASKS, send)
+ elif isinstance(send, str):
+ yield (NULL_TASK_ID, f"branch:to:{send}", START)
+ else:
+ raise TypeError(
+ f"In Command.goto, expected Send/str, got {type(send).__name__}"
+ )
+ if cmd.resume is not None:
+ yield (NULL_TASK_ID, RESUME, cmd.resume)
+ if cmd.update:
+ for k, v in cmd._update_as_tuples():
+ yield (NULL_TASK_ID, k, v)
+
+
+def map_input(
+ input_channels: str | Sequence[str],
+ chunk: dict[str, Any] | Any | None,
+) -> Iterator[tuple[str, Any]]:
+ """Map input chunk to a sequence of pending writes in the form (channel, value)."""
+ if chunk is None:
+ return
+ elif isinstance(input_channels, str):
+ yield (input_channels, chunk)
+ else:
+ if not isinstance(chunk, dict):
+ raise TypeError(f"Expected chunk to be a dict, got {type(chunk).__name__}")
+ for k in chunk:
+ if k in input_channels:
+ yield (k, chunk[k])
+ else:
+ logger.warning(f"Input channel {k} not found in {input_channels}")
+
+
+def map_output_values(
+ output_channels: str | Sequence[str],
+ pending_writes: Literal[True] | Sequence[tuple[str, Any]],
+ channels: Mapping[str, BaseChannel],
+) -> Iterator[dict[str, Any] | Any]:
+ """Map pending writes (a sequence of tuples (channel, value)) to output chunk."""
+ if isinstance(output_channels, str):
+ if pending_writes is True or any(
+ chan == output_channels for chan, _ in pending_writes
+ ):
+ yield read_channel(channels, output_channels)
+ else:
+ if pending_writes is True or {
+ c for c, _ in pending_writes if c in output_channels
+ }:
+ yield read_channels(channels, output_channels)
+
+
+def map_output_updates(
+ output_channels: str | Sequence[str],
+ tasks: list[tuple[PregelExecutableTask, Sequence[tuple[str, Any]]]],
+ cached: bool = False,
+) -> Iterator[dict[str, Any | dict[str, Any]]]:
+ """Map pending writes (a sequence of tuples (channel, value)) to output chunk."""
+ output_tasks = [
+ (t, ww)
+ for t, ww in tasks
+ if (not t.config or TAG_HIDDEN not in t.config.get("tags", EMPTY_SEQ))
+ and ww[0][0] != ERROR
+ and ww[0][0] != INTERRUPT
+ ]
+ if not output_tasks:
+ return
+ updated: list[tuple[str, Any]] = []
+ for task, writes in output_tasks:
+ rtn = next((value for chan, value in writes if chan == RETURN), MISSING)
+ if rtn is not MISSING:
+ updated.append((task.name, rtn))
+ elif isinstance(output_channels, str):
+ updated.extend(
+ (task.name, value) for chan, value in writes if chan == output_channels
+ )
+ elif any(chan in output_channels for chan, _ in writes):
+ counts = Counter(chan for chan, _ in writes)
+ if any(counts[chan] > 1 for chan in output_channels):
+ updated.extend(
+ (
+ task.name,
+ {chan: value},
+ )
+ for chan, value in writes
+ if chan in output_channels
+ )
+ else:
+ updated.append(
+ (
+ task.name,
+ {
+ chan: value
+ for chan, value in writes
+ if chan in output_channels
+ },
+ )
+ )
+ grouped: dict[str, Any] = {t.name: [] for t, _ in output_tasks}
+ for node, value in updated:
+ grouped[node].append(value)
+ for node, value in grouped.items():
+ if len(value) == 0:
+ grouped[node] = None
+ if len(value) == 1:
+ grouped[node] = value[0]
+ if cached:
+ grouped["__metadata__"] = {"cached": cached}
+ yield grouped
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_log.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd127777b23fab1a3daa78b552a93b1a13ce38b1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_log.py
@@ -0,0 +1,3 @@
+import logging
+
+logger = logging.getLogger("langgraph")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_loop.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..587f5905ae409a8a37f9f3dd13d1d22fb7261408
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_loop.py
@@ -0,0 +1,1963 @@
+from __future__ import annotations
+
+import asyncio
+import binascii
+import concurrent.futures
+from collections import defaultdict, deque
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from contextlib import (
+ AbstractAsyncContextManager,
+ AbstractContextManager,
+ AsyncExitStack,
+ ExitStack,
+)
+from datetime import datetime, timezone
+from inspect import signature
+from types import TracebackType
+from typing import (
+ Any,
+ Literal,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.callbacks import AsyncParentRunManager, ParentRunManager
+from langchain_core.runnables import RunnableConfig
+from langgraph.cache.base import BaseCache
+from langgraph.checkpoint.base import (
+ WRITES_IDX_MAP,
+ BaseCheckpointSaver,
+ ChannelVersions,
+ Checkpoint,
+ CheckpointMetadata,
+ CheckpointTuple,
+ PendingWrite,
+)
+from langgraph.store.base import BaseStore
+from typing_extensions import ParamSpec, Self
+
+from langgraph._internal._config import patch_configurable
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_REPLAY_STATE,
+ CONFIG_KEY_RESUME_MAP,
+ CONFIG_KEY_RESUMING,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SCRATCHPAD,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ INPUT,
+ INTERRUPT,
+ NS_END,
+ NS_SEP,
+ NULL_TASK_ID,
+ PUSH,
+ RESUME,
+ TASKS,
+)
+from langgraph._internal._replay import ReplayState
+from langgraph._internal._scratchpad import PregelScratchpad
+from langgraph._internal._typing import EMPTY_SEQ, MISSING
+from langgraph.callbacks import (
+ GraphInterruptEvent,
+ GraphLifecycleEvent,
+ GraphResumeEvent,
+)
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.delta import DeltaChannel
+from langgraph.channels.untracked_value import UntrackedValue
+from langgraph.constants import TAG_HIDDEN
+from langgraph.errors import (
+ EmptyInputError,
+ GraphInterrupt,
+)
+from langgraph.managed.base import (
+ ManagedValueMapping,
+ ManagedValueSpec,
+)
+from langgraph.pregel._algo import (
+ Call,
+ GetNextVersion,
+ PregelTaskWrites,
+ apply_writes,
+ checkpoint_null_version,
+ increment,
+ prepare_next_tasks,
+ prepare_node_error_handler_task,
+ prepare_single_task,
+ sanitize_untracked_values_in_send,
+ should_interrupt,
+ task_path_str,
+)
+from langgraph.pregel._checkpoint import (
+ achannels_from_checkpoint,
+ channels_from_checkpoint,
+ copy_checkpoint,
+ create_checkpoint,
+ delta_channels_to_snapshot,
+ empty_checkpoint,
+)
+from langgraph.pregel._executor import (
+ AsyncBackgroundExecutor,
+ BackgroundExecutor,
+ Submit,
+)
+from langgraph.pregel._io import (
+ map_command,
+ map_input,
+ map_output_updates,
+ map_output_values,
+ read_channels,
+)
+from langgraph.pregel._messages import ensure_message_ids
+from langgraph.pregel._read import PregelNode
+from langgraph.pregel._utils import get_new_channel_versions, is_xxh3_128_hexdigest
+from langgraph.pregel.debug import (
+ map_debug_checkpoint,
+ map_debug_task_results,
+ map_debug_tasks,
+)
+from langgraph.pregel.protocol import StreamChunk, StreamProtocol
+from langgraph.runtime import RunControl, Runtime
+from langgraph.types import (
+ All,
+ CachePolicy,
+ Command,
+ Durability,
+ Interrupt,
+ PregelExecutableTask,
+ RetryPolicy,
+ Send,
+ StreamMode,
+)
+
+V = TypeVar("V")
+P = ParamSpec("P")
+
+
+WritesT = Sequence[tuple[str, Any]]
+
+
+def DuplexStream(*streams: StreamProtocol) -> StreamProtocol:
+ def __call__(value: StreamChunk) -> None:
+ for stream in streams:
+ if value[1] in stream.modes:
+ stream(value)
+
+ return StreamProtocol(__call__, {mode for s in streams for mode in s.modes})
+
+
+class PregelLoop:
+ config: RunnableConfig
+ store: BaseStore | None
+ stream: StreamProtocol | None
+ step: int
+ stop: int
+
+ input: Any | None
+ cache: BaseCache[WritesT] | None
+ checkpointer: BaseCheckpointSaver | None
+ nodes: Mapping[str, PregelNode]
+ specs: Mapping[str, BaseChannel | ManagedValueSpec]
+ input_keys: str | Sequence[str]
+ output_keys: str | Sequence[str]
+ stream_keys: str | Sequence[str]
+ is_replaying: bool
+ is_nested: bool
+ manager: None | AsyncParentRunManager | ParentRunManager
+ interrupt_after: All | Sequence[str]
+ interrupt_before: All | Sequence[str]
+ durability: Durability
+ retry_policy: Sequence[RetryPolicy]
+ cache_policy: CachePolicy | None
+
+ checkpointer_get_next_version: GetNextVersion
+ checkpointer_put_writes: Callable[[RunnableConfig, WritesT, str], Any] | None
+ checkpointer_put_writes_accepts_task_path: bool
+ _checkpointer_put_after_previous: (
+ Callable[
+ [
+ concurrent.futures.Future | None,
+ RunnableConfig,
+ Checkpoint,
+ str,
+ ChannelVersions,
+ ],
+ Any,
+ ]
+ | None
+ )
+ _migrate_checkpoint: Callable[[Checkpoint], None] | None
+ submit: Submit
+ channels: Mapping[str, BaseChannel]
+ # Futures from `checkpointer.put_writes` calls that produced delta-channel
+ # writes. `_checkpointer_put_after_previous` drains this list (swap to a
+ # local `futs` then reset to `[]` and wait/gather) before putting the
+ # next checkpoint, so a checkpoint never becomes durable before the
+ # writes that produced it. Initialised to `[]` in both sync and async
+ # `__enter__`; stays `None` only when no checkpointer.
+ _delta_write_futs: list[Any] | None = None
+
+ # Same pattern as `_delta_write_futs` but for error-handler writes.
+ # When `put_writes` persists an ERROR_SOURCE_NODE marker, the future is
+ # appended here. `schedule_error_handler` / `aschedule_error_handler`
+ # drain this list so the write is durable before the handler starts.
+ _error_handler_write_futs: list[Any] | None = None
+
+ # Exit-mode accumulator: every delta-channel write produced during this
+ # run (input writes from `_first` + per-superstep writes captured in
+ # `after_tick`). At exit, `_put_exit_delta_writes` filters out channels
+ # that will snapshot, then persists the rest under an anchor parent.
+ # `None` when not in exit mode (so the capture sites are no-ops).
+ # Each tuple is `(step, task_id, channel, value)` — `step` drives the
+ # synthetic step-prefixed task_id used to preserve chronological order
+ # under the saver's `ORDER BY task_id, idx` sorting.
+ _exit_delta_writes: list[tuple[int, str, str, Any]] | None = None
+
+ # The checkpoint_config that points at the parent loaded at `__enter__`
+ # (or the synthetic-empty checkpoint, on first run). We capture it
+ # eagerly because every `_put_checkpoint` advances `self.checkpoint_config`
+ # to the newly-saved checkpoint's id — by exit time the original parent
+ # config would otherwise be lost. `_put_exit_delta_writes` uses this:
+ # on resumed runs as the anchor for exit delta writes; on first runs
+ # to derive the lazy stub's config (its `checkpoint_id` is the
+ # synthetic-empty id we want the stub persisted under).
+ _initial_checkpoint_config: RunnableConfig
+
+ # True iff the saver actually returned a tuple at `__enter__`. False
+ # on the first-ever run for a thread (no parent persisted yet).
+ # `_put_exit_delta_writes` uses this to decide between anchoring on
+ # the existing parent (True) or creating a lazy stub (False).
+ _has_persisted_parent: bool = False
+
+ managed: ManagedValueMapping
+ checkpoint: Checkpoint
+ checkpoint_id_saved: str
+ checkpoint_ns: tuple[str, ...]
+ checkpoint_config: RunnableConfig
+ checkpoint_metadata: CheckpointMetadata
+ checkpoint_pending_writes: list[PendingWrite]
+ checkpoint_previous_versions: dict[str, str | float | int]
+ prev_checkpoint_config: RunnableConfig | None
+
+ status: Literal[
+ "input",
+ "pending",
+ "done",
+ "draining",
+ "interrupt_before",
+ "interrupt_after",
+ "out_of_steps",
+ ]
+ control: RunControl | None
+ tasks: dict[str, PregelExecutableTask]
+ output: None | dict[str, Any] | Any = None
+ updated_channels: set[str] | None = None
+ _graph_lifecycle_events: deque[GraphLifecycleEvent]
+ _has_graph_lifecycle_callbacks: bool
+
+ # public
+
+ def __init__(
+ self,
+ input: Any | None,
+ *,
+ stream: StreamProtocol | None,
+ config: RunnableConfig,
+ store: BaseStore | None,
+ cache: BaseCache | None,
+ checkpointer: BaseCheckpointSaver | None,
+ nodes: Mapping[str, PregelNode],
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ input_keys: str | Sequence[str],
+ output_keys: str | Sequence[str],
+ stream_keys: str | Sequence[str],
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+ durability: Durability,
+ interrupt_after: All | Sequence[str] = EMPTY_SEQ,
+ interrupt_before: All | Sequence[str] = EMPTY_SEQ,
+ manager: None | AsyncParentRunManager | ParentRunManager = None,
+ migrate_checkpoint: Callable[[Checkpoint], None] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ has_graph_lifecycle_callbacks: bool = False,
+ ) -> None:
+ self.stream = stream
+ self.config = config
+ self.store = store
+ self.step = 0
+ self.stop = 0
+ self.input = input
+ self.checkpointer = checkpointer
+ self.cache = cache
+ self.nodes = nodes
+ self.specs = specs
+ self.input_keys = input_keys
+ self.output_keys = output_keys
+ self.stream_keys = stream_keys
+ self.interrupt_after = interrupt_after
+ self.interrupt_before = interrupt_before
+ self.manager = manager
+ self.is_nested = CONFIG_KEY_TASK_ID in self.config.get(CONF, {})
+ self.is_replaying = CONFIG_KEY_CHECKPOINT_ID in config[CONF]
+ self._migrate_checkpoint = migrate_checkpoint
+ self.trigger_to_nodes = trigger_to_nodes
+ self.retry_policy = retry_policy
+ self.cache_policy = cache_policy
+ self.durability = durability
+ self._has_graph_lifecycle_callbacks = has_graph_lifecycle_callbacks
+ self._graph_lifecycle_events = deque()
+ if self.stream is not None and CONFIG_KEY_STREAM in config[CONF]:
+ self.stream = DuplexStream(self.stream, config[CONF][CONFIG_KEY_STREAM])
+ scratchpad: PregelScratchpad | None = config[CONF].get(CONFIG_KEY_SCRATCHPAD)
+ if isinstance(scratchpad, PregelScratchpad):
+ # if count is > 0, append to checkpoint_ns
+ # if count is 0, leave as is
+ if cnt := scratchpad.subgraph_counter():
+ self.config = patch_configurable(
+ self.config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: NS_SEP.join(
+ (
+ config[CONF][CONFIG_KEY_CHECKPOINT_NS],
+ str(cnt),
+ )
+ )
+ },
+ )
+ if not self.is_nested and config[CONF].get(CONFIG_KEY_CHECKPOINT_NS):
+ self.config = patch_configurable(
+ self.config,
+ {CONFIG_KEY_CHECKPOINT_NS: "", CONFIG_KEY_CHECKPOINT_ID: None},
+ )
+ if (
+ CONFIG_KEY_CHECKPOINT_MAP in self.config[CONF]
+ and self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS)
+ in self.config[CONF][CONFIG_KEY_CHECKPOINT_MAP]
+ ):
+ self.checkpoint_config = patch_configurable(
+ self.config,
+ {
+ CONFIG_KEY_CHECKPOINT_ID: self.config[CONF][
+ CONFIG_KEY_CHECKPOINT_MAP
+ ][self.config[CONF][CONFIG_KEY_CHECKPOINT_NS]]
+ },
+ )
+ else:
+ self.checkpoint_config = self.config
+ if thread_id := self.checkpoint_config[CONF].get(CONFIG_KEY_THREAD_ID):
+ if not isinstance(thread_id, str):
+ self.checkpoint_config = patch_configurable(
+ self.checkpoint_config,
+ {CONFIG_KEY_THREAD_ID: str(thread_id)},
+ )
+ self.checkpoint_ns = (
+ tuple(cast(str, self.config[CONF][CONFIG_KEY_CHECKPOINT_NS]).split(NS_SEP))
+ if self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS)
+ else ()
+ )
+ self.prev_checkpoint_config = None
+ runtime = self.config[CONF].get(CONFIG_KEY_RUNTIME)
+ self.control = runtime.control if isinstance(runtime, Runtime) else None
+
+ def _push_graph_lifecycle_event(
+ self,
+ kind: Literal["resume", "interrupt"],
+ *,
+ interrupts: tuple[Interrupt, ...] = (),
+ ) -> None:
+ # drain status never reaches lifecycle events: tick() returns False
+ # before pushing, and interrupts are raised through GraphInterrupt
+ if self.status == "draining":
+ raise RuntimeError("Draining status cannot emit lifecycle events")
+ status = self.status
+ if kind == "resume":
+ self._graph_lifecycle_events.append(
+ GraphResumeEvent(
+ run_id=None,
+ status=status,
+ checkpoint_id=self.checkpoint["id"],
+ checkpoint_ns=self.checkpoint_ns,
+ )
+ )
+ elif kind == "interrupt":
+ self._graph_lifecycle_events.append(
+ GraphInterruptEvent(
+ run_id=None,
+ status=status,
+ checkpoint_id=self.checkpoint["id"],
+ checkpoint_ns=self.checkpoint_ns,
+ interrupts=interrupts,
+ )
+ )
+ else:
+ msg = f"Unknown graph lifecycle event type: {kind}"
+ raise AssertionError(msg)
+
+ def _pop_lifecycle_event(self) -> GraphLifecycleEvent | None:
+ if not self._graph_lifecycle_events:
+ return None
+ return self._graph_lifecycle_events.popleft()
+
+ def put_writes(self, task_id: str, writes: WritesT) -> None:
+ """Put writes for a task, to be read by the next tick."""
+ if not writes:
+ return
+ # deduplicate writes to special channels, last write wins
+ if all(w[0] in WRITES_IDX_MAP for w in writes):
+ writes = list({w[0]: w for w in writes}.values())
+ if task_id == NULL_TASK_ID:
+ # writes for the null task are accumulated
+ self.checkpoint_pending_writes = [
+ w
+ for w in self.checkpoint_pending_writes
+ if w[0] != task_id or w[1] not in WRITES_IDX_MAP
+ ]
+ writes_to_save: WritesT = [
+ w[1:] for w in self.checkpoint_pending_writes if w[0] == task_id
+ ] + list(writes)
+ else:
+ # remove existing writes for this task
+ self.checkpoint_pending_writes = [
+ w for w in self.checkpoint_pending_writes if w[0] != task_id
+ ]
+ writes_to_save = writes
+
+ # check if any writes are to an UntrackedValue channel
+ if any(
+ isinstance(channel, UntrackedValue) for channel in self.channels.values()
+ ):
+ # we do not persist untracked values in checkpoints
+ writes_to_save = [
+ # sanitize UntrackedValues that are nested within Send packets
+ (
+ (c, sanitize_untracked_values_in_send(v, self.channels))
+ if c == TASKS and isinstance(v, Send)
+ else (c, v)
+ )
+ for c, v in writes_to_save
+ # dont persist UntrackedValue channel writes
+ if not isinstance(self.specs.get(c), UntrackedValue)
+ ]
+
+ # save writes
+ self.checkpoint_pending_writes.extend((task_id, c, v) for c, v in writes)
+ # Assign stable IDs to any id=None BaseMessages in DeltaChannel writes
+ # before the background thread serialises them. Without this, reducers
+ # that assign IDs inside apply_writes() race with serialisation and
+ # store id=None, causing get_state() replays to produce a different UUID
+ # on every call.
+ for c, v in writes_to_save:
+ if isinstance(self.specs.get(c), DeltaChannel):
+ ensure_message_ids(v)
+ if self.durability != "exit" and self.checkpointer_put_writes is not None:
+ config = patch_configurable(
+ self.checkpoint_config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ )
+ if self.checkpointer_put_writes_accepts_task_path:
+ if hasattr(self, "tasks"):
+ task = self.tasks.get(task_id)
+ else:
+ task = None
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes_to_save,
+ task_id,
+ task_path_str(task.path) if task else "",
+ )
+ else:
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes_to_save,
+ task_id,
+ )
+ if self._delta_write_futs is not None and any(
+ isinstance(self.specs.get(c), DeltaChannel) for c, _ in writes_to_save
+ ):
+ self._delta_write_futs.append(fut)
+ # ERROR_SOURCE_NODE is only appended by commit() when the task
+ # has an error handler (_should_route_to_error_handler), so this
+ # check naturally limits future collection to those tasks.
+ if self._error_handler_write_futs is not None and any(
+ c == ERROR_SOURCE_NODE for c, _ in writes
+ ):
+ self._error_handler_write_futs.append(fut)
+ # output writes
+ if hasattr(self, "tasks"):
+ self.output_writes(task_id, writes)
+
+ def _put_pending_writes(self) -> None:
+ if self.checkpointer_put_writes is None:
+ return
+ if not self.checkpoint_pending_writes:
+ return
+ # patch config
+ config = patch_configurable(
+ self.checkpoint_config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ )
+ # group by task id
+ by_task = defaultdict(list)
+ for task_id, channel, value in self.checkpoint_pending_writes:
+ by_task[task_id].append((channel, value))
+ # submit writes to checkpointer
+ for task_id, writes in by_task.items():
+ if self.checkpointer_put_writes_accepts_task_path and hasattr(
+ self, "tasks"
+ ):
+ task = self.tasks.get(task_id)
+ self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes,
+ task_id,
+ task_path_str(task.path) if task else "",
+ )
+ else:
+ self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes,
+ task_id,
+ )
+
+ def accept_push(
+ self, task: PregelExecutableTask, write_idx: int, call: Call | None = None
+ ) -> PregelExecutableTask | None:
+ """Accept a PUSH from a task, potentially returning a new task to start."""
+ checkpoint_id_bytes = binascii.unhexlify(self.checkpoint["id"].replace("-", ""))
+ null_version = checkpoint_null_version(self.checkpoint)
+ if pushed := cast(
+ PregelExecutableTask | None,
+ prepare_single_task(
+ (PUSH, task.path, write_idx, task.id, call),
+ None,
+ checkpoint=self.checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ checkpoint_null_version=null_version,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=task.config,
+ step=self.step,
+ stop=self.stop,
+ for_execution=True,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ ),
+ ):
+ # produce debug output
+ self._emit("tasks", map_debug_tasks, [pushed])
+ # save the new task
+ self.tasks[pushed.id] = pushed
+ # match any pending writes to the new task
+ if not self.is_replaying:
+ self._reapply_writes_to_succeeded_nodes({pushed.id: pushed})
+ # return the new task, to be started if not run before
+ return pushed
+
+ def schedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ raise NotImplementedError
+
+ async def aschedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ raise NotImplementedError
+
+ def tick(self) -> bool:
+ """Execute a single iteration of the Pregel loop.
+
+ Returns:
+ True if more iterations are needed.
+ """
+
+ # check if iteration limit is reached
+ if self.step > self.stop:
+ self.status = "out_of_steps"
+ return False
+
+ # prepare next tasks
+ self.tasks = prepare_next_tasks(
+ self.checkpoint,
+ self.checkpoint_pending_writes,
+ self.nodes,
+ self.channels,
+ self.managed,
+ self.config,
+ self.step,
+ self.stop,
+ for_execution=True,
+ manager=self.manager,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ trigger_to_nodes=self.trigger_to_nodes,
+ updated_channels=self.updated_channels,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+
+ # produce debug output
+ if self._checkpointer_put_after_previous is not None:
+ self._emit(
+ "checkpoints",
+ map_debug_checkpoint,
+ {
+ **self.checkpoint_config,
+ CONF: {
+ **self.checkpoint_config[CONF],
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ },
+ self.channels,
+ self.stream_keys,
+ self.checkpoint_metadata,
+ self.tasks.values(),
+ self.checkpoint_pending_writes,
+ self.prev_checkpoint_config,
+ self.output_keys,
+ )
+
+ # if no more tasks, we're done
+ if not self.tasks:
+ self.status = "done"
+ return False
+
+ if self.control is not None and self.control.drain_requested:
+ self.status = "draining"
+ return False
+
+ # if there are pending writes from a previous loop, apply them
+ if not self.is_replaying and self.checkpoint_pending_writes:
+ self._reapply_writes_to_succeeded_nodes(self.tasks)
+ self._resume_error_handlers_if_applicable()
+
+ # before execution, check if we should interrupt
+ if self.interrupt_before and should_interrupt(
+ self.checkpoint, self.interrupt_before, self.tasks.values()
+ ):
+ self.status = "interrupt_before"
+ raise GraphInterrupt()
+
+ # produce debug output
+ self._emit("tasks", map_debug_tasks, self.tasks.values())
+
+ # print output for any tasks we applied previous writes to
+ for task in self.tasks.values():
+ if task.writes:
+ self.output_writes(task.id, task.writes, cached=True)
+
+ return True
+
+ def after_tick(self) -> None:
+ # finish superstep
+ writes = [w for t in self.tasks.values() for w in t.writes]
+ # all tasks have finished
+ self.updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ self.tasks.values(),
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ # produce values output
+ if not self.updated_channels.isdisjoint(
+ (self.output_keys,)
+ if isinstance(self.output_keys, str)
+ else self.output_keys
+ ):
+ self._emit(
+ "values", map_output_values, self.output_keys, writes, self.channels
+ )
+ # capture delta-channel writes for exit-mode accumulator before clearing
+ if self._exit_delta_writes is not None:
+ for tid, ch, v in self.checkpoint_pending_writes:
+ if isinstance(self.specs.get(ch), DeltaChannel):
+ self._exit_delta_writes.append((self.step, tid, ch, v))
+ # clear pending writes
+ self.checkpoint_pending_writes.clear()
+ # only replay (re-execute) done tasks on the first tick
+ self.is_replaying = False
+ # save checkpoint
+ self._put_checkpoint({"source": "loop"})
+ # after execution, check if we should interrupt
+ if self.interrupt_after and should_interrupt(
+ self.checkpoint, self.interrupt_after, self.tasks.values()
+ ):
+ self.status = "interrupt_after"
+ raise GraphInterrupt()
+ # unset resuming flag
+ self.config[CONF].pop(CONFIG_KEY_RESUMING, None)
+
+ def match_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ raise NotImplementedError
+
+ async def amatch_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ raise NotImplementedError
+
+ # private
+
+ def _reapply_writes_to_succeeded_nodes(
+ self, tasks: Mapping[str, PregelExecutableTask]
+ ) -> None:
+ """Restore successful channel writes from checkpoint to in-memory tasks.
+
+ Skips control signals (ERROR, ERROR_SOURCE_NODE, INTERRUPT, RESUME)
+ so that failed/interrupted tasks remain with empty writes and will be
+ re-executed (or routed to error handlers) by the runner.
+ """
+ for tid, k, v in self.checkpoint_pending_writes:
+ if k in (ERROR, ERROR_SOURCE_NODE, INTERRUPT, RESUME):
+ continue
+ if task := tasks.get(tid):
+ task.writes.append((k, v))
+
+ def _resume_error_handlers_if_applicable(self) -> None:
+ """On resume, schedule error handlers for tasks that failed in a prior run.
+
+ Called right after ``_reapply_writes_to_succeeded_nodes`` during ``tick()``.
+ At that point, ``_reapply_writes_to_succeeded_nodes`` has already skipped
+ ERROR / ERROR_SOURCE_NODE writes, so a previously-failed task still has
+ empty ``writes``. Without intervention the runner (which executes only
+ tasks where ``not t.writes``) would re-run the original node.
+
+ This method prevents that re-execution for nodes that have an error
+ handler:
+
+ 1. Scan ``checkpoint_pending_writes`` for ERROR_SOURCE_NODE markers
+ persisted by a prior ``commit()``. Each marker means "this task
+ already failed and was routed to an error handler".
+ 2. For each such task, write ``(ERROR, error)`` into ``task.writes``
+ so the task is no longer empty — the runner will skip it.
+ 3. Prepare a fresh error-handler task and add it to ``self.tasks``.
+ Because the handler task starts with empty ``writes``, the runner
+ will pick it up and execute it.
+ """
+ # Phase 1: collect task-ids that have ERROR_SOURCE_NODE + ERROR pairs.
+ failed: dict[str, BaseException] = {}
+ for tid, chan, val in self.checkpoint_pending_writes:
+ if chan == ERROR_SOURCE_NODE:
+ error = next(
+ (
+ v
+ for t, c, v in self.checkpoint_pending_writes
+ if t == tid and c == ERROR
+ ),
+ None,
+ )
+ if error is not None:
+ failed[tid] = error
+ # Phase 2: mark originals as done, schedule handler tasks.
+ for task_id, error in failed.items():
+ task = self.tasks.get(task_id)
+ if task is None:
+ continue
+ handler_node = self.nodes[task.name].error_handler_node
+ if not handler_node:
+ continue
+ # Non-empty writes → runner's `not t.writes` filter skips this task.
+ task.writes.append((ERROR, error))
+ # The handler task starts with empty writes → runner will execute it.
+ handler_task = prepare_node_error_handler_task(
+ task,
+ handler_node_name=handler_node,
+ failed_error=error,
+ checkpoint=self.checkpoint,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=task.config,
+ step=self.step,
+ stop=self.stop,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+ if handler_task is not None:
+ self.tasks[handler_task.id] = handler_task
+
+ def _pending_interrupts(self) -> set[str]:
+ """Return the set of interrupt ids that are pending without corresponding resume values."""
+ # mapping of task ids to interrupt ids
+ pending_interrupts: dict[str, str] = {}
+
+ # set of resume task ids
+ pending_resumes: set[str] = set()
+
+ for task_id, write_type, value in self.checkpoint_pending_writes:
+ if write_type == INTERRUPT:
+ # interrupts is always a list, but there should only be one element
+ pending_interrupts[task_id] = value[0].id
+ elif write_type == RESUME:
+ pending_resumes.add(task_id)
+
+ resumed_interrupt_ids = {
+ pending_interrupts[task_id]
+ for task_id in pending_resumes
+ if task_id in pending_interrupts
+ }
+
+ # Keep only interrupts whose interrupt_id is not resumed
+ hanging_interrupts: set[str] = {
+ interrupt_id
+ for interrupt_id in pending_interrupts.values()
+ if interrupt_id not in resumed_interrupt_ids
+ }
+
+ return hanging_interrupts
+
+ def _first(
+ self, *, input_keys: str | Sequence[str], updated_channels: set[str] | None
+ ) -> set[str] | None:
+ # Resuming from a previous checkpoint requires two things:
+ # 1. A prior checkpoint exists (channel_versions is non-empty)
+ # 2. The input signals continuation (not a fresh run with new input)
+ # For subgraphs, the parent explicitly sets CONFIG_KEY_RESUMING.
+ # For the outer graph, we infer from the input:
+ # - None input: resume after interrupt (invoke(None, config))
+ # - Command input: any Command operates on existing state
+ # - Same run_id: re-entry into an ongoing run (e.g. stream reconnect)
+ configurable = self.config.get(CONF, {})
+ input_is_command = isinstance(self.input, Command)
+ is_resuming = bool(self.checkpoint["channel_versions"]) and bool(
+ configurable.get(
+ CONFIG_KEY_RESUMING,
+ self.input is None
+ or input_is_command
+ or (
+ not self.is_nested
+ and self.config.get("metadata", {}).get("run_id")
+ == self.checkpoint_metadata.get("run_id", MISSING)
+ ),
+ )
+ )
+
+ # When replaying from a specific checkpoint, drop cached RESUME
+ # writes so that interrupt() calls re-fire instead of returning
+ # stale values. But if we're actively resuming, keep them —
+ # multi-interrupt scenarios need previously resolved values preserved.
+ is_time_traveling = self.is_replaying and (
+ # Time-travel to a subgraph checkpoint: the parent sets
+ # RESUMING=True (it can't distinguish time-travel from resume),
+ # so we check if this subgraph's own ns is in checkpoint_map.
+ # Normally the map only has ancestor entries (_algo.py); the
+ # subgraph's own entry only appears via get_state(subgraphs=True).
+ (
+ self.is_nested
+ and configurable.get(CONFIG_KEY_CHECKPOINT_NS, "")
+ in configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {})
+ )
+ or not (
+ # Outer graph: resume arrives as Command(resume=...)
+ (input_is_command and cast(Command, self.input).resume is not None)
+ # Subgraphs: resume arrives via config flag from parent
+ # (subgraph input is a Send arg, not a Command)
+ or configurable.get(CONFIG_KEY_RESUMING, False)
+ )
+ )
+ if is_time_traveling:
+ self.checkpoint_pending_writes = [
+ w for w in self.checkpoint_pending_writes if w[1] != RESUME
+ ]
+
+ # map command to writes
+ if input_is_command:
+ if (resume := cast(Command, self.input).resume) is not None:
+ if not self.checkpointer:
+ raise RuntimeError(
+ "Cannot use Command(resume=...) without checkpointer"
+ )
+
+ if resume_is_map := (
+ isinstance(resume, dict)
+ and all(is_xxh3_128_hexdigest(k) for k in resume)
+ ):
+ self.config[CONF][CONFIG_KEY_RESUME_MAP] = resume
+ else:
+ if len(self._pending_interrupts()) > 1:
+ raise RuntimeError(
+ "When there are multiple pending interrupts, you must specify the interrupt id when resuming. "
+ "Docs: https://docs.langchain.com/oss/python/langgraph/add-human-in-the-loop#resume-multiple-interrupts-with-one-invocation."
+ )
+
+ writes: defaultdict[str, list[tuple[str, Any]]] = defaultdict(list)
+ # group writes by task ID
+ for tid, c, v in map_command(cmd=cast(Command, self.input)):
+ if not (c == RESUME and resume_is_map):
+ writes[tid].append((c, v))
+ if not writes and not resume_is_map:
+ raise EmptyInputError("Received empty Command input")
+ # save writes
+ for tid, ws in writes.items():
+ self.put_writes(tid, ws)
+ # apply NULL writes
+ if null_writes := [
+ w[1:] for w in self.checkpoint_pending_writes if w[0] == NULL_TASK_ID
+ ]:
+ null_updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ if updated_channels is not None:
+ updated_channels.update(null_updated_channels)
+ # proceed past previous checkpoint
+ if is_resuming:
+ self.checkpoint["versions_seen"].setdefault(INTERRUPT, {})
+ for k in self.channels:
+ if k in self.checkpoint["channel_versions"]:
+ version = self.checkpoint["channel_versions"][k]
+ self.checkpoint["versions_seen"][INTERRUPT][k] = version
+ # When time-traveling (replaying from a specific checkpoint),
+ # save a fork checkpoint so the replayed execution creates a
+ # new branch. Without this, if the execution hits an interrupt
+ # before after_tick() runs, no new checkpoint is created —
+ # the parent's latest checkpoint remains the old one and
+ # subsequent resumes load the wrong state.
+ # Skip for update_state forks (source=update/fork) since they
+ # already have their own fork checkpoint.
+ if is_time_traveling and self.checkpoint_metadata.get("source") not in (
+ "update",
+ "fork",
+ ):
+ # Clear old INTERRUPT writes from the loaded checkpoint.
+ # The fork will have a new checkpoint_id which changes
+ # task IDs — stale interrupt writes would accumulate and
+ # confuse the multiple-interrupt check in future resumes.
+ self.checkpoint_pending_writes = [
+ w for w in self.checkpoint_pending_writes if w[1] != INTERRUPT
+ ]
+ self._put_checkpoint({"source": "fork"})
+ # produce values output
+ self._emit(
+ "values", map_output_values, self.output_keys, True, self.channels
+ )
+ # map inputs to channel updates
+ elif input_writes := deque(map_input(input_keys, self.input)):
+ # discard any unfinished tasks from previous checkpoint
+ discard_tasks = prepare_next_tasks(
+ self.checkpoint,
+ self.checkpoint_pending_writes,
+ self.nodes,
+ self.channels,
+ self.managed,
+ self.config,
+ self.step,
+ self.stop,
+ for_execution=True,
+ store=None,
+ checkpointer=None,
+ manager=None,
+ updated_channels=updated_channels,
+ )
+ # apply input writes
+ updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ [
+ *discard_tasks.values(),
+ PregelTaskWrites((), INPUT, input_writes, []),
+ ],
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ # Input writes go through `apply_writes` directly (above) — they
+ # never enter `checkpoint_pending_writes`, so the after_tick
+ # capture site does not see them. In exit mode, capture them
+ # here so `_exit_delta_writes` includes the input's delta writes
+ # alongside per-superstep writes; otherwise the input would be
+ # lost on read (it's not in final_checkpoint.channel_values for
+ # sub-freq channels, and walks ignore target.pending_writes).
+ if self._exit_delta_writes is not None:
+ for c, v in input_writes:
+ if isinstance(self.specs.get(c), DeltaChannel):
+ self._exit_delta_writes.append((self.step, NULL_TASK_ID, c, v))
+ # Persist delta-channel input writes so sub-freq inputs are
+ # recoverable via ancestor walk (mirrors the Command input path).
+ if self.durability != "exit":
+ delta_input = [
+ (c, v)
+ for c, v in input_writes
+ if isinstance(self.specs.get(c), DeltaChannel)
+ ]
+ if delta_input:
+ self.put_writes(NULL_TASK_ID, delta_input)
+ # save input checkpoint
+ self.updated_channels = updated_channels
+ self._put_checkpoint({"source": "input"})
+ elif CONFIG_KEY_RESUMING not in configurable:
+ raise EmptyInputError(f"Received no input for {input_keys}")
+ # Propagate resuming and replaying flags to subgraphs.
+ if not self.is_nested:
+ # Pass the resolved before-bound checkpoint ID so subgraphs can
+ # find their corresponding checkpoint without re-fetching the
+ # parent. For forks (source=update/fork), use the fork's parent
+ # checkpoint ID since the fork was created after the subgraph's
+ # checkpoints from the original execution.
+ #
+ # Only gate on is_time_traveling (not is_replaying). When the
+ # client resumes with an explicit checkpoint_id that happens to
+ # point at the current head (e.g. LangGraph Studio sending
+ # `checkpoint: {checkpoint_id}` alongside Command(resume=...)),
+ # is_replaying is True but is_time_traveling is False. In that
+ # case subgraphs should load their latest checkpoint normally,
+ # not go through ReplayState's before-bound lookup which would
+ # miss subgraph checkpoints created during processing of the
+ # current parent step.
+ replay_state: ReplayState | None = None
+ if is_time_traveling:
+ replay_checkpoint_id = self.checkpoint["id"]
+ if (
+ self.checkpoint_metadata.get("source")
+ in (
+ "update",
+ "fork",
+ )
+ and self.prev_checkpoint_config
+ ):
+ replay_checkpoint_id = self.prev_checkpoint_config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_ID, replay_checkpoint_id
+ )
+ replay_state = ReplayState(replay_checkpoint_id)
+ self.config = patch_configurable(
+ self.config,
+ {
+ CONFIG_KEY_RESUMING: is_resuming,
+ CONFIG_KEY_REPLAY_STATE: replay_state,
+ },
+ )
+ # set flag
+ self.status = "pending"
+ if is_resuming:
+ self._push_graph_lifecycle_event("resume")
+ return updated_channels
+
+ def _put_checkpoint(self, metadata: CheckpointMetadata) -> None:
+ # `is` (object identity) — not `==`. Three of four call sites pass a
+ # fresh dict ({"source":"input"|"loop"|"fork"}); only
+ # `_suppress_interrupt`(will rename to _on_loop_exit soon)
+ # at exit reuses the existing `self.checkpoint_metadata` instance. So
+ # `metadata is self.checkpoint_metadata` is True only on the exit call,
+ # which is what we use to gate exit-only behaviour (skip count-bump,
+ # don't replace metadata). Could be replaced by an explicit
+ # `exiting: bool = False` parameter; left as-is to match the existing
+ # idiom in this file.
+ # TODO: replace with an explicit `exiting: bool = False` parameter.
+ exiting = metadata is self.checkpoint_metadata
+ if exiting and self.checkpoint["id"] == self.checkpoint_id_saved:
+ # checkpoint already saved
+ return
+ # Per-delta-channel counter bookkeeping.
+ #
+ # Each delta channel tracks a (updates, supersteps) tuple:
+ # - `updates` increments only when the channel is written this step.
+ # - `supersteps` increments every superstep regardless.
+ #
+ # `_put_checkpoint` is called once per superstep with a fresh
+ # metadata dict (source="input"|"loop"|"fork") — those are the
+ # intermediate calls that bump counters. In exit mode,
+ # `_suppress_interrupt`(will rename to _on_loop_exit soon)
+ # additionally calls `_put_checkpoint(self.checkpoint_metadata)` AT
+ # EXIT to commit the final checkpoint — this runs *after* the last
+ # intermediate call already counted the last superstep. So the
+ # exit call must NOT bump again or it would double-count the last
+ # superstep.
+ if not exiting:
+ prev_counters = dict(
+ self.checkpoint_metadata.get("counters_since_delta_snapshot") or {}
+ )
+ new_counters: dict[str, tuple[int, int]] = {}
+ updated = self.updated_channels or set()
+ for ch_name, ch in self.channels.items():
+ if not isinstance(ch, DeltaChannel):
+ continue
+ u, s = prev_counters.get(ch_name, (0, 0))
+ s += 1
+ if ch_name in updated:
+ u += 1
+ new_counters[ch_name] = (u, s)
+ metadata["step"] = self.step
+ metadata["parents"] = self.config[CONF].get(CONFIG_KEY_CHECKPOINT_MAP, {})
+ self.checkpoint_metadata = metadata
+ else:
+ new_counters = dict(
+ self.checkpoint_metadata.get("counters_since_delta_snapshot") or {}
+ )
+ # do checkpoint?
+ do_checkpoint = self._checkpointer_put_after_previous is not None and (
+ exiting or self.durability != "exit"
+ )
+ # create new checkpoint
+ channels_to_snapshot = (
+ delta_channels_to_snapshot(self.channels, new_counters)
+ if do_checkpoint
+ else set()
+ )
+ self.checkpoint = create_checkpoint(
+ self.checkpoint,
+ self.channels if do_checkpoint else None,
+ self.step,
+ id=self.checkpoint["id"] if exiting else None,
+ updated_channels=self.updated_channels,
+ get_next_version=self.checkpointer_get_next_version
+ if do_checkpoint
+ else None,
+ channels_to_snapshot=channels_to_snapshot,
+ )
+ for k in channels_to_snapshot:
+ new_counters[k] = (0, 0)
+ non_zero = {k: v for k, v in new_counters.items() if v != (0, 0)}
+ if non_zero:
+ self.checkpoint_metadata["counters_since_delta_snapshot"] = non_zero
+ elif "counters_since_delta_snapshot" in self.checkpoint_metadata:
+ del self.checkpoint_metadata["counters_since_delta_snapshot"]
+ # sanitize TASK channel in the checkpoint before saving (durability=="exit")
+ if TASKS in self.checkpoint["channel_values"] and any(
+ isinstance(channel, UntrackedValue) for channel in self.channels.values()
+ ):
+ sanitized_tasks = [
+ sanitize_untracked_values_in_send(value, self.channels)
+ if isinstance(value, Send)
+ else value
+ for value in self.checkpoint["channel_values"][TASKS]
+ ]
+ self.checkpoint["channel_values"][TASKS] = sanitized_tasks
+ # bail if no checkpointer
+
+ if do_checkpoint and self._checkpointer_put_after_previous is not None:
+ self.prev_checkpoint_config = (
+ self.checkpoint_config
+ if CONFIG_KEY_CHECKPOINT_ID in self.checkpoint_config[CONF]
+ and self.checkpoint_config[CONF][CONFIG_KEY_CHECKPOINT_ID]
+ else None
+ )
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ CONF: {
+ **self.checkpoint_config[CONF],
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ },
+ }
+
+ channel_versions = self.checkpoint["channel_versions"].copy()
+ new_versions = get_new_channel_versions(
+ self.checkpoint_previous_versions, channel_versions
+ )
+ self.checkpoint_previous_versions = channel_versions
+
+ # save it, without blocking
+ # if there's a previous checkpoint save in progress, wait for it
+ # ensuring checkpointers receive checkpoints in order
+ self._put_checkpoint_fut = self.submit(
+ self._checkpointer_put_after_previous,
+ getattr(self, "_put_checkpoint_fut", None),
+ self.checkpoint_config,
+ copy_checkpoint(self.checkpoint),
+ self.checkpoint_metadata,
+ new_versions,
+ )
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ CONF: {
+ **self.checkpoint_config[CONF],
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ }
+ if not exiting:
+ # increment step
+ self.step += 1
+
+ def _put_exit_delta_writes(self) -> None:
+ """Stage stub + accumulated delta writes so final_checkpoint's put
+ waits on them (visibility invariant: both must be durable before
+ final_checkpoint becomes visible to readers).
+
+ Stub is created lazily — only when no persisted parent exists AND at
+ least one delta channel has writes that won't be snapshotted.
+ """
+ if (
+ not self._exit_delta_writes
+ or self.checkpointer is None
+ or self._checkpointer_put_after_previous is None
+ or self.checkpointer_put_writes is None
+ ):
+ return
+
+ counters = dict(
+ self.checkpoint_metadata.get("counters_since_delta_snapshot") or {}
+ )
+ channels_to_snapshot = delta_channels_to_snapshot(self.channels, counters)
+
+ pending = [
+ (step, tid, ch, v)
+ for (step, tid, ch, v) in self._exit_delta_writes
+ if ch not in channels_to_snapshot
+ ]
+ if not pending:
+ return
+
+ if self._has_persisted_parent:
+ # _initial_checkpoint_config's checkpoint_id is the saved parent's
+ # id (saver returned a real tuple at __enter__).
+ anchor_config = self._initial_checkpoint_config
+ else:
+ stub_cp = empty_checkpoint()
+ stub_cp["id"] = self.checkpoint_id_saved
+ stub_cp["ts"] = datetime.now(timezone.utc).isoformat()
+ # Stub has no parent (checkpoint_id=None in config).
+ stub_put_config = patch_configurable(
+ self._initial_checkpoint_config,
+ {CONFIG_KEY_CHECKPOINT_ID: None},
+ )
+ # Anchor config for put_writes: checkpoint_id = stub's id.
+ anchor_config = patch_configurable(
+ self._initial_checkpoint_config,
+ {CONFIG_KEY_CHECKPOINT_ID: stub_cp["id"]},
+ )
+ self._put_checkpoint_fut = self.submit(
+ self._checkpointer_put_after_previous,
+ getattr(self, "_put_checkpoint_fut", None),
+ stub_put_config,
+ stub_cp,
+ {"step": -2},
+ {},
+ )
+ # Set checkpoint_config so final_checkpoint's _put_checkpoint
+ # sees the stub as its parent.
+ self.checkpoint_config = anchor_config
+
+ # Step-prefixed synthetic task_id preserves chronological superstep
+ # order under the saver's ORDER BY task_id, idx sorting.
+ grouped: dict[tuple[int, str], list[tuple[str, Any]]] = {}
+ for step, tid, ch, v in pending:
+ grouped.setdefault((step, tid), []).append((ch, v))
+ anchor_write_config = patch_configurable(
+ anchor_config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ CONFIG_KEY_CHECKPOINT_ID: anchor_config[CONF][CONFIG_KEY_CHECKPOINT_ID],
+ },
+ )
+ for (step, tid), entries in grouped.items():
+ synth_tid = f"{step:08d}-{tid}"
+ if self.checkpointer_put_writes_accepts_task_path:
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ anchor_write_config,
+ entries,
+ synth_tid,
+ "",
+ )
+ else:
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ anchor_write_config,
+ entries,
+ synth_tid,
+ )
+ if self._delta_write_futs is not None:
+ self._delta_write_futs.append(fut)
+
+ def _suppress_interrupt(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # persist current checkpoint and writes
+ if self.durability == "exit" and (
+ # if it's a top graph
+ not self.is_nested
+ # or a nested graph with error or interrupt
+ or exc_value is not None
+ # or a nested graph with checkpointer=True
+ or all(NS_END not in part for part in self.checkpoint_ns)
+ ):
+ self._put_exit_delta_writes()
+ self._put_checkpoint(self.checkpoint_metadata)
+ self._put_pending_writes()
+ # suppress interrupt
+ if isinstance(exc_value, GraphInterrupt) and not self.is_nested:
+ interrupt = exc_value
+ interrupts = tuple(interrupt.args[0]) if interrupt.args else ()
+ self._push_graph_lifecycle_event("interrupt", interrupts=interrupts)
+ # emit one last "values" event, with pending writes applied
+ if (
+ hasattr(self, "tasks")
+ and self.checkpoint_pending_writes
+ and any(task.writes for task in self.tasks.values())
+ ):
+ updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ self.tasks.values(),
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ if not updated_channels.isdisjoint(
+ (self.output_keys,)
+ if isinstance(self.output_keys, str)
+ else self.output_keys
+ ):
+ self._emit(
+ "values",
+ map_output_values,
+ self.output_keys,
+ [w for t in self.tasks.values() for w in t.writes],
+ self.channels,
+ )
+ # emit INTERRUPT if exception is empty (otherwise emitted by put_writes)
+ if not interrupt.args or not interrupt.args[0]:
+ interrupt_payload = interrupt.args[0] if interrupt.args else ()
+ self._emit(
+ "updates",
+ lambda: iter([{INTERRUPT: interrupt_payload}]),
+ )
+ # save final output
+ self.output = read_channels(self.channels, self.output_keys)
+ # suppress interrupt
+ return True
+ elif exc_type is None:
+ # save final output
+ self.output = read_channels(self.channels, self.output_keys)
+
+ def _emit(
+ self,
+ mode: StreamMode,
+ values: Callable[P, Iterator[Any]],
+ *args: P.args,
+ **kwargs: P.kwargs,
+ ) -> None:
+ if self.stream is None:
+ return
+ debug_remap = mode in ("checkpoints", "tasks") and "debug" in self.stream.modes
+ if mode not in self.stream.modes and not debug_remap:
+ return
+ for v in values(*args, **kwargs):
+ if mode in self.stream.modes:
+ self.stream((self.checkpoint_ns, mode, v))
+ # "debug" mode is "checkpoints" or "tasks" with a wrapper dict
+ if debug_remap:
+ self.stream(
+ (
+ self.checkpoint_ns,
+ "debug",
+ {
+ "step": self.step - 1
+ if mode == "checkpoints"
+ else self.step,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "type": "checkpoint"
+ if mode == "checkpoints"
+ else "task_result"
+ if "result" in v
+ else "task",
+ "payload": v,
+ },
+ )
+ )
+
+ def output_writes(
+ self, task_id: str, writes: WritesT, *, cached: bool = False
+ ) -> None:
+ if task := self.tasks.get(task_id):
+ if task.config is not None and TAG_HIDDEN in task.config.get(
+ "tags", EMPTY_SEQ
+ ):
+ return
+ if writes[0][0] == INTERRUPT:
+ # in loop.py we append a bool to the PUSH task paths to indicate
+ # whether or not a call was present. If so,
+ # we don't emit the interrupt as it'll be emitted by the parent
+ if task.path[0] == PUSH and task.path[-1] is True:
+ return
+ interrupts = [
+ {
+ INTERRUPT: tuple(
+ v
+ for w in writes
+ if w[0] == INTERRUPT
+ for v in (w[1] if isinstance(w[1], Sequence) else (w[1],))
+ )
+ }
+ ]
+ stream_modes = self.stream.modes if self.stream else []
+ if "updates" in stream_modes:
+ self._emit("updates", lambda: iter(interrupts))
+ if "values" in stream_modes:
+ current_values = read_channels(self.channels, self.output_keys)
+ # self.output_keys is a sequence, stream chunk contains entire state and interrupts
+ if isinstance(current_values, dict):
+ current_values[INTERRUPT] = interrupts[0][INTERRUPT]
+ self._emit("values", lambda: iter([current_values]))
+ # self.output_keys is a string, stream chunk contains only interrupts
+ else:
+ self._emit("values", lambda: iter(interrupts))
+ elif writes[0][0] != ERROR:
+ self._emit(
+ "updates",
+ map_output_updates,
+ self.output_keys,
+ [(task, writes)],
+ cached,
+ )
+ if not cached:
+ self._emit(
+ "tasks",
+ map_debug_task_results,
+ (task, writes),
+ self.stream_keys,
+ )
+
+
+class SyncPregelLoop(PregelLoop, AbstractContextManager):
+ def __init__(
+ self,
+ input: Any | None,
+ *,
+ stream: StreamProtocol | None,
+ config: RunnableConfig,
+ store: BaseStore | None,
+ cache: BaseCache | None,
+ checkpointer: BaseCheckpointSaver | None,
+ nodes: Mapping[str, PregelNode],
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+ durability: Durability,
+ manager: None | AsyncParentRunManager | ParentRunManager = None,
+ interrupt_after: All | Sequence[str] = EMPTY_SEQ,
+ interrupt_before: All | Sequence[str] = EMPTY_SEQ,
+ input_keys: str | Sequence[str] = EMPTY_SEQ,
+ output_keys: str | Sequence[str] = EMPTY_SEQ,
+ stream_keys: str | Sequence[str] = EMPTY_SEQ,
+ migrate_checkpoint: Callable[[Checkpoint], None] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ has_graph_lifecycle_callbacks: bool = False,
+ ) -> None:
+ super().__init__(
+ input,
+ stream=stream,
+ config=config,
+ checkpointer=checkpointer,
+ cache=cache,
+ store=store,
+ nodes=nodes,
+ specs=specs,
+ input_keys=input_keys,
+ output_keys=output_keys,
+ stream_keys=stream_keys,
+ interrupt_after=interrupt_after,
+ interrupt_before=interrupt_before,
+ manager=manager,
+ migrate_checkpoint=migrate_checkpoint,
+ trigger_to_nodes=trigger_to_nodes,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ durability=durability,
+ has_graph_lifecycle_callbacks=has_graph_lifecycle_callbacks,
+ )
+ self.stack = ExitStack()
+ if checkpointer:
+ self.checkpointer_get_next_version = checkpointer.get_next_version
+ self.checkpointer_put_writes = checkpointer.put_writes
+ self.checkpointer_put_writes_accepts_task_path = (
+ signature(checkpointer.put_writes).parameters.get("task_path")
+ is not None
+ )
+ else:
+ self.checkpointer_get_next_version = increment
+ self._checkpointer_put_after_previous = None # type: ignore[assignment]
+ self.checkpointer_put_writes = None
+ self.checkpointer_put_writes_accepts_task_path = False
+
+ def _checkpointer_put_after_previous(
+ self,
+ prev: concurrent.futures.Future | None,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ if self._delta_write_futs:
+ futs, self._delta_write_futs = self._delta_write_futs, []
+ concurrent.futures.wait(futs)
+ try:
+ if prev is not None:
+ prev.result()
+ finally:
+ cast(BaseCheckpointSaver, self.checkpointer).put(
+ config, checkpoint, metadata, new_versions
+ )
+
+ def match_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ if self.cache is None:
+ return ()
+ matched: list[PregelExecutableTask] = []
+ if cached := {
+ (t.cache_key.ns, t.cache_key.key): t
+ for t in self.tasks.values()
+ if t.cache_key and not t.writes
+ }:
+ for key, values in self.cache.get(tuple(cached)).items():
+ task = cached[key]
+ task.writes.extend(values)
+ matched.append(task)
+ return matched
+
+ def accept_push(
+ self, task: PregelExecutableTask, write_idx: int, call: Call | None = None
+ ) -> PregelExecutableTask | None:
+ if pushed := super().accept_push(task, write_idx, call):
+ for task in self.match_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return pushed
+
+ def schedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ handler_node = self.nodes[failed_task.name].error_handler_node
+ if not handler_node:
+ return None
+ # ensure error + ERROR_SOURCE_NODE writes are durable before handler runs
+ if self._error_handler_write_futs:
+ futs, self._error_handler_write_futs = self._error_handler_write_futs, []
+ concurrent.futures.wait(futs)
+ handler_task = prepare_node_error_handler_task(
+ failed_task,
+ handler_node_name=handler_node,
+ failed_error=error,
+ checkpoint=self.checkpoint,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=failed_task.config,
+ step=self.step,
+ stop=self.stop,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+ if handler_task is None:
+ return None
+ self.tasks[handler_task.id] = handler_task
+ if not self.is_replaying:
+ self._reapply_writes_to_succeeded_nodes({handler_task.id: handler_task})
+ for task in self.match_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return handler_task
+
+ def put_writes(self, task_id: str, writes: WritesT) -> None:
+ """Put writes for a task, to be read by the next tick."""
+ super().put_writes(task_id, writes)
+ if not writes or self.cache is None or not hasattr(self, "tasks"):
+ return
+ task = self.tasks.get(task_id)
+ if task is None or task.cache_key is None:
+ return
+ self.submit(
+ self.cache.set,
+ {
+ (task.cache_key.ns, task.cache_key.key): (
+ task.writes,
+ task.cache_key.ttl,
+ )
+ },
+ )
+
+ # context manager
+
+ def __enter__(self) -> Self:
+ self._graph_lifecycle_events = deque()
+ if not self.checkpointer:
+ saved = None
+ elif self.checkpoint_config[CONF].get(CONFIG_KEY_CHECKPOINT_ID):
+ # Explicit checkpoint_id requested — fetch that exact checkpoint.
+ # This covers both normal replay and subgraphs resolved via
+ # checkpoint_map during time-travel.
+ saved = self.checkpointer.get_tuple(self.checkpoint_config)
+ elif replay_state := self.config[CONF].get(CONFIG_KEY_REPLAY_STATE):
+ # Subgraph replay: the parent is replaying and passed us a
+ # replay_state with its checkpoint_id. Look up our checkpoint
+ # from the parent's checkpoint_map instead of fetching latest.
+ saved = replay_state.get_checkpoint(
+ self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, ""),
+ self.checkpointer,
+ self.checkpoint_config,
+ )
+ # Clear RESUMING so _first re-applies input instead of resuming.
+ # This recreates ephemeral routing channels so nodes trigger
+ # naturally via version comparison.
+ self.config[CONF].pop(CONFIG_KEY_RESUMING, None)
+ else:
+ # Normal case: fetch the most recent checkpoint for this
+ # graph/thread. Returns None on first invocation.
+ saved = self.checkpointer.get_tuple(self.checkpoint_config)
+
+ # Capture before the synthetic-empty fallback below overwrites `saved`.
+ # `_put_exit_delta_writes` uses this on first run (no persisted parent)
+ # to lazy-create a stub instead of anchoring delta writes on a parent.
+ self._has_persisted_parent = saved is not None
+ if saved is None:
+ saved = CheckpointTuple(
+ self.checkpoint_config, empty_checkpoint(), {"step": -2}, None, []
+ )
+ elif self._migrate_checkpoint is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ **saved.config,
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: "",
+ **self.checkpoint_config.get(CONF, {}),
+ **saved.config.get(CONF, {}),
+ },
+ }
+ self._initial_checkpoint_config = self.checkpoint_config
+ self.prev_checkpoint_config = saved.parent_config
+ self.checkpoint_id_saved = saved.checkpoint["id"]
+ self.checkpoint = saved.checkpoint
+ self.checkpoint_metadata = saved.metadata
+ self.checkpoint_pending_writes = (
+ [(str(tid), k, v) for tid, k, v in saved.pending_writes]
+ if saved.pending_writes is not None
+ else []
+ )
+ self._delta_write_futs = []
+ self._error_handler_write_futs = []
+ self._exit_delta_writes = (
+ [] if self.durability == "exit" and self.checkpointer is not None else None
+ )
+ self.submit = self.stack.enter_context(BackgroundExecutor(self.config))
+ self.channels, self.managed = channels_from_checkpoint(
+ self.specs,
+ self.checkpoint,
+ saver=self.checkpointer,
+ config=self.checkpoint_config,
+ )
+ self.stack.push(self._suppress_interrupt)
+ self.status = "input"
+ self.step = self.checkpoint_metadata["step"] + 1
+ self.stop = self.step + self.config["recursion_limit"] + 1
+ self.checkpoint_previous_versions = self.checkpoint["channel_versions"].copy()
+ self.updated_channels = self._first(
+ input_keys=self.input_keys,
+ updated_channels=set(self.checkpoint.get("updated_channels")) # type: ignore[arg-type]
+ if self.checkpoint.get("updated_channels")
+ else None,
+ )
+
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # unwind stack
+ return self.stack.__exit__(exc_type, exc_value, traceback)
+
+
+class AsyncPregelLoop(PregelLoop, AbstractAsyncContextManager):
+ def __init__(
+ self,
+ input: Any | None,
+ *,
+ stream: StreamProtocol | None,
+ config: RunnableConfig,
+ store: BaseStore | None,
+ cache: BaseCache | None,
+ checkpointer: BaseCheckpointSaver | None,
+ nodes: Mapping[str, PregelNode],
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+ durability: Durability,
+ interrupt_after: All | Sequence[str] = EMPTY_SEQ,
+ interrupt_before: All | Sequence[str] = EMPTY_SEQ,
+ manager: None | AsyncParentRunManager | ParentRunManager = None,
+ input_keys: str | Sequence[str] = EMPTY_SEQ,
+ output_keys: str | Sequence[str] = EMPTY_SEQ,
+ stream_keys: str | Sequence[str] = EMPTY_SEQ,
+ migrate_checkpoint: Callable[[Checkpoint], None] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ has_graph_lifecycle_callbacks: bool = False,
+ ) -> None:
+ super().__init__(
+ input,
+ stream=stream,
+ config=config,
+ checkpointer=checkpointer,
+ cache=cache,
+ store=store,
+ nodes=nodes,
+ specs=specs,
+ input_keys=input_keys,
+ output_keys=output_keys,
+ stream_keys=stream_keys,
+ interrupt_after=interrupt_after,
+ interrupt_before=interrupt_before,
+ manager=manager,
+ migrate_checkpoint=migrate_checkpoint,
+ trigger_to_nodes=trigger_to_nodes,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ durability=durability,
+ has_graph_lifecycle_callbacks=has_graph_lifecycle_callbacks,
+ )
+ self.stack = AsyncExitStack()
+ if checkpointer:
+ self.checkpointer_get_next_version = checkpointer.get_next_version
+ self.checkpointer_put_writes = checkpointer.aput_writes
+ self.checkpointer_put_writes_accepts_task_path = (
+ signature(checkpointer.aput_writes).parameters.get("task_path")
+ is not None
+ )
+ else:
+ self.checkpointer_get_next_version = increment
+ self._checkpointer_put_after_previous = None # type: ignore[assignment]
+ self.checkpointer_put_writes = None
+ self.checkpointer_put_writes_accepts_task_path = False
+
+ async def _checkpointer_put_after_previous(
+ self,
+ prev: asyncio.Task | None,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ # Drain DeltaChannel write futures before committing the checkpoint so
+ # ancestor walks never see a checkpoint without its backing writes.
+ if self._delta_write_futs:
+ futs, self._delta_write_futs = self._delta_write_futs, []
+ await asyncio.gather(*futs)
+ try:
+ if prev is not None:
+ await prev
+ finally:
+ await cast(BaseCheckpointSaver, self.checkpointer).aput(
+ config, checkpoint, metadata, new_versions
+ )
+
+ async def amatch_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ if self.cache is None:
+ return []
+ matched: list[PregelExecutableTask] = []
+ if cached := {
+ (t.cache_key.ns, t.cache_key.key): t
+ for t in self.tasks.values()
+ if t.cache_key and not t.writes
+ }:
+ for key, values in (await self.cache.aget(tuple(cached))).items():
+ task = cached[key]
+ task.writes.extend(values)
+ matched.append(task)
+ return matched
+
+ async def aaccept_push(
+ self, task: PregelExecutableTask, write_idx: int, call: Call | None = None
+ ) -> PregelExecutableTask | None:
+ if pushed := super().accept_push(task, write_idx, call):
+ for task in await self.amatch_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return pushed
+
+ async def aschedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ handler_node = self.nodes[failed_task.name].error_handler_node
+ if not handler_node:
+ return None
+ # ensure error + ERROR_SOURCE_NODE writes are durable before handler runs
+ if self._error_handler_write_futs:
+ futs, self._error_handler_write_futs = self._error_handler_write_futs, []
+ await asyncio.gather(*futs)
+ handler_task = prepare_node_error_handler_task(
+ failed_task,
+ handler_node_name=handler_node,
+ failed_error=error,
+ checkpoint=self.checkpoint,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=failed_task.config,
+ step=self.step,
+ stop=self.stop,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+ if handler_task is None:
+ return None
+ self.tasks[handler_task.id] = handler_task
+ if not self.is_replaying:
+ self._reapply_writes_to_succeeded_nodes({handler_task.id: handler_task})
+ for task in await self.amatch_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return handler_task
+
+ def put_writes(self, task_id: str, writes: WritesT) -> None:
+ """Put writes for a task, to be read by the next tick."""
+ super().put_writes(task_id, writes)
+ if not writes or self.cache is None or not hasattr(self, "tasks"):
+ return
+ task = self.tasks.get(task_id)
+ if task is None or task.cache_key is None:
+ return
+ if writes[0][0] in (INTERRUPT, ERROR):
+ # only cache successful tasks
+ return
+ self.submit(
+ self.cache.aset,
+ {
+ (task.cache_key.ns, task.cache_key.key): (
+ task.writes,
+ task.cache_key.ttl,
+ )
+ },
+ )
+
+ # context manager
+
+ async def __aenter__(self) -> Self:
+ self._graph_lifecycle_events = deque()
+ if not self.checkpointer:
+ saved = None
+ elif self.checkpoint_config[CONF].get(CONFIG_KEY_CHECKPOINT_ID):
+ # Explicit checkpoint_id requested — fetch that exact checkpoint.
+ # This covers both normal replay and subgraphs resolved via
+ # checkpoint_map during time-travel.
+ saved = await self.checkpointer.aget_tuple(self.checkpoint_config)
+ elif replay_state := self.config[CONF].get(CONFIG_KEY_REPLAY_STATE):
+ # Subgraph replay: the parent is replaying and passed us a
+ # replay_state with its checkpoint_id. Look up our checkpoint
+ # from the parent's checkpoint_map instead of fetching latest.
+ saved = await replay_state.aget_checkpoint(
+ self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, ""),
+ self.checkpointer,
+ self.checkpoint_config,
+ )
+ # Clear RESUMING so _first re-applies input instead of resuming.
+ # This recreates ephemeral routing channels so nodes trigger
+ # naturally via version comparison.
+ self.config[CONF].pop(CONFIG_KEY_RESUMING, None)
+ else:
+ # Normal case: fetch the most recent checkpoint for this
+ # graph/thread. Returns None on first invocation.
+ saved = await self.checkpointer.aget_tuple(self.checkpoint_config)
+
+ # Capture before the synthetic-empty fallback below overwrites `saved`.
+ # `_put_exit_delta_writes` uses this on first run (no persisted parent)
+ # to lazy-create a stub instead of anchoring delta writes on a parent.
+ self._has_persisted_parent = saved is not None
+ if saved is None:
+ saved = CheckpointTuple(
+ self.checkpoint_config, empty_checkpoint(), {"step": -2}, None, []
+ )
+ elif self._migrate_checkpoint is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ **saved.config,
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: "",
+ **self.checkpoint_config.get(CONF, {}),
+ **saved.config.get(CONF, {}),
+ },
+ }
+ self._initial_checkpoint_config = self.checkpoint_config
+ self.prev_checkpoint_config = saved.parent_config
+ self.checkpoint_id_saved = saved.checkpoint["id"]
+ self.checkpoint = saved.checkpoint
+ self.checkpoint_metadata = saved.metadata
+ self.checkpoint_pending_writes = (
+ [(str(tid), k, v) for tid, k, v in saved.pending_writes]
+ if saved.pending_writes is not None
+ else []
+ )
+ self._delta_write_futs = []
+ self._error_handler_write_futs = []
+ self._exit_delta_writes = (
+ [] if self.durability == "exit" and self.checkpointer is not None else None
+ )
+ self.submit = await self.stack.enter_async_context(
+ AsyncBackgroundExecutor(self.config)
+ )
+ self.channels, self.managed = await achannels_from_checkpoint(
+ self.specs,
+ self.checkpoint,
+ saver=self.checkpointer,
+ config=self.checkpoint_config,
+ )
+ self.stack.push(self._suppress_interrupt)
+ self.status = "input"
+ self.step = self.checkpoint_metadata["step"] + 1
+ self.stop = self.step + self.config["recursion_limit"] + 1
+ self.checkpoint_previous_versions = self.checkpoint["channel_versions"].copy()
+ self.updated_channels = self._first(
+ input_keys=self.input_keys,
+ updated_channels=set(self.checkpoint.get("updated_channels")) # type: ignore[arg-type]
+ if self.checkpoint.get("updated_channels")
+ else None,
+ )
+
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # unwind stack
+ exit_task = asyncio.create_task(
+ self.stack.__aexit__(exc_type, exc_value, traceback)
+ )
+ try:
+ return await exit_task
+ except asyncio.CancelledError as e:
+ # Bubble up the exit task upon cancellation to permit the API
+ # consumer to await it before e.g., reusing the DB connection.
+ e.args = (*e.args, exit_task)
+ raise
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_messages.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_messages.py
new file mode 100644
index 0000000000000000000000000000000000000000..80c5df6f033825c5c6e4ac7047a69cb81d235ba2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_messages.py
@@ -0,0 +1,461 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Callable, Iterator, Sequence
+from dataclasses import fields, is_dataclass
+from typing import (
+ Any,
+ TypeVar,
+ cast,
+)
+from uuid import UUID, uuid4
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import BaseMessage, ToolMessage
+from langchain_core.messages.utils import convert_to_messages
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, LLMResult
+from pydantic import BaseModel
+
+from langgraph._internal._constants import NS_SEP
+from langgraph.constants import TAG_HIDDEN, TAG_NOSTREAM
+from langgraph.pregel.protocol import StreamChunk
+from langgraph.types import Command
+
+try:
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
+except ImportError:
+ _StreamingCallbackHandler = object # type: ignore
+
+try:
+ from langchain_core.tracers._streaming import _V2StreamingCallbackHandler
+except ImportError:
+ _V2StreamingCallbackHandler = object # type: ignore
+
+T = TypeVar("T")
+Meta = tuple[tuple[str, ...], dict[str, Any]]
+
+
+def _state_values(obj: Any) -> Sequence[Any]:
+ """Extract top-level field values from a state object (dict, BaseModel, or dataclass)."""
+ if isinstance(obj, dict):
+ return list(obj.values())
+ elif isinstance(obj, BaseModel):
+ return [getattr(obj, k) for k in type(obj).model_fields]
+ elif is_dataclass(obj) and not isinstance(obj, type):
+ return [getattr(obj, f.name) for f in fields(obj)]
+ return ()
+
+
+class StreamMessagesHandler(BaseCallbackHandler, _StreamingCallbackHandler):
+ """A callback handler that implements stream_mode=messages.
+
+ Collects messages from:
+ (1) chat model stream events; and
+ (2) node outputs.
+ """
+
+ run_inline = True
+ """We want this callback to run in the main thread to avoid order/locking issues."""
+
+ def __init__(
+ self,
+ stream: Callable[[StreamChunk], None],
+ subgraphs: bool,
+ *,
+ parent_ns: tuple[str, ...] | None = None,
+ ) -> None:
+ """Configure the handler to stream messages from LLMs and nodes.
+
+ Args:
+ stream: A callable that takes a StreamChunk and emits it.
+ subgraphs: Whether to emit messages from subgraphs.
+ parent_ns: The namespace where the handler was created.
+ We keep track of this namespace to allow calls to subgraphs that
+ were explicitly requested as a stream with `messages` mode
+ configured.
+
+ Example:
+ parent_ns is used to handle scenarios where the subgraph is explicitly
+ streamed with `stream_mode="messages"`.
+
+ ```python
+ def parent_graph_node():
+ # This node is in the parent graph.
+ async for event in some_subgraph(..., stream_mode="messages"):
+ do something with event # <-- these events will be emitted
+ return ...
+
+ parent_graph.invoke(subgraphs=False)
+ ```
+ """
+ self.stream = stream
+ self.subgraphs = subgraphs
+ self.metadata: dict[UUID, Meta] = {}
+ self.seen: set[int | str] = set()
+ self.parent_ns = parent_ns
+
+ def _emit(self, meta: Meta, message: BaseMessage, *, dedupe: bool = False) -> None:
+ if dedupe and message.id in self.seen:
+ return
+ else:
+ if message.id is None:
+ message.id = str(uuid4())
+ self.seen.add(message.id)
+ self.stream((meta[0], "messages", (message, meta[1])))
+
+ def _find_and_emit_messages(self, meta: Meta, response: Any) -> None:
+ if isinstance(response, BaseMessage):
+ self._emit(meta, response, dedupe=True)
+ elif isinstance(response, Sequence):
+ for value in response:
+ if isinstance(value, BaseMessage):
+ self._emit(meta, value, dedupe=True)
+ else:
+ for value in _state_values(response):
+ if isinstance(value, BaseMessage):
+ self._emit(meta, value, dedupe=True)
+ elif isinstance(value, Sequence):
+ for item in value:
+ if isinstance(item, BaseMessage):
+ self._emit(meta, item, dedupe=True)
+
+ def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ return output
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ return output
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if metadata and (not tags or (TAG_NOSTREAM not in tags)):
+ ns = tuple(cast(str, metadata["langgraph_checkpoint_ns"]).split(NS_SEP))[
+ :-1
+ ]
+ if not self.subgraphs and len(ns) > 0 and ns != self.parent_ns:
+ return
+ if tags:
+ if filtered_tags := [t for t in tags if not t.startswith("seq:step")]:
+ metadata["tags"] = filtered_tags
+ self.metadata[run_id] = (ns, metadata)
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if not isinstance(chunk, ChatGenerationChunk):
+ return
+ if meta := self.metadata.get(run_id):
+ self._emit(meta, chunk.message)
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if meta := self.metadata.get(run_id):
+ if response.generations and response.generations[0]:
+ gen = response.generations[0][0]
+ if isinstance(gen, ChatGeneration):
+ self._emit(meta, gen.message, dedupe=True)
+ self.metadata.pop(run_id, None)
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self.metadata.pop(run_id, None)
+
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if (
+ metadata
+ and kwargs.get("name") == metadata.get("langgraph_node")
+ and (not tags or TAG_HIDDEN not in tags)
+ ):
+ ns = tuple(cast(str, metadata["langgraph_checkpoint_ns"]).split(NS_SEP))[
+ :-1
+ ]
+ if not self.subgraphs and len(ns) > 0:
+ return
+ self.metadata[run_id] = (ns, metadata)
+ for value in _state_values(inputs):
+ if isinstance(value, BaseMessage):
+ if value.id is not None:
+ self.seen.add(value.id)
+ elif isinstance(value, Sequence) and not isinstance(value, str):
+ for item in value:
+ if isinstance(item, BaseMessage):
+ if item.id is not None:
+ self.seen.add(item.id)
+
+ def on_chain_end(
+ self,
+ response: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if meta := self.metadata.pop(run_id, None):
+ # Handle Command node updates
+ if isinstance(response, Command):
+ self._find_and_emit_messages(meta, response.update)
+ # Handle list of Command updates
+ elif isinstance(response, Sequence) and any(
+ isinstance(value, Command) for value in response
+ ):
+ for value in response:
+ if isinstance(value, Command):
+ self._find_and_emit_messages(meta, value.update)
+ else:
+ self._find_and_emit_messages(meta, value)
+ # Handle basic updates / streaming
+ else:
+ self._find_and_emit_messages(meta, response)
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self.metadata.pop(run_id, None)
+
+
+class StreamMessagesHandlerV2(StreamMessagesHandler, _V2StreamingCallbackHandler):
+ """v2 variant of `StreamMessagesHandler`.
+
+ Declaring `_V2StreamingCallbackHandler` as a base flips
+ `BaseChatModel.invoke` to route through `_stream_chat_model_events`
+ (firing `on_stream_event`) instead of `_stream` (firing
+ `on_llm_new_token`). Inherits `on_stream_event` from the parent,
+ which forwards protocol events onto the messages stream channel.
+
+ Pregel attaches this class instead of the v1 handler only when
+ `StreamingHandler` opts in via the internal
+ `CONFIG_KEY_STREAM_MESSAGES_V2` config key; direct
+ `graph.stream(stream_mode="messages")` callers keep the v1
+ AIMessageChunk shape.
+ """
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Intentional no-op — v1 chunks are not used on v2-flagged runs.
+
+ The v2 marker already steers `invoke` to the event generator, so
+ `on_llm_new_token` should not fire under normal routing. This
+ override stays a pass-through (no call to `super()`) to make
+ the intent explicit and to guard against any caller (e.g. a
+ node that calls `model.stream()` directly, which still fires
+ the v1 callback) leaking AIMessageChunks onto a v2-flagged
+ messages stream.
+ """
+ # Intentionally empty: v2 handler does not forward v1 chunks.
+
+ def __init__(
+ self,
+ stream: Callable[[StreamChunk], None],
+ subgraphs: bool,
+ *,
+ parent_ns: tuple[str, ...] | None = None,
+ ) -> None:
+ super().__init__(stream, subgraphs, parent_ns=parent_ns)
+ self._streamed_run_ids: set[UUID] = set()
+
+ def _find_and_emit_messages(self, meta: Meta, response: Any) -> None:
+ """Like the v1 handler, but skip ToolMessage from node outputs.
+
+ Tool results belong on the tools channel / state in v3; v2-flagged streams
+ must not replay finalized ToolMessages as chat tokens (see MessagesTransformer).
+ Legacy v1-only `stream_mode="messages"` still emits ToolMessages (see subgraph
+ streaming tests).
+ """
+ if isinstance(response, BaseMessage) and not isinstance(response, ToolMessage):
+ self._emit(meta, response, dedupe=True)
+ elif isinstance(response, Sequence):
+ for value in response:
+ if isinstance(value, BaseMessage) and not isinstance(
+ value, ToolMessage
+ ):
+ self._emit(meta, value, dedupe=True)
+ else:
+ for value in _state_values(response):
+ if isinstance(value, BaseMessage) and not isinstance(
+ value, ToolMessage
+ ):
+ self._emit(meta, value, dedupe=True)
+ elif isinstance(value, Sequence):
+ for item in value:
+ if isinstance(item, BaseMessage) and not isinstance(
+ item, ToolMessage
+ ):
+ self._emit(meta, item, dedupe=True)
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if meta := self.metadata.get(run_id):
+ if response.generations and response.generations[0]:
+ gen = response.generations[0][0]
+ if isinstance(gen, ChatGeneration):
+ if run_id in self._streamed_run_ids:
+ if gen.message.id is None:
+ gen.message.id = str(uuid4())
+ self.seen.add(gen.message.id)
+ else:
+ self._emit(meta, gen.message, dedupe=True)
+ self._streamed_run_ids.discard(run_id)
+ self.metadata.pop(run_id, None)
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._streamed_run_ids.discard(run_id)
+ super().on_llm_error(
+ error,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ **kwargs,
+ )
+
+ def on_stream_event(
+ self,
+ event: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Forward a protocol event from `stream_events(version="v3")` as a messages stream part.
+
+ Fires once per `MessagesData` event (`message-start`, per-block
+ `content-block-*`, `message-finish`). The transformer layer
+ correlates events back to a single `ChatModelStream` via
+ `metadata["run_id"]` — attached here so the v1
+ `stream_mode="messages"` output (which emits
+ `(AIMessageChunk, metadata)` via `on_llm_new_token`) keeps its
+ original metadata shape.
+
+ Lives on the v2 handler rather than the v1 base: content-block
+ events are a v2-only concept, and forwarding them only when the
+ v2 handler is attached keeps the message channel's shape
+ predictable for v1 callers.
+ """
+ if meta := self.metadata.get(run_id):
+ # Record message_id on message-start so on_chain_end's
+ # dedupe skips the finalized AIMessage the node returns
+ # (otherwise the messages projection double-counts: once
+ # from streaming, once from the chain output).
+ if event.get("event") == "message-start":
+ self._streamed_run_ids.add(run_id)
+ msg_id = event.get("message_id")
+ if msg_id:
+ self.seen.add(msg_id)
+ v2_meta = {**meta[1], "run_id": str(run_id)}
+ self.stream((meta[0], "messages", (event, v2_meta)))
+
+
+# Known role values (OpenAI-style) and type values (LangChain serialisation)
+# that identify a dict as a message. Checked before coercing to BaseMessage so
+# we don't accidentally touch unrelated dicts that happen to have a "role" key.
+_MESSAGE_ROLES: frozenset[str] = frozenset(
+ {"user", "human", "assistant", "ai", "tool", "system", "function"}
+)
+_MESSAGE_TYPES: frozenset[str] = frozenset(
+ {"human", "ai", "tool", "system", "function", "remove"}
+)
+
+
+def _is_message_dict(item: dict) -> bool:
+ return item.get("role") in _MESSAGE_ROLES or item.get("type") in _MESSAGE_TYPES
+
+
+def ensure_message_ids(value: Any) -> None:
+ """Coerce message-like write values to typed BaseMessages with stable IDs.
+
+ Called in put_writes() before DeltaChannel writes are submitted to the
+ checkpointer. Without this the checkpoint may store raw dicts or id=None
+ BaseMessages; every get_state() replay then produces a different UUID and
+ the same message appears with a different ID in each LangSmith trace.
+
+ Handles three input shapes:
+ - BaseMessage objects: assign a UUID if id is None.
+ - Dicts with a known "role" (OpenAI-style) or "type" (LangChain format) at
+ the root level: stamp "id" into the dict in-place. The reducer's
+ convert_to_messages call will forward the id to the resulting BaseMessage.
+ - Lists of the above: apply the same logic to each element, replacing dict
+ items with coerced BaseMessages so the shared list reference seen by
+ checkpoint_pending_writes and the background thread both get typed messages.
+
+ Mutating synchronously here (before the background thread is submitted) is
+ safe: the serialised bytes always reflect the post-coercion state.
+ """
+ if isinstance(value, BaseMessage):
+ if value.id is None:
+ value.id = str(uuid4())
+ elif isinstance(value, dict) and _is_message_dict(value):
+ if not value.get("id"):
+ value["id"] = str(uuid4())
+ elif isinstance(value, list):
+ for i, item in enumerate(value):
+ if isinstance(item, BaseMessage):
+ if item.id is None:
+ item.id = str(uuid4())
+ elif isinstance(item, dict) and _is_message_dict(item):
+ msg = convert_to_messages([item])[0]
+ if msg.id is None:
+ msg.id = str(uuid4())
+ value[i] = msg
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_read.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_read.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d49fce8562486da82bad592884a07437697f213
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_read.py
@@ -0,0 +1,298 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
+from datetime import timedelta
+from functools import cached_property
+from typing import (
+ Any,
+)
+
+from langchain_core.runnables import Runnable, RunnableConfig
+
+from langgraph._internal._config import merge_configs
+from langgraph._internal._constants import CONF, CONFIG_KEY_READ
+from langgraph._internal._runnable import RunnableCallable, RunnableSeq
+from langgraph._internal._timeout import coerce_timeout_policy
+from langgraph.pregel._utils import find_subgraph_pregel
+from langgraph.pregel._write import ChannelWrite
+from langgraph.pregel.protocol import PregelProtocol
+from langgraph.types import CachePolicy, RetryPolicy, TimeoutPolicy
+
+READ_TYPE = Callable[[str | Sequence[str], bool], Any | dict[str, Any]]
+INPUT_CACHE_KEY_TYPE = tuple[Callable[..., Any], tuple[str, ...]]
+
+
+class ChannelRead(RunnableCallable):
+ """Implements the logic for reading state from CONFIG_KEY_READ.
+ Usable both as a runnable as well as a static method to call imperatively."""
+
+ channel: str | list[str]
+
+ fresh: bool = False
+
+ mapper: Callable[[Any], Any] | None = None
+
+ def __init__(
+ self,
+ channel: str | list[str],
+ *,
+ fresh: bool = False,
+ mapper: Callable[[Any], Any] | None = None,
+ tags: list[str] | None = None,
+ ) -> None:
+ super().__init__(
+ func=self._read,
+ afunc=self._aread,
+ tags=tags,
+ name=None,
+ trace=False,
+ )
+ self.fresh = fresh
+ self.mapper = mapper
+ self.channel = channel
+
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ if name:
+ pass
+ elif isinstance(self.channel, str):
+ name = f"ChannelRead<{self.channel}>"
+ else:
+ name = f"ChannelRead<{','.join(self.channel)}>"
+ return super().get_name(suffix, name=name)
+
+ def _read(self, _: Any, config: RunnableConfig) -> Any:
+ return self.do_read(
+ config, select=self.channel, fresh=self.fresh, mapper=self.mapper
+ )
+
+ async def _aread(self, _: Any, config: RunnableConfig) -> Any:
+ return self.do_read(
+ config, select=self.channel, fresh=self.fresh, mapper=self.mapper
+ )
+
+ @staticmethod
+ def do_read(
+ config: RunnableConfig,
+ *,
+ select: str | list[str],
+ fresh: bool = False,
+ mapper: Callable[[Any], Any] | None = None,
+ ) -> Any:
+ try:
+ read: READ_TYPE = config[CONF][CONFIG_KEY_READ]
+ except KeyError:
+ raise RuntimeError(
+ "Not configured with a read function"
+ "Make sure to call in the context of a Pregel process"
+ )
+ if mapper:
+ return mapper(read(select, fresh))
+ else:
+ return read(select, fresh)
+
+
+DEFAULT_BOUND = RunnableCallable(lambda input: input)
+
+
+class PregelNode:
+ """A node in a Pregel graph. This won't be invoked as a runnable by the graph
+ itself, but instead acts as a container for the components necessary to make
+ a PregelExecutableTask for a node."""
+
+ channels: str | list[str]
+ """The channels that will be passed as input to `bound`.
+ If a str, the node will be invoked with its value if it isn't empty.
+ If a list, the node will be invoked with a dict of those channels' values."""
+
+ triggers: list[str]
+ """If any of these channels is written to, this node will be triggered in
+ the next step."""
+
+ mapper: Callable[[Any], Any] | None
+ """A function to transform the input before passing it to `bound`."""
+
+ writers: list[Runnable]
+ """A list of writers that will be executed after `bound`, responsible for
+ taking the output of `bound` and writing it to the appropriate channels."""
+
+ bound: Runnable[Any, Any]
+ """The main logic of the node. This will be invoked with the input from
+ `channels`."""
+
+ retry_policy: Sequence[RetryPolicy] | None
+ """The retry policies to use when invoking the node."""
+
+ cache_policy: CachePolicy | None
+ """The cache policy to use when invoking the node."""
+
+ timeout: TimeoutPolicy | None
+ """Timeout policy for a single invocation.
+
+ If exceeded, `NodeTimeoutError` is raised and the retry policy (if any)
+ decides whether to retry. Supported only for async nodes.
+ """
+
+ tags: Sequence[str] | None
+ """Tags to attach to the node for tracing."""
+
+ metadata: Mapping[str, Any] | None
+ """Metadata to attach to the node for tracing."""
+
+ is_error_handler: bool
+ """Whether this node is registered as an error handler node."""
+
+ error_handler_node: str | None
+ """Optional handler node name for failures from this node."""
+
+ subgraphs: Sequence[PregelProtocol]
+ """Subgraphs used by the node."""
+
+ def __init__(
+ self,
+ *,
+ channels: str | list[str],
+ triggers: Sequence[str],
+ mapper: Callable[[Any], Any] | None = None,
+ writers: list[Runnable] | None = None,
+ tags: list[str] | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ bound: Runnable[Any, Any] | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ is_error_handler: bool = False,
+ error_handler_node: str | None = None,
+ subgraphs: Sequence[PregelProtocol] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ ) -> None:
+ self.channels = channels
+ self.triggers = list(triggers)
+ self.mapper = mapper
+ self.writers = writers or []
+ self.bound = bound if bound is not None else DEFAULT_BOUND
+ self.cache_policy = cache_policy
+ if isinstance(retry_policy, RetryPolicy):
+ self.retry_policy = (retry_policy,)
+ else:
+ self.retry_policy = retry_policy
+ self.timeout = coerce_timeout_policy(timeout)
+ self.tags = tags
+ self.metadata = metadata
+ self.is_error_handler = is_error_handler
+ self.error_handler_node = error_handler_node
+ if subgraphs is not None:
+ self.subgraphs = subgraphs
+ elif self.bound is not DEFAULT_BOUND:
+ try:
+ subgraph = find_subgraph_pregel(self.bound)
+ except Exception:
+ subgraph = None
+ if subgraph:
+ self.subgraphs = [subgraph]
+ else:
+ self.subgraphs = []
+ else:
+ self.subgraphs = []
+
+ def copy(self, update: dict[str, Any]) -> PregelNode:
+ attrs = {**self.__dict__, **update}
+ # Drop the cached properties
+ attrs.pop("flat_writers", None)
+ attrs.pop("node", None)
+ attrs.pop("input_cache_key", None)
+ return PregelNode(**attrs)
+
+ @cached_property
+ def flat_writers(self) -> list[Runnable]:
+ """Get writers with optimizations applied. Dedupes consecutive ChannelWrites."""
+ writers = self.writers.copy()
+ while (
+ len(writers) > 1
+ and isinstance(writers[-1], ChannelWrite)
+ and isinstance(writers[-2], ChannelWrite)
+ ):
+ # we can combine writes if they are consecutive
+ # careful to not modify the original writers list or ChannelWrite
+ writers[-2] = ChannelWrite(
+ writes=writers[-2].writes + writers[-1].writes,
+ )
+ writers.pop()
+ return writers
+
+ @cached_property
+ def node(self) -> Runnable[Any, Any] | None:
+ """Get a runnable that combines `bound` and `writers`."""
+ writers = self.flat_writers
+ if self.bound is DEFAULT_BOUND and not writers:
+ return None
+ elif self.bound is DEFAULT_BOUND and len(writers) == 1:
+ return writers[0]
+ elif self.bound is DEFAULT_BOUND:
+ return RunnableSeq(*writers)
+ elif writers:
+ return RunnableSeq(self.bound, *writers)
+ else:
+ return self.bound
+
+ @cached_property
+ def input_cache_key(self) -> INPUT_CACHE_KEY_TYPE:
+ """Get a cache key for the input to the node.
+ This is used to avoid calculating the same input multiple times."""
+ return (
+ self.mapper,
+ tuple(self.channels)
+ if isinstance(self.channels, list)
+ else (self.channels,),
+ )
+
+ def invoke(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Any:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ return self.bound.invoke(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ )
+
+ async def ainvoke(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Any:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ return await self.bound.ainvoke(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ )
+
+ def stream(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Any]:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ yield from self.bound.stream(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ )
+
+ async def astream(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Any]:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ async for item in self.bound.astream(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ ):
+ yield item
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_retry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_retry.py
new file mode 100644
index 0000000000000000000000000000000000000000..acade9643684bd205ebf672fa83816647473d926
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_retry.py
@@ -0,0 +1,798 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+import random
+import sys
+import threading
+import time
+import weakref
+from collections.abc import Awaitable, Callable, Sequence
+from contextlib import suppress
+from dataclasses import dataclass, replace
+from datetime import datetime, timedelta, timezone
+from typing import Any, Literal, NamedTuple
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.runnables import RunnableConfig
+
+from langgraph._internal._config import (
+ merge_configs,
+ patch_configurable,
+ recast_checkpoint_ns,
+)
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CALL,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_RESUMING,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SEND,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ CONFIG_KEY_TIMED_ATTEMPT_OBSERVER,
+ NS_SEP,
+)
+from langgraph._internal._runnable import create_task_in_config_context
+from langgraph._internal._timeout import sync_timeout_unsupported
+from langgraph.errors import GraphBubbleUp, NodeTimeoutError, ParentCommand
+from langgraph.pregel.protocol import StreamProtocol
+from langgraph.runtime import ExecutionInfo, Runtime
+from langgraph.types import Command, PregelExecutableTask, RetryPolicy, TimeoutPolicy
+
+logger = logging.getLogger(__name__)
+SUPPORTS_EXC_NOTES = sys.version_info >= (3, 11)
+
+
+def _timeout_secs(value: float | timedelta) -> float:
+ return value.total_seconds() if isinstance(value, timedelta) else value
+
+
+@dataclass(frozen=True, slots=True)
+class _ResolvedTimeout:
+ run_timeout_secs: float | None
+ idle_timeout_secs: float | None
+ refresh_on: Literal["auto", "heartbeat"] | None
+
+
+def _resolve_timeout(timeout: TimeoutPolicy) -> _ResolvedTimeout:
+ idle_timeout_secs = (
+ _timeout_secs(timeout.idle_timeout)
+ if timeout.idle_timeout is not None
+ else None
+ )
+ return _ResolvedTimeout(
+ run_timeout_secs=(
+ _timeout_secs(timeout.run_timeout)
+ if timeout.run_timeout is not None
+ else None
+ ),
+ idle_timeout_secs=idle_timeout_secs,
+ refresh_on=timeout.refresh_on if idle_timeout_secs is not None else None,
+ )
+
+
+class _AttemptContext(NamedTuple):
+ """Immutable per-attempt metadata shared across start/progress/finish events.
+
+ Built once at attempt start and referenced (not copied) by every emitted
+ `_AttemptEvent`, so per-event allocation is just the small event wrapper.
+
+ Intentionally underscore-prefixed: this and `_AttemptEvent` are part of an
+ internal observer contract consumed by langgraph-server. Do not move to
+ `langgraph.types` — server imports them by this path.
+ """
+
+ task_id: str
+ task_name: str
+ attempt: int
+ run_id: str | None
+ thread_id: str | None
+ checkpoint_ns: str | None
+ started_at: datetime
+ run_timeout_secs: float | None
+ idle_timeout_secs: float | None
+ refresh_on: Literal["auto", "heartbeat"] | None
+
+
+@dataclass(frozen=True, slots=True)
+class _AttemptEvent:
+ """One lifecycle event for a timed attempt.
+
+ Holds a reference to the shared `_AttemptContext` and the event-specific
+ fields. The observer must treat this and `context` as read-only — they
+ are reused across all events for the same attempt.
+ """
+
+ context: _AttemptContext
+ event: Literal["start", "progress", "finish"]
+ progress_at: datetime | None = None
+ finished_at: datetime | None = None
+ status: Literal["success", "error"] | None = None
+ error_type: str | None = None
+ error_message: str | None = None
+
+
+class _TimedAttemptScope:
+ """Guarded-config window for timed attempts.
+
+ The wrapped config marks writes, stream events, runtime stream writer calls,
+ child task scheduling, and any LangChain callback event emitted under the
+ node's run as observable progress when `refresh_on="auto"`.
+ `runtime.heartbeat()` exposes a manual progress signal for work that doesn't
+ otherwise emit any of these, and is the only progress signal when
+ `refresh_on="heartbeat"`.
+ Guarded writes are serialized with `close()` so cancelled background tasks
+ cannot persist writes past the timeout boundary. Stream/custom output is
+ best-effort: it is dropped after close is observed, but callbacks run outside
+ the lock because they may contain arbitrary user/runtime code.
+ """
+
+ __slots__ = (
+ "__weakref__",
+ "_active",
+ "_last_progress",
+ "_last_progress_emit",
+ "_lock",
+ "_on_progress",
+ "_progress_min_interval",
+ "_refresh_on",
+ )
+
+ def __init__(
+ self,
+ on_progress: Callable[[], None] | None = None,
+ progress_min_interval: float = 0.0,
+ refresh_on: Literal["auto", "heartbeat"] | None = None,
+ ) -> None:
+ self._active = True
+ self._last_progress = time.monotonic()
+ self._lock = threading.Lock()
+ self._on_progress = on_progress
+ self._progress_min_interval = progress_min_interval
+ self._refresh_on = refresh_on
+ # `-inf` so the first touch always passes the rate-limit gate.
+ self._last_progress_emit: float = float("-inf")
+
+ def wrap_config(self, config: RunnableConfig) -> RunnableConfig:
+ configurable = config.get(CONF, {})
+ patch: dict[str, Any] = {}
+ if (send := configurable.get(CONFIG_KEY_SEND)) is not None:
+ patch[CONFIG_KEY_SEND] = self._guard_send(send)
+ if (stream := configurable.get(CONFIG_KEY_STREAM)) is not None:
+ patch[CONFIG_KEY_STREAM] = self._guard_stream(stream)
+ if (call := configurable.get(CONFIG_KEY_CALL)) is not None:
+ patch[CONFIG_KEY_CALL] = self._guard_call(call)
+ if isinstance(runtime := configurable.get(CONFIG_KEY_RUNTIME), Runtime):
+ if self._refresh_on is not None:
+ patch[CONFIG_KEY_RUNTIME] = runtime.override(
+ stream_writer=self._guard_stream_writer(runtime.stream_writer),
+ heartbeat=self.touch,
+ )
+ else:
+ patch[CONFIG_KEY_RUNTIME] = runtime.override(
+ stream_writer=self._guard_stream_writer(runtime.stream_writer)
+ )
+ new_config = patch_configurable(config, patch) if patch else config
+ if self._refresh_on == "auto":
+ return merge_configs(
+ new_config, {"callbacks": [_IdleProgressCallbackHandler(self)]}
+ )
+ return new_config
+
+ def touch(self) -> None:
+ # Avoid locking this hot progress path. We accept a small race window in
+ # timestamp ordering because idle_timeout is expected to be coarse compared
+ # with scheduler/thread timing.
+ now = time.monotonic()
+ self._last_progress = now
+ if self._on_progress is None:
+ return
+ # Best-effort rate limit: a benign race may emit a duplicate progress
+ # event under heavy concurrency, which observers must already tolerate
+ # (callbacks fire from arbitrary threads).
+ if now - self._last_progress_emit < self._progress_min_interval:
+ return
+ self._last_progress_emit = now
+ self._on_progress()
+
+ def close(self) -> None:
+ with self._lock:
+ self._active = False
+
+ async def wait_for_idle_timeout(self, idle_timeout_s: float) -> None:
+ while True:
+ with self._lock:
+ if not self._active:
+ return
+ remaining = self._last_progress + idle_timeout_s - time.monotonic()
+ if remaining <= 0:
+ raise asyncio.TimeoutError
+ await asyncio.sleep(remaining)
+
+ def _guard_send(
+ self, send: Callable[[Sequence[tuple[str, Any]]], None]
+ ) -> Callable[[Sequence[tuple[str, Any]]], None]:
+ def guarded_send(writes: Sequence[tuple[str, Any]]) -> None:
+ with self._lock:
+ if self._active:
+ if writes and self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ send(writes)
+
+ return guarded_send
+
+ def _guard_stream(self, stream: StreamProtocol) -> StreamProtocol:
+ # No lock: stream callbacks fire from the event loop only, so the
+ # active-check + write happen atomically between awaits.
+ def guarded_stream(chunk: tuple[tuple[str, ...], str, Any]) -> None:
+ if not self._active:
+ return
+ if self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ stream(chunk)
+
+ return StreamProtocol(guarded_stream, stream.modes)
+
+ def _guard_call(self, call: Callable[..., Any]) -> Callable[..., Any]:
+ # No lock: child-task scheduling happens from the event loop only.
+ def guarded_call(*args: Any, **kwargs: Any) -> Any:
+ if not self._active:
+ raise asyncio.CancelledError
+ if self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ return call(*args, **kwargs)
+
+ return guarded_call
+
+ def _guard_stream_writer(
+ self, stream_writer: Callable[[Any], None]
+ ) -> Callable[[Any], None]:
+ def guarded_stream_writer(chunk: Any) -> None:
+ with self._lock:
+ if not self._active:
+ return
+ if self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ stream_writer(chunk)
+
+ return guarded_stream_writer
+
+
+class _IdleProgressCallbackHandler(BaseCallbackHandler):
+ """Resets the idle timeout clock on any LangChain callback event.
+
+ Inherits via `config["callbacks"]`, so it sees only events emitted by
+ runs descended from the node's attempt — sibling nodes do not bleed
+ through. Holds the scope by weakref so a child manager that outlives
+ the attempt cannot keep the scope alive.
+ """
+
+ # Run inline so progress is recorded in callback emission order;
+ # thread-pool dispatch would introduce extra reordering.
+ run_inline = True
+
+ def __init__(self, scope: _TimedAttemptScope) -> None:
+ self._scope_ref = weakref.ref(scope)
+
+ def _touch(self, *args: Any, **kwargs: Any) -> None:
+ if (scope := self._scope_ref()) is not None:
+ scope.touch()
+
+ on_llm_start = _touch
+ on_chat_model_start = _touch
+ on_llm_new_token = _touch
+ on_llm_end = _touch
+ on_llm_error = _touch
+ on_chain_start = _touch
+ on_chain_end = _touch
+ on_chain_error = _touch
+ on_tool_start = _touch
+ on_tool_end = _touch
+ on_tool_error = _touch
+ on_retriever_start = _touch
+ on_retriever_end = _touch
+ on_retriever_error = _touch
+ on_agent_action = _touch
+ on_agent_finish = _touch
+ on_text = _touch
+ on_retry = _touch
+ on_custom_event = _touch
+
+
+def _drain_cancelled(task: asyncio.Task[Any]) -> None:
+ # Mark the abandoned task's exception as retrieved so asyncio doesn't log it.
+ with suppress(asyncio.CancelledError):
+ task.exception()
+
+
+def _start_timed_attempt(
+ task: PregelExecutableTask, config: RunnableConfig, timeout: _ResolvedTimeout
+) -> _AttemptContext | None:
+ configurable = config.get(CONF, {})
+ callback = configurable.get(CONFIG_KEY_TIMED_ATTEMPT_OBSERVER)
+ if callback is None:
+ return None
+ runtime = configurable.get(CONFIG_KEY_RUNTIME)
+ execution_info = runtime.execution_info if isinstance(runtime, Runtime) else None
+ context = _AttemptContext(
+ task_id=task.id,
+ task_name=task.name,
+ attempt=execution_info.node_attempt if execution_info is not None else 1,
+ run_id=execution_info.run_id if execution_info is not None else None,
+ thread_id=execution_info.thread_id if execution_info is not None else None,
+ checkpoint_ns=(
+ execution_info.checkpoint_ns if execution_info is not None else None
+ ),
+ started_at=datetime.now(timezone.utc),
+ run_timeout_secs=timeout.run_timeout_secs,
+ idle_timeout_secs=timeout.idle_timeout_secs,
+ refresh_on=timeout.refresh_on,
+ )
+ _dispatch_observer(callback, _AttemptEvent(context=context, event="start"))
+ return context
+
+
+def _finish_timed_attempt(
+ config: RunnableConfig,
+ context: _AttemptContext | None,
+ error: BaseException | None = None,
+) -> None:
+ if context is None:
+ return
+ callback = config.get(CONF, {}).get(CONFIG_KEY_TIMED_ATTEMPT_OBSERVER)
+ if callback is None:
+ return
+ _dispatch_observer(
+ callback,
+ _AttemptEvent(
+ context=context,
+ event="finish",
+ finished_at=datetime.now(timezone.utc),
+ status="error" if error is not None else "success",
+ error_type=type(error).__name__ if error is not None else None,
+ error_message=str(error) if error is not None else None,
+ ),
+ )
+
+
+def _emit_progress(
+ callback: Callable[[_AttemptEvent], None],
+ context: _AttemptContext,
+) -> None:
+ _dispatch_observer(
+ callback,
+ _AttemptEvent(
+ context=context,
+ event="progress",
+ progress_at=datetime.now(timezone.utc),
+ ),
+ )
+
+
+def _dispatch_observer(
+ callback: Callable[[_AttemptEvent], None],
+ event: _AttemptEvent,
+) -> None:
+ try:
+ callback(event)
+ except Exception:
+ logger.warning("Timed attempt observer failed", exc_info=True)
+
+
+async def _run_timeout_watchdog(run_timeout_s: float) -> None:
+ await asyncio.sleep(run_timeout_s)
+ raise asyncio.TimeoutError
+
+
+async def _arun_with_timeout(
+ task: PregelExecutableTask,
+ config: RunnableConfig,
+ timeout: _ResolvedTimeout,
+ attempt_ctx: _AttemptContext | None,
+ *,
+ stream: bool,
+) -> Any:
+ run_timeout_s = timeout.run_timeout_secs
+ idle_timeout_s = timeout.idle_timeout_secs
+ on_progress: Callable[[], None] | None = None
+ if attempt_ctx is not None:
+ callback = config.get(CONF, {}).get(CONFIG_KEY_TIMED_ATTEMPT_OBSERVER)
+ if callback is not None and idle_timeout_s is not None:
+ on_progress = lambda: _emit_progress(callback, attempt_ctx) # noqa: E731
+ scope = _TimedAttemptScope(
+ on_progress=on_progress,
+ # Cap progress emission at ~4 events per idle window so token-rate
+ # callbacks don't flood the observer.
+ progress_min_interval=idle_timeout_s / 4 if idle_timeout_s is not None else 0.0,
+ refresh_on=timeout.refresh_on,
+ )
+ scoped_config = scope.wrap_config(config)
+ start = time.monotonic()
+ if stream:
+ # Yielded chunks count as progress only under `refresh_on="auto"`.
+ # `refresh_on="heartbeat"` is the strict mode where only explicit
+ # `runtime.heartbeat()` calls reset the idle clock.
+ async def run() -> Any:
+ async for _ in task.proc.astream(task.input, scoped_config):
+ if timeout.refresh_on == "auto":
+ scope.touch()
+
+ else:
+
+ async def run() -> Any:
+ return await task.proc.ainvoke(task.input, scoped_config)
+
+ bg = create_task_in_config_context(run, scoped_config)
+ watchdogs: dict[asyncio.Task[None], Literal["idle", "run"]] = {}
+ if idle_timeout_s is not None:
+ watchdogs[asyncio.create_task(scope.wait_for_idle_timeout(idle_timeout_s))] = (
+ "idle"
+ )
+ if run_timeout_s is not None:
+ watchdogs[asyncio.create_task(_run_timeout_watchdog(run_timeout_s))] = "run"
+ try:
+ done, _ = await asyncio.wait(
+ {bg, *watchdogs}, return_when=asyncio.FIRST_COMPLETED
+ )
+ if bg in done:
+ # Task completed in time.
+ for watchdog in watchdogs:
+ watchdog.cancel()
+ # FIRST_COMPLETED can return both; a watchdog may have
+ # already raised TimeoutError before we cancelled it.
+ for watchdog in watchdogs:
+ with suppress(asyncio.CancelledError, asyncio.TimeoutError):
+ await watchdog
+ return await bg
+ # bg was not in `done`, so every member of `done` is one of our
+ # watchdogs. Only a watchdog's TimeoutError converts to
+ # NodeTimeoutError; any TimeoutError raised by the proc itself
+ # propagates unchanged.
+ for watchdog in done:
+ kind = watchdogs[watchdog]
+ try:
+ await watchdog
+ except asyncio.TimeoutError as exc:
+ elapsed = time.monotonic() - start
+ scope.close()
+ task.writes.clear()
+ bg.cancel()
+ bg.add_done_callback(_drain_cancelled)
+ raise NodeTimeoutError(
+ task.name,
+ elapsed,
+ kind=kind,
+ idle_timeout=idle_timeout_s,
+ run_timeout=run_timeout_s,
+ ) from exc
+ raise RuntimeError(
+ f"{kind} timeout watchdog completed without raising TimeoutError"
+ )
+ raise RuntimeError("timeout wait completed without task or watchdog")
+ except asyncio.CancelledError:
+ scope.close()
+ bg.cancel()
+ for watchdog in watchdogs:
+ watchdog.cancel()
+ bg.add_done_callback(_drain_cancelled)
+ raise
+ finally:
+ scope.close()
+ for watchdog in watchdogs:
+ watchdog.cancel()
+
+
+def _ensure_execution_info(
+ runtime: Runtime, config: RunnableConfig, task: PregelExecutableTask
+) -> Runtime:
+ """Ensure runtime has execution_info, creating one from config if needed.
+
+ In the distributed runtime (LangGraph Platform), tasks are prepared by the
+ server and deserialized in the executor, bypassing the OSS _algo.py code
+ that normally creates ExecutionInfo. This function fills in execution_info
+ from the task config when it's missing.
+ """
+ if runtime.execution_info is not None:
+ return runtime
+ configurable = config.get(CONF, {})
+ return runtime.override(
+ execution_info=ExecutionInfo(
+ checkpoint_id=configurable.get(CONFIG_KEY_CHECKPOINT_ID) or "",
+ checkpoint_ns=configurable.get(CONFIG_KEY_CHECKPOINT_NS) or "",
+ task_id=configurable.get(CONFIG_KEY_TASK_ID) or task.id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+
+
+def _checkpoint_ns_for_parent_command(ns: str) -> str:
+ """Return the checkpoint namespace for the parent graph.
+
+ The checkpoint namespace is a `|`-separated path. Each segment is usually
+ of the form `name:task_id` (e.g. `parent_first:|node:`), but the
+ runtime may also insert a purely-numeric segment (e.g. `|1`) to disambiguate
+ concurrent tasks (e.g. `parent_first:|1|node:`).
+
+ Numeric segments are not real path levels, so we drop them before computing
+ the parent namespace.
+ """
+
+ parts = ns.split(NS_SEP)
+
+ # Drop any trailing numeric selectors for the current frame (e.g. `...|node:|1`).
+ while parts and parts[-1].isdigit():
+ parts.pop()
+
+ # Drop the current frame segment itself (e.g. the `node:`).
+ if parts:
+ parts.pop()
+
+ # Drop any trailing numeric selectors for the parent frame (e.g. `...|1|node:`).
+ while parts and parts[-1].isdigit():
+ parts.pop()
+
+ return NS_SEP.join(parts)
+
+
+def run_with_retry(
+ task: PregelExecutableTask,
+ retry_policy: Sequence[RetryPolicy] | None,
+ configurable: dict[str, Any] | None = None,
+) -> None:
+ """Run a task with retries."""
+ retry_policy = task.retry_policy or retry_policy
+ if task.timeout is not None:
+ # `validate_timeout_supported` catches sync nodes at compile time;
+ # this is a runtime safety net for paths that may bypass that validation.
+ raise sync_timeout_unsupported(task.name)
+ attempts = 0
+ node_first_attempt_time = time.time()
+ config = task.config
+ if configurable is not None:
+ config = patch_configurable(config, configurable)
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ runtime = _ensure_execution_info(runtime, config, task)
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ node_first_attempt_time=node_first_attempt_time,
+ )
+ },
+ )
+ while True:
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ # node_attempt is execution count (1-indexed): 1 on first run,
+ # then 2, 3, ... on subsequent retries.
+ node_attempt=attempts + 1,
+ )
+ },
+ )
+ try:
+ # clear any writes from previous attempts
+ task.writes.clear()
+ # run the task
+ return task.proc.invoke(task.input, config)
+ except ParentCommand as exc:
+ ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
+ cmd = exc.args[0]
+ # strip task_ids from namespace for comparison (ns format: "node1|node2:task_id")
+ if cmd.graph in (ns, recast_checkpoint_ns(ns), task.name):
+ # this command is for the current graph, handle it
+ for w in task.writers:
+ w.invoke(cmd, config)
+ break
+ elif cmd.graph == Command.PARENT:
+ # this command is for the parent graph, assign it to the parent.
+ exc.args = (replace(cmd, graph=_checkpoint_ns_for_parent_command(ns)),)
+ # bubble up
+ raise
+ except GraphBubbleUp:
+ # if interrupted, end
+ raise
+ except Exception as exc:
+ if SUPPORTS_EXC_NOTES:
+ exc.add_note(f"During task with name '{task.name}' and id '{task.id}'")
+ if not retry_policy:
+ raise
+
+ # Check which retry policy applies to this exception
+ matching_policy = None
+ for policy in retry_policy:
+ if _should_retry_on(policy, exc):
+ matching_policy = policy
+ break
+
+ if not matching_policy:
+ raise
+
+ # attempts tracks failed tries only; it increments after a failure.
+ attempts += 1
+ # check if we should give up
+ if attempts >= matching_policy.max_attempts:
+ raise
+ # sleep before retrying
+ interval = matching_policy.initial_interval
+ # Apply backoff factor based on attempt count
+ interval = min(
+ matching_policy.max_interval,
+ interval * (matching_policy.backoff_factor ** (attempts - 1)),
+ )
+
+ # Apply jitter if configured
+ sleep_time = (
+ interval + random.uniform(0, 1) if matching_policy.jitter else interval
+ )
+ time.sleep(sleep_time)
+
+ # log the retry
+ logger.info(
+ f"Retrying task {task.name} after {sleep_time:.2f} seconds (attempt {attempts}) after {exc.__class__.__name__} {exc}",
+ exc_info=exc,
+ )
+ # signal subgraphs to resume (if available)
+ config = patch_configurable(config, {CONFIG_KEY_RESUMING: True})
+
+
+async def arun_with_retry(
+ task: PregelExecutableTask,
+ retry_policy: Sequence[RetryPolicy] | None,
+ stream: bool = False,
+ match_cached_writes: Callable[[], Awaitable[Sequence[PregelExecutableTask]]]
+ | None = None,
+ configurable: dict[str, Any] | None = None,
+) -> None:
+ """Run a task asynchronously with retries."""
+ retry_policy = task.retry_policy or retry_policy
+ resolved_timeout = (
+ _resolve_timeout(task.timeout) if task.timeout is not None else None
+ )
+ attempts = 0
+ node_first_attempt_time = time.time()
+ config = task.config
+ if configurable is not None:
+ config = patch_configurable(config, configurable)
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ runtime = _ensure_execution_info(runtime, config, task)
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ node_first_attempt_time=node_first_attempt_time,
+ )
+ },
+ )
+ if match_cached_writes is not None and task.cache_key is not None:
+ for t in await match_cached_writes():
+ if t is task:
+ # if the task is already cached, return
+ return
+ while True:
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ # node_attempt is execution count (1-indexed): 1 on first run,
+ # then 2, 3, ... on subsequent retries.
+ node_attempt=attempts + 1,
+ )
+ },
+ )
+ attempt_ctx = (
+ _start_timed_attempt(task, config, resolved_timeout)
+ if resolved_timeout is not None
+ else None
+ )
+ try:
+ task.writes.clear()
+ if resolved_timeout is None:
+ if stream:
+ async for _ in task.proc.astream(task.input, config):
+ pass
+ break
+ return await task.proc.ainvoke(task.input, config)
+ result = await _arun_with_timeout(
+ task, config, resolved_timeout, attempt_ctx, stream=stream
+ )
+ _finish_timed_attempt(config, attempt_ctx)
+ if stream:
+ # if successful, end
+ break
+ return result
+ except ParentCommand as exc:
+ ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
+ cmd = exc.args[0]
+ # strip task_ids from namespace for comparison (ns format: "node1|node2:task_id")
+ if cmd.graph in (ns, recast_checkpoint_ns(ns), task.name):
+ try:
+ # this command is for the current graph, handle it
+ for w in task.writers:
+ w.invoke(cmd, config)
+ except Exception as writer_exc:
+ _finish_timed_attempt(config, attempt_ctx, writer_exc)
+ raise
+ _finish_timed_attempt(config, attempt_ctx)
+ break
+ elif cmd.graph == Command.PARENT:
+ # this command is for the parent graph, assign it to the parent.
+ exc.args = (replace(cmd, graph=_checkpoint_ns_for_parent_command(ns)),)
+ _finish_timed_attempt(config, attempt_ctx)
+ # bubble up the exception to the parent graph
+ raise
+ except GraphBubbleUp:
+ # if interrupted, end
+ _finish_timed_attempt(config, attempt_ctx)
+ raise
+ except Exception as exc:
+ _finish_timed_attempt(config, attempt_ctx, exc)
+ if SUPPORTS_EXC_NOTES:
+ exc.add_note(f"During task with name '{task.name}' and id '{task.id}'")
+ if not retry_policy:
+ raise
+
+ # Check which retry policy applies to this exception
+ matching_policy = None
+ for policy in retry_policy:
+ if _should_retry_on(policy, exc):
+ matching_policy = policy
+ break
+
+ if not matching_policy:
+ raise
+
+ # attempts tracks failed tries only; it increments after a failure.
+ # The next execution's node_attempt is derived as attempts + 1.
+ attempts += 1
+ # check if we should give up
+ if attempts >= matching_policy.max_attempts:
+ raise
+ # sleep before retrying
+ interval = matching_policy.initial_interval
+ # Apply backoff factor based on attempt count
+ interval = min(
+ matching_policy.max_interval,
+ interval * (matching_policy.backoff_factor ** (attempts - 1)),
+ )
+
+ # Apply jitter if configured
+ sleep_time = (
+ interval + random.uniform(0, 1) if matching_policy.jitter else interval
+ )
+ await asyncio.sleep(sleep_time)
+
+ # log the retry
+ logger.info(
+ f"Retrying task {task.name} after {sleep_time:.2f} seconds (attempt {attempts}) after {exc.__class__.__name__} {exc}",
+ exc_info=exc,
+ )
+ # signal subgraphs to resume (if available)
+ config = patch_configurable(config, {CONFIG_KEY_RESUMING: True})
+
+
+def _should_retry_on(retry_policy: RetryPolicy, exc: Exception) -> bool:
+ """Check if the given exception should be retried based on the retry policy."""
+ if isinstance(retry_policy.retry_on, Sequence):
+ return isinstance(exc, tuple(retry_policy.retry_on))
+ elif isinstance(retry_policy.retry_on, type) and issubclass(
+ retry_policy.retry_on, Exception
+ ):
+ return isinstance(exc, retry_policy.retry_on)
+ elif callable(retry_policy.retry_on):
+ return retry_policy.retry_on(exc) # type: ignore[call-arg]
+ else:
+ raise TypeError(
+ "retry_on must be an Exception class, a list or tuple of Exception classes, or a callable"
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_runner.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d53b9f9de80dc397ec23c79f0707e38152f9519
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_runner.py
@@ -0,0 +1,941 @@
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import inspect
+import threading
+import time
+import weakref
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Collection,
+ Iterable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from functools import partial
+from typing import (
+ Any,
+ Generic,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.callbacks import Callbacks
+
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CALL,
+ CONFIG_KEY_SCRATCHPAD,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ INTERRUPT,
+ NO_WRITES,
+ RESUME,
+ RETURN,
+)
+from langgraph._internal._future import chain_future, run_coroutine_threadsafe
+from langgraph._internal._scratchpad import PregelScratchpad
+from langgraph._internal._typing import MISSING
+from langgraph.constants import TAG_HIDDEN
+from langgraph.errors import GraphBubbleUp, GraphInterrupt
+from langgraph.pregel._algo import Call
+from langgraph.pregel._executor import Submit
+from langgraph.pregel._retry import arun_with_retry, run_with_retry
+from langgraph.types import (
+ CachePolicy,
+ PregelExecutableTask,
+ RetryPolicy,
+ TimeoutPolicy,
+)
+
+F = TypeVar("F", concurrent.futures.Future, asyncio.Future)
+E = TypeVar("E", threading.Event, asyncio.Event)
+
+# List of filenames to exclude from exception traceback
+# Note: Frames will be removed if they are the last frame in traceback, recursively
+EXCLUDED_FRAME_FNAMES = (
+ "langgraph/pregel/retry.py",
+ "langgraph/pregel/runner.py",
+ "langgraph/pregel/executor.py",
+ "langgraph/utils/runnable.py",
+ "langchain_core/runnables/config.py",
+ "concurrent/futures/thread.py",
+ "concurrent/futures/_base.py",
+)
+
+SKIP_RERAISE_SET: weakref.WeakSet[concurrent.futures.Future | asyncio.Future] = (
+ weakref.WeakSet()
+)
+
+
+class FuturesDict(Generic[F, E], dict[F, PregelExecutableTask | None]):
+ event: E
+ callback: weakref.ref[Callable[[PregelExecutableTask, BaseException | None], None]]
+ # Stop condition is injected by PregelRunner instead of hard-coded here.
+ # This lets the runner treat graph-error-handled exceptions as non-fatal
+ # so `on_done` does not trigger an early stop for those futures.
+ should_stop: Callable[[set[F]], bool]
+ counter: int
+ done: set[F]
+ lock: threading.Lock
+
+ def __init__(
+ self,
+ event: E,
+ callback: weakref.ref[
+ Callable[[PregelExecutableTask, BaseException | None], None]
+ ],
+ should_stop: Callable[[set[F]], bool],
+ future_type: type[F],
+ # used for generic typing, newer py supports FutureDict[...](...)
+ ) -> None:
+ super().__init__()
+ self.lock = threading.Lock()
+ self.event = event
+ self.callback = callback
+ self.should_stop = should_stop
+ self.counter = 0
+ self.done: set[F] = set()
+
+ def __setitem__(
+ self,
+ key: F,
+ value: PregelExecutableTask | None,
+ ) -> None:
+ super().__setitem__(key, value) # type: ignore[index]
+ if value is not None:
+ with self.lock:
+ self.event.clear()
+ self.counter += 1
+ key.add_done_callback(partial(self.on_done, value))
+
+ def on_done(
+ self,
+ task: PregelExecutableTask,
+ fut: F,
+ ) -> None:
+ # Called automatically by future.add_done_callback registered in __setitem__.
+ try:
+ if cb := self.callback():
+ cb(task, _exception(fut))
+ finally:
+ with self.lock:
+ self.done.add(fut)
+ self.counter -= 1
+ # Wake waiter when all tracked futures are done, or when runner-level
+ # stop condition is met (for example, a non-handled fatal exception).
+ if self.counter == 0 or self.should_stop(self.done):
+ self.event.set()
+
+
+class PregelRunner:
+ """Responsible for executing a set of Pregel tasks concurrently, committing
+ their writes, yielding control to caller when there is output to emit, and
+ interrupting other tasks if appropriate."""
+
+ def __init__(
+ self,
+ *,
+ submit: weakref.ref[Submit],
+ put_writes: weakref.ref[Callable[[str, Sequence[tuple[str, Any]]], None]],
+ use_astream: bool = False,
+ node_finished: Callable[[str], None] | None = None,
+ node_error_handler_map: Mapping[str, str] | None = None,
+ schedule_error_handler: Callable[
+ [PregelExecutableTask, BaseException], PregelExecutableTask | None
+ ]
+ | None = None,
+ aschedule_error_handler: Callable[
+ [PregelExecutableTask, BaseException],
+ Awaitable[PregelExecutableTask | None],
+ ]
+ | None = None,
+ ) -> None:
+ self.submit = submit
+ self.put_writes = put_writes
+ self.use_astream = use_astream
+ self.node_finished = node_finished
+ self.node_error_handler_map = dict(node_error_handler_map or {})
+ self.error_handler_nodes = set(self.node_error_handler_map.values())
+ self.schedule_error_handler = schedule_error_handler
+ self.aschedule_error_handler = aschedule_error_handler
+ # Exception object ids that are already routed to graph-level error handler.
+ # These ids are consulted by stop/panic checks to avoid re-raising handled
+ # exceptions via the normal fatal path in the same run.
+ self._handled_exception_ids: set[int] = set()
+
+ def _should_route_to_error_handler(self, task: PregelExecutableTask) -> bool:
+ if task.name in self.error_handler_nodes:
+ return False
+ return task.name in self.node_error_handler_map
+
+ def tick(
+ self,
+ tasks: Iterable[PregelExecutableTask],
+ *,
+ reraise: bool = True,
+ timeout: float | None = None,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ get_waiter: Callable[[], concurrent.futures.Future[None]] | None = None,
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ PregelExecutableTask | None,
+ ],
+ ) -> Iterator[None]:
+ tasks = tuple(tasks)
+ futures = FuturesDict(
+ callback=weakref.WeakMethod(self.commit),
+ event=threading.Event(),
+ should_stop=partial(
+ _should_stop_others, handled_exception_ids=self._handled_exception_ids
+ ),
+ future_type=concurrent.futures.Future,
+ )
+ # give control back to the caller
+ yield
+ # fast path if single task with no timeout and no waiter
+ if len(tasks) == 0:
+ return
+ elif len(tasks) == 1 and timeout is None and get_waiter is None:
+ t = tasks[0]
+ scheduled_error_handler = False
+ try:
+ run_with_retry(
+ t,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(t),
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ ),
+ },
+ )
+ self.commit(t, None)
+ except Exception as exc:
+ self.commit(t, exc)
+ if (
+ not isinstance(exc, GraphBubbleUp)
+ and self._should_route_to_error_handler(t)
+ and self.schedule_error_handler is not None
+ ):
+ self._handled_exception_ids.add(id(exc))
+ if handler_task := self.schedule_error_handler(t, exc):
+ tasks = (handler_task,)
+ scheduled_error_handler = True
+ # Continue to the regular scheduling path for handler execution.
+ if reraise and futures:
+ if id(exc) not in self._handled_exception_ids:
+ # will be re-raised after futures are done
+ fut: concurrent.futures.Future = concurrent.futures.Future()
+ fut.set_exception(exc)
+ futures.done.add(fut)
+ elif reraise and id(exc) not in self._handled_exception_ids:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+ if not futures and not scheduled_error_handler:
+ # maybe `t` scheduled another task
+ return
+ else:
+ if not scheduled_error_handler:
+ tasks = () # don't reschedule this task
+ # add waiter task if requested
+ if get_waiter is not None:
+ futures[get_waiter()] = None
+ # schedule tasks
+ for t in tasks:
+ fut = self.submit()( # type: ignore[misc]
+ run_with_retry,
+ t,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(t),
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ ),
+ },
+ __reraise_on_exit__=reraise,
+ )
+ futures[fut] = t
+ # execute tasks, and wait for one to fail or all to finish.
+ # each task is independent from all other concurrent tasks
+ # yield updates/debug output as each task finishes
+ end_time = timeout + time.monotonic() if timeout else None
+ handled_futures: set[concurrent.futures.Future[Any]] = set()
+ while len(futures) > (1 if get_waiter is not None else 0):
+ done, inflight = concurrent.futures.wait(
+ futures,
+ return_when=concurrent.futures.FIRST_COMPLETED,
+ timeout=(max(0, end_time - time.monotonic()) if end_time else None),
+ )
+ if not done:
+ break # timed out
+ done_for_stop: set[concurrent.futures.Future[Any]] = set()
+ for fut in done:
+ task = futures.pop(fut)
+ if task is None:
+ # waiter task finished, schedule another
+ if inflight and get_waiter is not None:
+ futures[get_waiter()] = None
+ elif (
+ (task_exc := _exception(fut))
+ and self._should_route_to_error_handler(task)
+ and not isinstance(task_exc, GraphBubbleUp)
+ ):
+ self._handled_exception_ids.add(id(task_exc))
+ SKIP_RERAISE_SET.add(fut)
+ handled_futures.add(fut)
+ if self.schedule_error_handler is not None:
+ if handler_task := self.schedule_error_handler(task, task_exc):
+ handler_fut = self.submit()( # type: ignore[misc]
+ run_with_retry,
+ handler_task,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(handler_task),
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ ),
+ },
+ __reraise_on_exit__=reraise,
+ )
+ futures[handler_fut] = handler_task
+ else:
+ done_for_stop.add(fut)
+ else:
+ # remove references to loop vars
+ del fut, task
+ # maybe stop other tasks
+ if _should_stop_others(
+ done_for_stop, handled_exception_ids=self._handled_exception_ids
+ ):
+ break
+ # give control back to the caller
+ yield
+ # wait for done callbacks
+ futures.event.wait(
+ timeout=(max(0, end_time - time.monotonic()) if end_time else None)
+ )
+ # give control back to the caller
+ yield
+ # panic on failure or timeout
+ try:
+ _panic_or_proceed(
+ futures.done.union(f for f, t in futures.items() if t is not None),
+ panic=reraise,
+ handled_exception_ids=self._handled_exception_ids,
+ handled_futures=handled_futures,
+ )
+ except Exception as exc:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+
+ async def atick(
+ self,
+ tasks: Iterable[PregelExecutableTask],
+ *,
+ reraise: bool = True,
+ timeout: float | None = None,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ get_waiter: Callable[[], asyncio.Future[None]] | None = None,
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ Awaitable[PregelExecutableTask | None],
+ ],
+ ) -> AsyncIterator[None]:
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ tasks = tuple(tasks)
+ futures = FuturesDict(
+ callback=weakref.WeakMethod(self.commit),
+ event=asyncio.Event(),
+ should_stop=partial(
+ _should_stop_others, handled_exception_ids=self._handled_exception_ids
+ ),
+ future_type=asyncio.Future,
+ )
+ # give control back to the caller
+ yield
+ # fast path if single task with no waiter and no timeout
+ if len(tasks) == 0:
+ return
+ elif len(tasks) == 1 and get_waiter is None and timeout is None:
+ t = tasks[0]
+ scheduled_error_handler = False
+ try:
+ await arun_with_retry(
+ t,
+ retry_policy,
+ stream=self.use_astream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(t),
+ stream=self.use_astream,
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ loop=loop,
+ ),
+ },
+ )
+ self.commit(t, None)
+ except Exception as exc:
+ self.commit(t, exc)
+ if (
+ not isinstance(exc, GraphBubbleUp)
+ and self._should_route_to_error_handler(t)
+ and self.aschedule_error_handler is not None
+ ):
+ self._handled_exception_ids.add(id(exc))
+ if handler_task := await self.aschedule_error_handler(t, exc):
+ tasks = (handler_task,)
+ scheduled_error_handler = True
+ if reraise and futures:
+ if id(exc) not in self._handled_exception_ids:
+ # will be re-raised after futures are done
+ fut: asyncio.Future = loop.create_future()
+ fut.set_exception(exc)
+ futures.done.add(fut)
+ elif reraise and id(exc) not in self._handled_exception_ids:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+ if not futures and not scheduled_error_handler:
+ # maybe `t` scheduled another task
+ return
+ else:
+ if not scheduled_error_handler:
+ tasks = () # don't reschedule this task
+ # add waiter task if requested
+ if get_waiter is not None:
+ futures[get_waiter()] = None
+ # schedule tasks
+ for t in tasks:
+ fut = cast(
+ asyncio.Future,
+ self.submit()( # type: ignore[misc]
+ arun_with_retry,
+ t,
+ retry_policy,
+ stream=self.use_astream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(t),
+ retry_policy=retry_policy,
+ stream=self.use_astream,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ loop=loop,
+ ),
+ },
+ __name__=t.name,
+ __cancel_on_exit__=True,
+ __reraise_on_exit__=reraise,
+ ),
+ )
+ futures[fut] = t
+ # execute tasks, and wait for one to fail or all to finish.
+ # each task is independent from all other concurrent tasks
+ # yield updates/debug output as each task finishes
+ end_time = timeout + loop.time() if timeout else None
+ handled_futures: set[asyncio.Future[Any]] = set()
+ while len(futures) > (1 if get_waiter is not None else 0):
+ done, inflight = await asyncio.wait(
+ futures,
+ return_when=asyncio.FIRST_COMPLETED,
+ timeout=(max(0, end_time - loop.time()) if end_time else None),
+ )
+ if not done:
+ break # timed out
+ done_for_stop: set[asyncio.Future[Any]] = set()
+ for fut in done:
+ task = futures.pop(fut)
+ if task is None:
+ # waiter task finished, schedule another
+ if inflight and get_waiter is not None:
+ futures[get_waiter()] = None
+ elif (
+ (task_exc := _exception(fut))
+ and self._should_route_to_error_handler(task)
+ and not isinstance(task_exc, GraphBubbleUp)
+ ):
+ self._handled_exception_ids.add(id(task_exc))
+ SKIP_RERAISE_SET.add(fut)
+ handled_futures.add(fut)
+ if self.aschedule_error_handler is not None:
+ if handler_task := await self.aschedule_error_handler(
+ task, task_exc
+ ):
+ handler_fut = cast(
+ asyncio.Future,
+ self.submit()( # type: ignore[misc]
+ arun_with_retry,
+ handler_task,
+ retry_policy,
+ stream=self.use_astream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(handler_task),
+ retry_policy=retry_policy,
+ stream=self.use_astream,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ loop=loop,
+ ),
+ },
+ __name__=handler_task.name,
+ __cancel_on_exit__=True,
+ __reraise_on_exit__=reraise,
+ ),
+ )
+ futures[handler_fut] = handler_task
+ else:
+ done_for_stop.add(fut)
+ else:
+ # remove references to loop vars
+ del fut, task
+ # maybe stop other tasks
+ if _should_stop_others(
+ done_for_stop, handled_exception_ids=self._handled_exception_ids
+ ):
+ break
+ # give control back to the caller
+ yield
+ # wait for done callbacks
+ await asyncio.wait_for(
+ futures.event.wait(),
+ timeout=(max(0, end_time - loop.time()) if end_time else None),
+ )
+ # give control back to the caller
+ yield
+ # cancel waiter task
+ for fut in futures:
+ fut.cancel()
+ # panic on failure or timeout
+ try:
+ _panic_or_proceed(
+ futures.done.union(f for f, t in futures.items() if t is not None),
+ timeout_exc_cls=asyncio.TimeoutError,
+ panic=reraise,
+ handled_exception_ids=self._handled_exception_ids,
+ handled_futures=handled_futures,
+ )
+ except Exception as exc:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+
+ def commit(
+ self,
+ task: PregelExecutableTask,
+ exception: BaseException | None,
+ ) -> None:
+ if isinstance(exception, asyncio.CancelledError):
+ # for cancelled tasks, also save error in task,
+ # so loop can finish super-step
+ task.writes.append((ERROR, exception))
+ self.put_writes()(task.id, task.writes) # type: ignore[misc]
+ elif exception:
+ if isinstance(exception, GraphInterrupt):
+ # save interrupt to checkpointer
+ if exception.args[0]:
+ writes = [(INTERRUPT, exception.args[0])]
+ if resumes := [w for w in task.writes if w[0] == RESUME]:
+ writes.extend(resumes)
+ self.put_writes()(task.id, writes) # type: ignore[misc]
+ elif isinstance(exception, GraphBubbleUp):
+ # exception will be raised in _panic_or_proceed
+ pass
+ else:
+ # save error to checkpointer
+ task.writes.append((ERROR, exception))
+ if self._should_route_to_error_handler(task) and not isinstance(
+ exception, GraphBubbleUp
+ ):
+ task.writes.append((ERROR_SOURCE_NODE, task.name))
+ self._handled_exception_ids.add(id(exception))
+ self.put_writes()(task.id, task.writes) # type: ignore[misc]
+ else:
+ if self.node_finished and (
+ task.config is None or TAG_HIDDEN not in task.config.get("tags", [])
+ ):
+ self.node_finished(task.name)
+ if not task.writes:
+ # add no writes marker
+ task.writes.append((NO_WRITES, None))
+ # save task writes to checkpointer
+ self.put_writes()(task.id, task.writes) # type: ignore[misc]
+
+
+def _should_stop_others(
+ done: set[F],
+ *,
+ handled_exception_ids: set[int] | None = None,
+) -> bool:
+ """Check if any task failed, if so, cancel all other tasks.
+ GraphInterrupts are not considered failures."""
+ for fut in done:
+ if fut.cancelled():
+ continue
+ elif exc := fut.exception():
+ if (
+ id(exc) not in (handled_exception_ids or set())
+ and not isinstance(exc, GraphBubbleUp)
+ and fut not in SKIP_RERAISE_SET
+ ):
+ return True
+
+ return False
+
+
+def _exception(
+ fut: concurrent.futures.Future[Any] | asyncio.Future[Any],
+) -> BaseException | None:
+ """Return the exception from a future, without raising CancelledError."""
+ if fut.cancelled():
+ if isinstance(fut, asyncio.Future):
+ return asyncio.CancelledError()
+ else:
+ return concurrent.futures.CancelledError()
+ else:
+ return fut.exception()
+
+
+def _panic_or_proceed(
+ futs: set[concurrent.futures.Future] | set[asyncio.Future],
+ *,
+ timeout_exc_cls: type[Exception] = TimeoutError,
+ panic: bool = True,
+ handled_exception_ids: set[int] | None = None,
+ handled_futures: Collection[concurrent.futures.Future[Any] | asyncio.Future[Any]]
+ | None = None,
+) -> None:
+ """Cancel remaining tasks if any failed, re-raise exception if panic is True."""
+ done: set[concurrent.futures.Future[Any] | asyncio.Future[Any]] = set()
+ inflight: set[concurrent.futures.Future[Any] | asyncio.Future[Any]] = set()
+ for fut in futs:
+ if fut.cancelled():
+ continue
+ elif fut.done():
+ done.add(fut)
+ else:
+ inflight.add(fut)
+ interrupts: list[GraphInterrupt] = []
+ while done:
+ # if any task failed
+ fut = done.pop()
+ if exc := _exception(fut):
+ if fut in (handled_futures or set()):
+ continue
+ if id(exc) in (handled_exception_ids or set()):
+ continue
+ # cancel all pending tasks
+ while inflight:
+ inflight.pop().cancel()
+ # raise the exception
+ if panic:
+ if isinstance(exc, GraphInterrupt):
+ # collect interrupts
+ interrupts.append(exc)
+ elif fut not in SKIP_RERAISE_SET:
+ raise exc
+ # raise combined interrupts
+ if interrupts:
+ raise GraphInterrupt(tuple(i for exc in interrupts for i in exc.args[0]))
+ if inflight:
+ # if we got here means we timed out
+ while inflight:
+ # cancel all pending tasks
+ inflight.pop().cancel()
+ # raise timeout error
+ raise timeout_exc_cls("Timed out")
+
+
+def _call(
+ task: weakref.ref[PregelExecutableTask],
+ func: Callable[[Any], Awaitable[Any] | Any],
+ input: Any,
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+ callbacks: Callbacks = None,
+ futures: weakref.ref[FuturesDict],
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None], PregelExecutableTask | None
+ ],
+ submit: weakref.ref[Submit],
+) -> concurrent.futures.Future[Any]:
+ if inspect.iscoroutinefunction(func):
+ raise RuntimeError("In an sync context async tasks cannot be called")
+
+ fut: concurrent.futures.Future | None = None
+ # schedule PUSH tasks, collect futures
+ scratchpad: PregelScratchpad = task().config[CONF][CONFIG_KEY_SCRATCHPAD] # type: ignore[union-attr]
+ # schedule the next task, if the callback returns one
+ if next_task := schedule_task(
+ task(), # type: ignore[arg-type]
+ scratchpad.call_counter(),
+ Call(
+ func,
+ input,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ callbacks=callbacks,
+ timeout=timeout,
+ ),
+ ):
+ if fut := next(
+ (
+ f
+ for f, t in list(futures().items()) # type: ignore[union-attr]
+ if t is not None and t == next_task.id
+ ),
+ None,
+ ):
+ # if the parent task was retried,
+ # the next task might already be running
+ pass
+ elif next_task.writes:
+ # if it already ran, return the result
+ fut = concurrent.futures.Future()
+ ret = next((v for c, v in next_task.writes if c == RETURN), MISSING)
+ if ret is not MISSING:
+ fut.set_result(ret)
+ elif exc := next((v for c, v in next_task.writes if c == ERROR), None):
+ fut.set_exception(
+ exc if isinstance(exc, BaseException) else Exception(exc)
+ )
+ else:
+ fut.set_result(None)
+ else:
+ # schedule the next task
+ fut = submit()( # type: ignore[misc]
+ run_with_retry,
+ next_task,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(next_task),
+ futures=futures,
+ retry_policy=retry_policy,
+ callbacks=callbacks,
+ schedule_task=schedule_task,
+ submit=submit,
+ ),
+ },
+ __reraise_on_exit__=False,
+ # starting a new task in the next tick ensures
+ # updates from this tick are committed/streamed first
+ __next_tick__=True,
+ )
+ # exceptions for call() tasks are raised into the parent task
+ # so we should not re-raise at the end of the tick
+ SKIP_RERAISE_SET.add(fut)
+ futures()[fut] = next_task # type: ignore[index]
+ fut = cast(asyncio.Future | concurrent.futures.Future, fut)
+ # return a chained future to ensure commit() callback is called
+ # before the returned future is resolved, to ensure stream order etc
+ return chain_future(fut, concurrent.futures.Future())
+
+
+def _acall(
+ task: weakref.ref[PregelExecutableTask],
+ func: Callable[[Any], Awaitable[Any] | Any],
+ input: Any,
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+ callbacks: Callbacks = None,
+ # injected dependencies
+ futures: weakref.ref[FuturesDict],
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ Awaitable[PregelExecutableTask | None],
+ ],
+ submit: weakref.ref[Submit],
+ loop: asyncio.AbstractEventLoop,
+ stream: bool = False,
+) -> asyncio.Future[Any] | concurrent.futures.Future[Any]:
+ # return a chained future to ensure commit() callback is called
+ # before the returned future is resolved, to ensure stream order etc
+ try:
+ in_async = asyncio.current_task() is not None
+ except RuntimeError:
+ in_async = False
+ # if in async context return an async future, otherwise return a sync future
+ if in_async:
+ fut: asyncio.Future[Any] | concurrent.futures.Future[Any] = asyncio.Future(
+ loop=loop
+ )
+ else:
+ fut = concurrent.futures.Future()
+ # schedule the next task
+ run_coroutine_threadsafe(
+ _acall_impl(
+ fut,
+ task,
+ func,
+ input,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ timeout=timeout,
+ callbacks=callbacks,
+ futures=futures,
+ schedule_task=schedule_task,
+ submit=submit,
+ loop=loop,
+ stream=stream,
+ ),
+ loop,
+ lazy=False,
+ )
+ return fut
+
+
+async def _acall_impl(
+ destination: asyncio.Future[Any] | concurrent.futures.Future[Any],
+ task: weakref.ref[PregelExecutableTask],
+ func: Callable[[Any], Awaitable[Any] | Any],
+ input: Any,
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+ callbacks: Callbacks = None,
+ # injected dependencies
+ futures: weakref.ref[FuturesDict[asyncio.Future, asyncio.Event]],
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ Awaitable[PregelExecutableTask | None],
+ ],
+ submit: weakref.ref[Submit],
+ loop: asyncio.AbstractEventLoop,
+ stream: bool = False,
+) -> None:
+ try:
+ fut: asyncio.Future | None = None
+ # schedule PUSH tasks, collect futures
+ scratchpad: PregelScratchpad = task().config[CONF][CONFIG_KEY_SCRATCHPAD] # type: ignore[union-attr]
+ # schedule the next task, if the callback returns one
+ if next_task := await schedule_task(
+ task(), # type: ignore[arg-type]
+ scratchpad.call_counter(),
+ Call(
+ func,
+ input,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ callbacks=callbacks,
+ timeout=timeout,
+ ),
+ ):
+ if fut := next(
+ (
+ f
+ for f, t in list(futures().items()) # type: ignore[union-attr]
+ if t is not None and t == next_task.id
+ ),
+ None,
+ ):
+ # if the parent task was retried,
+ # the next task might already be running
+ pass
+ elif next_task.writes:
+ # if it already ran, return the result
+ fut = asyncio.Future(loop=loop)
+ ret = next((v for c, v in next_task.writes if c == RETURN), MISSING)
+ if ret is not MISSING:
+ fut.set_result(ret)
+ elif exc := next((v for c, v in next_task.writes if c == ERROR), None):
+ fut.set_exception(
+ exc if isinstance(exc, BaseException) else Exception(exc)
+ )
+ else:
+ fut.set_result(None)
+ else:
+ # schedule the next task
+ fut = cast(
+ asyncio.Future,
+ submit()( # type: ignore[misc]
+ arun_with_retry,
+ next_task,
+ retry_policy,
+ stream=stream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(next_task),
+ stream=stream,
+ futures=futures,
+ schedule_task=schedule_task,
+ submit=submit,
+ loop=loop,
+ ),
+ },
+ __name__=next_task.name,
+ __cancel_on_exit__=True,
+ __reraise_on_exit__=False,
+ # starting a new task in the next tick ensures
+ # updates from this tick are committed/streamed first
+ __next_tick__=True,
+ ),
+ )
+ # exceptions for call() tasks are raised into the parent task
+ # so we should not re-raise at the end of the tick
+ SKIP_RERAISE_SET.add(fut)
+ futures()[fut] = next_task # type: ignore[index]
+ if fut is not None:
+ chain_future(fut, destination)
+ else:
+ destination.set_exception(RuntimeError("Task not scheduled"))
+ except Exception as exc:
+ destination.set_exception(exc)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_tools.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd7bb63bc0ce57c1100e33beabd751d10831f07e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_tools.py
@@ -0,0 +1,268 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Callable, Iterator
+from contextvars import ContextVar, Token
+from typing import Any, TypeVar, cast
+from uuid import UUID
+
+from langchain_core.callbacks import BaseCallbackHandler
+
+from langgraph._internal._constants import NS_SEP
+from langgraph.constants import TAG_NOSTREAM
+from langgraph.pregel.protocol import StreamChunk
+
+try:
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
+except ImportError:
+ _StreamingCallbackHandler = object # type: ignore[assignment,misc]
+
+
+T = TypeVar("T")
+
+ToolCallWriter = Callable[[Any], None]
+"""A closure bound to a single tool call that emits `tool-output-delta` events."""
+
+_tool_call_writer: ContextVar[ToolCallWriter | None] = ContextVar(
+ "langgraph_tool_call_writer", default=None
+)
+"""ContextVar holding the writer for the currently-executing tool call.
+
+Set by `StreamToolCallHandler.on_tool_start` and reset on end/error.
+Read by `ToolRuntime.emit_output_delta` (in `langgraph.prebuilt`).
+"""
+
+
+class StreamToolCallHandler(BaseCallbackHandler, _StreamingCallbackHandler):
+ """Callback handler that emits tool-call lifecycle events on the stream.
+
+ Fires on LangChain's `on_tool_*` callbacks and pushes to the `tools`
+ stream mode. Emits `tool-started` / `tool-output-delta` /
+ `tool-finished` / `tool-error` payloads keyed by `tool_call_id`.
+
+ While a tool is executing, this handler sets `_tool_call_writer` to a
+ closure bound to that call's namespace and `tool_call_id`.
+ `ToolRuntime.emit_output_delta` reads that ContextVar so tool bodies
+ can stream partial output without threading the writer through their
+ own signature.
+
+ Attached by `Pregel.stream` / `astream` when `"tools"` is in
+ `stream_modes`. `run_inline = True` keeps event ordering
+ deterministic.
+ """
+
+ run_inline = True
+
+ def __init__(
+ self,
+ stream: Callable[[StreamChunk], None],
+ subgraphs: bool,
+ *,
+ parent_ns: tuple[str, ...] | None = None,
+ ) -> None:
+ """Configure the handler to stream tool-call events.
+
+ Args:
+ stream: Callable that accepts a `StreamChunk` tuple
+ `(namespace, mode, payload)` and enqueues it.
+ subgraphs: Whether to emit events from tools called inside
+ nested subgraphs. When False, only tools at the
+ handler's own scope (`parent_ns`) emit.
+ parent_ns: Namespace where the handler was attached.
+ Mirrors the `StreamMessagesHandler` escape hatch:
+ tools whose containing namespace equals `parent_ns`
+ still emit even with `subgraphs=False`, so a node that
+ explicitly streams a subgraph with `stream_mode="tools"`
+ sees its own tools.
+ """
+ self.stream = stream
+ self.subgraphs = subgraphs
+ self.parent_ns = parent_ns
+ # run_id → (namespace, tool_call_id, ContextVar token)
+ # `on_tool_end` does not receive `tool_call_id` in kwargs, so
+ # we correlate by `run_id` which is present on every callback.
+ self._run_to_call: dict[
+ UUID, tuple[tuple[str, ...], str, Token[ToolCallWriter | None]]
+ ] = {}
+
+ def _ns_for_emit(
+ self,
+ metadata: dict[str, Any] | None,
+ tags: list[str] | None,
+ ) -> tuple[str, ...] | None:
+ """Resolve the namespace this tool call should emit at, or `None` to skip.
+
+ Mirrors `StreamMessagesHandler.on_chat_model_start`'s namespace
+ derivation: parses `langgraph_checkpoint_ns` (which ends with
+ the `node_name:task_id` of the calling node), drops that
+ trailing segment, and returns the containing subgraph's own
+ namespace. Returns `None` when the call should be silently
+ suppressed:
+
+ - `metadata` is missing — handler is attached to a context
+ without Pregel routing info.
+ - `TAG_NOSTREAM` is in `tags` — caller explicitly opted out.
+ - Tool runs in a subgraph (`len(ns) > 0`) and the handler was
+ attached with `subgraphs=False` and a different `parent_ns`
+ than the call's containing subgraph.
+ """
+ if not metadata:
+ return None
+ if tags and TAG_NOSTREAM in tags:
+ return None
+ nskey = metadata.get("langgraph_checkpoint_ns")
+ if not nskey:
+ ns: tuple[str, ...] = ()
+ else:
+ ns = tuple(cast(str, nskey).split(NS_SEP))[:-1]
+ if not self.subgraphs and len(ns) > 0 and ns != self.parent_ns:
+ return None
+ return ns
+
+ def _start(
+ self,
+ serialized: dict[str, Any] | None,
+ input_str: str,
+ *,
+ run_id: UUID,
+ metadata: dict[str, Any] | None,
+ tags: list[str] | None,
+ inputs: dict[str, Any] | None,
+ kwargs: dict[str, Any],
+ ) -> None:
+ ns = self._ns_for_emit(metadata, tags)
+ if ns is None:
+ return
+ tool_call_id = cast("str | None", kwargs.get("tool_call_id")) or str(run_id)
+ tool_name = (
+ (serialized or {}).get("name")
+ or cast("str | None", kwargs.get("name"))
+ or ""
+ )
+
+ def writer(delta: Any) -> None:
+ self.stream(
+ (
+ ns,
+ "tools",
+ {
+ "event": "tool-output-delta",
+ "tool_call_id": tool_call_id,
+ "delta": delta,
+ },
+ )
+ )
+
+ token = _tool_call_writer.set(writer)
+ self._run_to_call[run_id] = (ns, tool_call_id, token)
+
+ payload: dict[str, Any] = {
+ "event": "tool-started",
+ "tool_call_id": tool_call_id,
+ "tool_name": tool_name,
+ }
+ if inputs is not None:
+ payload["input"] = inputs
+ self.stream((ns, "tools", payload))
+
+ def _end(self, output: Any, *, run_id: UUID) -> None:
+ info = self._run_to_call.pop(run_id, None)
+ if info is None:
+ return
+ ns, tool_call_id, token = info
+ self._reset_writer(token)
+ self.stream(
+ (
+ ns,
+ "tools",
+ {
+ "event": "tool-finished",
+ "tool_call_id": tool_call_id,
+ "output": output,
+ },
+ )
+ )
+
+ def _error(self, error: BaseException, *, run_id: UUID) -> None:
+ info = self._run_to_call.pop(run_id, None)
+ if info is None:
+ return
+ ns, tool_call_id, token = info
+ self._reset_writer(token)
+ self.stream(
+ (
+ ns,
+ "tools",
+ {
+ "event": "tool-error",
+ "tool_call_id": tool_call_id,
+ "message": str(error),
+ },
+ )
+ )
+
+ def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Pass-through — required by the `_StreamingCallbackHandler` protocol."""
+ return output
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Pass-through — sync counterpart to `tap_output_aiter`."""
+ return output
+
+ @staticmethod
+ def _reset_writer(token: Token[ToolCallWriter | None]) -> None:
+ # Token is invalid if `on_tool_end` runs in a different context
+ # than `on_tool_start` (e.g. langchain may hand off to a thread
+ # worker without copying the context). Swallow that case; the
+ # ContextVar lifetime is bounded by the enclosing task anyway.
+ try:
+ _tool_call_writer.reset(token)
+ except ValueError:
+ pass
+
+ # ------------------------------------------------------------------
+ # Sync callbacks
+ # ------------------------------------------------------------------
+
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._start(
+ serialized,
+ input_str,
+ run_id=run_id,
+ metadata=metadata,
+ tags=tags,
+ inputs=inputs,
+ kwargs=kwargs,
+ )
+
+ def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._end(output, run_id=run_id)
+
+ def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._error(error, run_id=run_id)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7f91e08b61cd38b61de518928ca5f89b3c5f35d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_utils.py
@@ -0,0 +1,291 @@
+from __future__ import annotations
+
+import ast
+import inspect
+import re
+import textwrap
+from collections.abc import Callable, Sequence
+from functools import partial
+from typing import Any
+
+from langchain_core.runnables import (
+ Runnable,
+ RunnableLambda,
+ RunnableParallel,
+ RunnableSequence,
+)
+from langchain_core.runnables.base import RunnableBindingBase
+from langchain_core.runnables.config import run_in_executor
+from langgraph.checkpoint.base import ChannelVersions
+from typing_extensions import override
+
+from langgraph._internal._runnable import RunnableCallable, RunnableSeq
+from langgraph._internal._timeout import sync_timeout_unsupported
+from langgraph.pregel.protocol import PregelProtocol
+
+_SEQUENCE_TYPES = (RunnableSeq, RunnableSequence)
+
+
+def get_new_channel_versions(
+ previous_versions: ChannelVersions, current_versions: ChannelVersions
+) -> ChannelVersions:
+ """Get subset of current_versions that are newer than previous_versions."""
+ if previous_versions:
+ version_type = type(next(iter(current_versions.values()), None))
+ null_version = version_type() # type: ignore[misc]
+ new_versions = {
+ k: v
+ for k, v in current_versions.items()
+ if v > previous_versions.get(k, null_version) # type: ignore[operator]
+ }
+ else:
+ new_versions = current_versions
+
+ return new_versions
+
+
+def find_subgraph_pregel(candidate: Runnable) -> PregelProtocol | None:
+ from langgraph.pregel import Pregel
+
+ candidates: list[Runnable] = [candidate]
+
+ for c in candidates:
+ if (
+ isinstance(c, PregelProtocol)
+ # subgraphs that disabled checkpointing are not considered
+ and (not isinstance(c, Pregel) or c.checkpointer is not False)
+ ):
+ return c
+ elif isinstance(c, RunnableSequence) or isinstance(c, RunnableSeq):
+ candidates.extend(c.steps)
+ elif isinstance(c, RunnableLambda):
+ candidates.extend(c.deps)
+ elif isinstance(c, RunnableCallable):
+ if c.func is not None:
+ candidates.extend(
+ nl.__self__ if hasattr(nl, "__self__") else nl
+ for nl in get_function_nonlocals(c.func)
+ )
+ elif c.afunc is not None:
+ candidates.extend(
+ nl.__self__ if hasattr(nl, "__self__") else nl
+ for nl in get_function_nonlocals(c.afunc)
+ )
+
+ return None
+
+
+def _sequence_steps(runnable: Runnable) -> Sequence[Runnable] | None:
+ if isinstance(runnable, _SEQUENCE_TYPES):
+ return runnable.steps
+ return None
+
+
+def _parallel_steps(runnable: Runnable) -> Sequence[Runnable] | None:
+ if isinstance(runnable, RunnableParallel):
+ return tuple(runnable.steps__.values())
+ return None
+
+
+def _has_method_override(runnable: Runnable, method_name: str) -> bool:
+ method = getattr(type(runnable), method_name, None)
+ return method is not None and method is not getattr(Runnable, method_name)
+
+
+def _is_executor_backed_afunc(afunc: Callable[..., Any] | None) -> bool:
+ return isinstance(afunc, partial) and afunc.func is run_in_executor
+
+
+def _has_native_async(runnable: Runnable) -> bool:
+ if isinstance(runnable, RunnableCallable):
+ return runnable.afunc is not None and not _is_executor_backed_afunc(
+ runnable.afunc
+ )
+ if isinstance(runnable, RunnableLambda):
+ return bool(getattr(runnable, "afunc", False))
+ return _has_method_override(runnable, "ainvoke")
+
+
+def _runnable_has_native_async(runnable: Runnable) -> bool:
+ """Return whether a runnable can be idle-timed without known sync code.
+
+ For custom runnable subclasses, an `ainvoke` override is treated as the
+ async contract. We do not introspect whether that implementation delegates
+ to blocking work internally — e.g. a subclass whose `ainvoke` calls
+ `asyncio.to_thread(self.invoke, ...)` will pass this check but the wrapped
+ sync work is still uncancellable. Idle-timeout enforcement on such a
+ runnable will fire `NodeTimeoutError` correctly, but the background thread
+ will keep running until its sync work returns.
+ """
+
+ while isinstance(runnable, RunnableBindingBase):
+ runnable = runnable.bound
+ steps = _sequence_steps(runnable)
+ if steps is None:
+ steps = _parallel_steps(runnable)
+ if steps is not None:
+ return all(_runnable_has_native_async(step) for step in steps)
+ # Raw callables and the common composition wrappers created by graph
+ # builders fall through here. We do not exhaustively unwrap every Runnable
+ # wrapper — wrappers that provide `ainvoke` are treated as owning the async
+ # contract.
+ return _has_native_async(runnable)
+
+
+def validate_timeout_supported(runnable: Runnable, *, name: str) -> None:
+ if not _runnable_has_native_async(runnable):
+ raise sync_timeout_unsupported(name)
+
+
+def get_function_nonlocals(func: Callable) -> list[Any]:
+ """Get the nonlocal variables accessed by a function.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ List[Any]: The nonlocal variables accessed by the function.
+ """
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = FunctionNonLocals()
+ visitor.visit(tree)
+ values: list[Any] = []
+ closure = (
+ inspect.getclosurevars(func.__wrapped__)
+ if hasattr(func, "__wrapped__") and callable(func.__wrapped__)
+ else inspect.getclosurevars(func)
+ )
+ candidates = {**closure.globals, **closure.nonlocals}
+ for k, v in candidates.items():
+ if k in visitor.nonlocals:
+ values.append(v)
+ for kk in visitor.nonlocals:
+ if "." in kk and kk.startswith(k):
+ vv = v
+ for part in kk.split(".")[1:]:
+ if vv is None:
+ break
+ else:
+ try:
+ vv = getattr(vv, part)
+ except AttributeError:
+ break
+ else:
+ values.append(vv)
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return []
+
+ return values
+
+
+class FunctionNonLocals(ast.NodeVisitor):
+ """Get the nonlocal variables accessed of a function."""
+
+ def __init__(self) -> None:
+ self.nonlocals: set[str] = set()
+
+ @override
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
+ """Visit a function definition.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any:
+ """Visit an async function definition.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> Any:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+
+class NonLocals(ast.NodeVisitor):
+ """Get nonlocal variables accessed."""
+
+ def __init__(self) -> None:
+ self.loads: set[str] = set()
+ self.stores: set[str] = set()
+
+ @override
+ def visit_Name(self, node: ast.Name) -> Any:
+ """Visit a name node.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ self.loads.add(node.id)
+ elif isinstance(node.ctx, ast.Store):
+ self.stores.add(node.id)
+
+ @override
+ def visit_Attribute(self, node: ast.Attribute) -> Any:
+ """Visit an attribute node.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ parent = node.value
+ attr_expr = node.attr
+ while isinstance(parent, ast.Attribute):
+ attr_expr = parent.attr + "." + attr_expr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+ self.loads.discard(parent.id)
+ elif isinstance(parent, ast.Call):
+ if isinstance(parent.func, ast.Name):
+ self.loads.add(parent.func.id)
+ else:
+ parent = parent.func
+ attr_expr = ""
+ while isinstance(parent, ast.Attribute):
+ if attr_expr:
+ attr_expr = parent.attr + "." + attr_expr
+ else:
+ attr_expr = parent.attr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+
+
+def is_xxh3_128_hexdigest(value: str) -> bool:
+ """Check if the given string matches the format of xxh3_128_hexdigest."""
+ return bool(re.fullmatch(r"[0-9a-f]{32}", value))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_write.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_write.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b4508257653e54c94cb2360bd32de91bb161bfd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/_write.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+from collections.abc import Callable, Sequence
+from typing import (
+ Any,
+ NamedTuple,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.runnables import Runnable, RunnableConfig
+
+from langgraph._internal._constants import CONF, CONFIG_KEY_SEND, TASKS
+from langgraph._internal._runnable import RunnableCallable
+from langgraph._internal._typing import MISSING
+from langgraph.errors import InvalidUpdateError
+from langgraph.types import Send
+
+TYPE_SEND = Callable[[Sequence[tuple[str, Any]]], None]
+R = TypeVar("R", bound=Runnable)
+
+SKIP_WRITE = object()
+PASSTHROUGH = object()
+
+
+class ChannelWriteEntry(NamedTuple):
+ channel: str
+ """Channel name to write to."""
+ value: Any = PASSTHROUGH
+ """Value to write, or PASSTHROUGH to use the input."""
+ skip_none: bool = False
+ """Whether to skip writing if the value is None."""
+ mapper: Callable | None = None
+ """Function to transform the value before writing."""
+
+
+class ChannelWriteTupleEntry(NamedTuple):
+ mapper: Callable[[Any], Sequence[tuple[str, Any]] | None]
+ """Function to extract tuples from value."""
+ value: Any = PASSTHROUGH
+ """Value to write, or PASSTHROUGH to use the input."""
+ static: Sequence[tuple[str, Any, str | None]] | None = None
+ """Optional, declared writes for static analysis."""
+
+
+class ChannelWrite(RunnableCallable):
+ """Implements the logic for sending writes to CONFIG_KEY_SEND.
+ Can be used as a runnable or as a static method to call imperatively."""
+
+ writes: list[ChannelWriteEntry | ChannelWriteTupleEntry | Send]
+ """Sequence of write entries or Send objects to write."""
+
+ def __init__(
+ self,
+ writes: Sequence[ChannelWriteEntry | ChannelWriteTupleEntry | Send],
+ *,
+ tags: Sequence[str] | None = None,
+ ):
+ super().__init__(
+ func=self._write,
+ afunc=self._awrite,
+ name=None,
+ tags=tags,
+ trace=False,
+ )
+ self.writes = cast(
+ list[ChannelWriteEntry | ChannelWriteTupleEntry | Send], writes
+ )
+
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ if not name:
+ name = f"ChannelWrite<{','.join(w.channel if isinstance(w, ChannelWriteEntry) else '...' if isinstance(w, ChannelWriteTupleEntry) else w.node for w in self.writes)}>"
+ return super().get_name(suffix, name=name)
+
+ def _write(self, input: Any, config: RunnableConfig) -> None:
+ writes = [
+ ChannelWriteEntry(write.channel, input, write.skip_none, write.mapper)
+ if isinstance(write, ChannelWriteEntry) and write.value is PASSTHROUGH
+ else ChannelWriteTupleEntry(write.mapper, input)
+ if isinstance(write, ChannelWriteTupleEntry) and write.value is PASSTHROUGH
+ else write
+ for write in self.writes
+ ]
+ self.do_write(
+ config,
+ writes,
+ )
+ return input
+
+ async def _awrite(self, input: Any, config: RunnableConfig) -> None:
+ writes = [
+ ChannelWriteEntry(write.channel, input, write.skip_none, write.mapper)
+ if isinstance(write, ChannelWriteEntry) and write.value is PASSTHROUGH
+ else ChannelWriteTupleEntry(write.mapper, input)
+ if isinstance(write, ChannelWriteTupleEntry) and write.value is PASSTHROUGH
+ else write
+ for write in self.writes
+ ]
+ self.do_write(
+ config,
+ writes,
+ )
+ return input
+
+ @staticmethod
+ def do_write(
+ config: RunnableConfig,
+ writes: Sequence[ChannelWriteEntry | ChannelWriteTupleEntry | Send],
+ allow_passthrough: bool = True,
+ ) -> None:
+ # validate
+ for w in writes:
+ if isinstance(w, ChannelWriteEntry):
+ if w.channel == TASKS:
+ raise InvalidUpdateError(
+ "Cannot write to the reserved channel TASKS"
+ )
+ if w.value is PASSTHROUGH and not allow_passthrough:
+ raise InvalidUpdateError("PASSTHROUGH value must be replaced")
+ if isinstance(w, ChannelWriteTupleEntry):
+ if w.value is PASSTHROUGH and not allow_passthrough:
+ raise InvalidUpdateError("PASSTHROUGH value must be replaced")
+ # if we want to persist writes found before hitting a ParentCommand
+ # can move this to a finally block
+ write: TYPE_SEND = config[CONF][CONFIG_KEY_SEND]
+ write(_assemble_writes(writes))
+
+ @staticmethod
+ def is_writer(runnable: Runnable) -> bool:
+ """Used by PregelNode to distinguish between writers and other runnables."""
+ return (
+ isinstance(runnable, ChannelWrite)
+ or getattr(runnable, "_is_channel_writer", MISSING) is not MISSING
+ )
+
+ @staticmethod
+ def get_static_writes(
+ runnable: Runnable,
+ ) -> Sequence[tuple[str, Any, str | None]] | None:
+ """Used to get conditional writes a writer declares for static analysis."""
+ if isinstance(runnable, ChannelWrite):
+ return [
+ w
+ for entry in runnable.writes
+ if isinstance(entry, ChannelWriteTupleEntry) and entry.static
+ for w in entry.static
+ ] or None
+ elif writes := getattr(runnable, "_is_channel_writer", MISSING):
+ if writes is not MISSING:
+ writes = cast(
+ Sequence[tuple[ChannelWriteEntry | Send, str | None]],
+ writes,
+ )
+ entries = [e for e, _ in writes]
+ labels = [la for _, la in writes]
+ return [(*t, la) for t, la in zip(_assemble_writes(entries), labels)]
+
+ @staticmethod
+ def register_writer(
+ runnable: R,
+ static: Sequence[tuple[ChannelWriteEntry | Send, str | None]] | None = None,
+ ) -> R:
+ """Used to mark a runnable as a writer, so that it can be detected by is_writer.
+ Instances of ChannelWrite are automatically marked as writers.
+ Optionally, a list of declared writes can be passed for static analysis."""
+ # using object.__setattr__ to work around objects that override __setattr__
+ # eg. pydantic models and dataclasses
+ object.__setattr__(runnable, "_is_channel_writer", static)
+ return runnable
+
+
+def _assemble_writes(
+ writes: Sequence[ChannelWriteEntry | ChannelWriteTupleEntry | Send],
+) -> list[tuple[str, Any]]:
+ """Assembles the writes into a list of tuples."""
+ tuples: list[tuple[str, Any]] = []
+ for w in writes:
+ if isinstance(w, Send):
+ tuples.append((TASKS, w))
+ elif isinstance(w, ChannelWriteTupleEntry):
+ if ww := w.mapper(w.value):
+ tuples.extend(ww)
+ elif isinstance(w, ChannelWriteEntry):
+ value = w.mapper(w.value) if w.mapper is not None else w.value
+ if value is SKIP_WRITE:
+ continue
+ if w.skip_none and value is None:
+ continue
+ tuples.append((w.channel, value))
+ else:
+ raise ValueError(f"Invalid write entry: {w}")
+ return tuples
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/debug.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/debug.py
new file mode 100644
index 0000000000000000000000000000000000000000..519a36488f8c4918efcf3cd3e032e957e23954c7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/debug.py
@@ -0,0 +1,279 @@
+from __future__ import annotations
+
+from collections.abc import Iterable, Iterator, Mapping, Sequence
+from dataclasses import asdict
+from typing import Any
+from uuid import UUID
+
+from langchain_core.runnables import RunnableConfig
+from langgraph.checkpoint.base import CheckpointMetadata, PendingWrite
+
+from langgraph._internal._config import patch_checkpoint_map
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CHECKPOINT_NS,
+ ERROR,
+ INTERRUPT,
+ NS_END,
+ NS_SEP,
+ RETURN,
+)
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel
+from langgraph.constants import TAG_HIDDEN
+from langgraph.pregel._io import read_channels
+from langgraph.types import (
+ CheckpointPayload,
+ PregelExecutableTask,
+ PregelTask,
+ StateSnapshot,
+ TaskPayload,
+ TaskResultPayload,
+)
+
+TASK_NAMESPACE = UUID("6ba7b831-9dad-11d1-80b4-00c04fd430c8")
+
+
+def map_debug_tasks(tasks: Iterable[PregelExecutableTask]) -> Iterator[TaskPayload]:
+ """Produce "task" events for stream_mode=debug."""
+ for task in tasks:
+ if task.config is not None and TAG_HIDDEN in task.config.get("tags", []):
+ continue
+
+ yield {
+ "id": task.id,
+ "name": task.name,
+ "input": task.input,
+ "triggers": task.triggers,
+ }
+
+
+def is_multiple_channel_write(value: Any) -> bool:
+ """Return True if the payload already wraps multiple writes from the same channel."""
+ return (
+ isinstance(value, dict)
+ and "$writes" in value
+ and isinstance(value["$writes"], list)
+ )
+
+
+def map_task_result_writes(writes: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ """Folds task writes into a result dict and aggregates multiple writes to the same channel.
+
+ If the channel contains a single write, we record the write in the result dict as `{channel: write}`
+ If the channel contains multiple writes, we record the writes in the result dict as `{channel: {'$writes': [write1, write2, ...]}}`"""
+
+ result: dict[str, Any] = {}
+ for channel, value in writes:
+ existing = result.get(channel)
+
+ if existing is not None:
+ channel_writes = (
+ existing["$writes"]
+ if is_multiple_channel_write(existing)
+ else [existing]
+ )
+ channel_writes.append(value)
+ result[channel] = {"$writes": channel_writes}
+ else:
+ result[channel] = value
+ return result
+
+
+def map_debug_task_results(
+ task_tup: tuple[PregelExecutableTask, Sequence[tuple[str, Any]]],
+ stream_keys: str | Sequence[str],
+) -> Iterator[TaskResultPayload]:
+ """Produce "task_result" events for stream_mode=debug."""
+ stream_channels_list = (
+ [stream_keys] if isinstance(stream_keys, str) else stream_keys
+ )
+ task, writes = task_tup
+ yield {
+ "id": task.id,
+ "name": task.name,
+ "error": next((w[1] for w in writes if w[0] == ERROR), None),
+ "result": map_task_result_writes(
+ [w for w in writes if w[0] in stream_channels_list or w[0] == RETURN]
+ ),
+ "interrupts": [
+ asdict(v)
+ for w in writes
+ if w[0] == INTERRUPT
+ for v in (w[1] if isinstance(w[1], Sequence) else [w[1]])
+ ],
+ }
+
+
+def rm_pregel_keys(config: RunnableConfig | None) -> RunnableConfig | None:
+ """Remove pregel-specific keys from the config."""
+ if config is None:
+ return config
+ return {
+ "configurable": {
+ k: v
+ for k, v in config.get("configurable", {}).items()
+ if not k.startswith("__pregel_")
+ }
+ }
+
+
+def map_debug_checkpoint(
+ config: RunnableConfig,
+ channels: Mapping[str, BaseChannel],
+ stream_channels: str | Sequence[str],
+ metadata: CheckpointMetadata,
+ tasks: Iterable[PregelExecutableTask],
+ pending_writes: list[PendingWrite],
+ parent_config: RunnableConfig | None,
+ output_keys: str | Sequence[str],
+) -> Iterator[CheckpointPayload]:
+ """Produce "checkpoint" events for stream_mode=debug."""
+
+ parent_ns = config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_states: dict[str, RunnableConfig | StateSnapshot] = {}
+
+ for task in tasks:
+ if not task.subgraphs:
+ continue
+
+ # assemble checkpoint_ns for this task
+ task_ns = f"{task.name}{NS_END}{task.id}"
+ if parent_ns:
+ task_ns = f"{parent_ns}{NS_SEP}{task_ns}"
+
+ # set config as signal that subgraph checkpoints exist
+ task_states[task.id] = {
+ CONF: {
+ "thread_id": config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+
+ yield {
+ "config": rm_pregel_keys(patch_checkpoint_map(config, metadata)),
+ "parent_config": rm_pregel_keys(patch_checkpoint_map(parent_config, metadata)),
+ "values": read_channels(channels, stream_channels),
+ "metadata": metadata,
+ "next": [t.name for t in tasks],
+ "tasks": [
+ {
+ "id": t.id,
+ "name": t.name,
+ "error": t.error,
+ "state": t.state,
+ }
+ if t.error
+ else {
+ "id": t.id,
+ "name": t.name,
+ "result": t.result,
+ "interrupts": tuple(asdict(i) for i in t.interrupts),
+ "state": t.state,
+ }
+ if t.result
+ else {
+ "id": t.id,
+ "name": t.name,
+ "interrupts": tuple(asdict(i) for i in t.interrupts),
+ "state": t.state,
+ }
+ for t in tasks_w_writes(tasks, pending_writes, task_states, output_keys)
+ ],
+ }
+
+
+def tasks_w_writes(
+ tasks: Iterable[PregelTask | PregelExecutableTask],
+ pending_writes: list[PendingWrite] | None,
+ states: dict[str, RunnableConfig | StateSnapshot] | None,
+ output_keys: str | Sequence[str],
+) -> tuple[PregelTask, ...]:
+ """Apply writes / subgraph states to tasks to be returned in a StateSnapshot."""
+ pending_writes = pending_writes or []
+ out: list[PregelTask] = []
+ for task in tasks:
+ rtn = next(
+ (
+ val
+ for tid, chan, val in pending_writes
+ if tid == task.id and chan == RETURN
+ ),
+ MISSING,
+ )
+ task_error = next(
+ (exc for tid, n, exc in pending_writes if tid == task.id and n == ERROR),
+ None,
+ )
+ task_interrupts = tuple(
+ v
+ for tid, n, vv in pending_writes
+ if tid == task.id and n == INTERRUPT
+ for v in (vv if isinstance(vv, Sequence) else [vv])
+ )
+
+ task_writes = [
+ (chan, val)
+ for tid, chan, val in pending_writes
+ if tid == task.id and chan not in (ERROR, INTERRUPT, RETURN)
+ ]
+
+ if rtn is not MISSING:
+ task_result = rtn
+ elif isinstance(output_keys, str):
+ # unwrap single channel writes to just the write value
+ filtered_writes = [
+ (chan, val) for chan, val in task_writes if chan == output_keys
+ ]
+ mapped_writes = map_task_result_writes(filtered_writes)
+ task_result = mapped_writes.get(str(output_keys)) if mapped_writes else None
+ else:
+ if isinstance(output_keys, str):
+ output_keys = [output_keys]
+ # map task result writes to the desired output channels
+ # repeateed writes to the same channel are aggregated into: {'$writes': [write1, write2, ...]}
+ filtered_writes = [
+ (chan, val) for chan, val in task_writes if chan in output_keys
+ ]
+ mapped_writes = map_task_result_writes(filtered_writes)
+ task_result = mapped_writes if filtered_writes else {}
+
+ has_writes = rtn is not MISSING or any(
+ w[0] == task.id and w[1] not in (ERROR, INTERRUPT) for w in pending_writes
+ )
+
+ out.append(
+ PregelTask(
+ task.id,
+ task.name,
+ task.path,
+ task_error,
+ task_interrupts,
+ states.get(task.id) if states else None,
+ task_result if has_writes else None,
+ )
+ )
+ return tuple(out)
+
+
+COLOR_MAPPING = {
+ "black": "0;30",
+ "red": "0;31",
+ "green": "0;32",
+ "yellow": "0;33",
+ "blue": "0;34",
+ "magenta": "0;35",
+ "cyan": "0;36",
+ "white": "0;37",
+ "gray": "1;30",
+}
+
+
+def get_colored_text(text: str, color: str) -> str:
+ """Get colored text."""
+ return f"\033[1;3{COLOR_MAPPING[color]}m{text}\033[0m"
+
+
+def get_bolded_text(text: str) -> str:
+ """Get bolded text."""
+ return f"\033[1m{text}\033[0m"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/main.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..1550e5a92390bd70cdff256f6c482020940548ed
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/main.py
@@ -0,0 +1,4314 @@
+from __future__ import annotations
+
+import asyncio
+import concurrent
+import concurrent.futures
+import contextlib
+import queue
+import warnings
+import weakref
+from collections import defaultdict, deque
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from dataclasses import is_dataclass, replace
+from datetime import timedelta
+from functools import partial
+from inspect import isclass
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ cast,
+ get_type_hints,
+ overload,
+)
+from uuid import UUID, uuid5
+
+from langchain_core._api import beta
+from langchain_core.globals import get_debug
+from langchain_core.runnables import (
+ RunnableSequence,
+)
+from langchain_core.runnables.base import Input, Output
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+)
+from langchain_core.runnables.graph import Graph
+from langchain_core.runnables.schema import StreamEvent
+from langgraph.cache.base import BaseCache
+from langgraph.checkpoint.base import (
+ BaseCheckpointSaver,
+ Checkpoint,
+ CheckpointTuple,
+)
+from langgraph.store.base import BaseStore
+from pydantic import BaseModel, TypeAdapter
+from typing_extensions import Self, Unpack, deprecated, is_typeddict
+
+from langgraph._internal import _serde
+from langgraph._internal._config import (
+ ensure_config,
+ merge_configs,
+ patch_checkpoint_map,
+ patch_config,
+ patch_configurable,
+ recast_checkpoint_ns,
+)
+from langgraph._internal._constants import (
+ CACHE_NS_WRITES,
+ CONF,
+ CONFIG_KEY_CACHE,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_CHECKPOINTER,
+ CONFIG_KEY_DURABILITY,
+ CONFIG_KEY_NODE_FINISHED,
+ CONFIG_KEY_READ,
+ CONFIG_KEY_RUNNER_SUBMIT,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SEND,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_STREAM_MESSAGES_V2,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ ERROR,
+ INPUT,
+ INTERRUPT,
+ NS_END,
+ NS_SEP,
+ NULL_TASK_ID,
+ PUSH,
+ TASKS,
+)
+from langgraph._internal._pydantic import create_model
+from langgraph._internal._queue import ( # type: ignore[attr-defined]
+ AsyncQueue,
+ SyncQueue,
+)
+from langgraph._internal._runnable import (
+ Runnable,
+ RunnableLike,
+ RunnableSeq,
+ coerce_to_runnable,
+)
+from langgraph._internal._timeout import coerce_timeout_policy
+from langgraph._internal._typing import MISSING, DeprecatedKwargs
+from langgraph.callbacks import (
+ GraphInterruptEvent,
+ GraphResumeEvent,
+ get_async_graph_callback_manager_for_config,
+ get_sync_graph_callback_manager_for_config,
+)
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.topic import Topic
+from langgraph.config import get_config
+from langgraph.constants import END
+from langgraph.errors import (
+ ErrorCode,
+ GraphDrained,
+ GraphRecursionError,
+ InvalidUpdateError,
+ create_error_message,
+)
+from langgraph.managed.base import ManagedValueSpec
+from langgraph.pregel._algo import (
+ PregelTaskWrites,
+ _scratchpad,
+ apply_writes,
+ local_read,
+ prepare_next_tasks,
+)
+from langgraph.pregel._call import identifier
+from langgraph.pregel._checkpoint import (
+ achannels_from_checkpoint,
+ channels_from_checkpoint,
+ copy_checkpoint,
+ create_checkpoint,
+ empty_checkpoint,
+)
+from langgraph.pregel._draw import draw_graph
+from langgraph.pregel._io import map_input, read_channels
+from langgraph.pregel._loop import (
+ AsyncPregelLoop,
+ SyncPregelLoop,
+)
+from langgraph.pregel._messages import (
+ StreamMessagesHandler,
+ StreamMessagesHandlerV2,
+)
+from langgraph.pregel._read import DEFAULT_BOUND, PregelNode
+from langgraph.pregel._retry import RetryPolicy
+from langgraph.pregel._runner import PregelRunner
+from langgraph.pregel._tools import StreamToolCallHandler
+from langgraph.pregel._utils import (
+ get_new_channel_versions,
+ validate_timeout_supported,
+)
+from langgraph.pregel._validate import validate_graph, validate_keys
+from langgraph.pregel._write import ChannelWrite, ChannelWriteEntry
+from langgraph.pregel.debug import get_bolded_text, get_colored_text, tasks_w_writes
+from langgraph.pregel.protocol import PregelProtocol, StreamChunk, StreamProtocol
+from langgraph.runtime import (
+ DEFAULT_RUNTIME,
+ BaseUser,
+ RunControl,
+ Runtime,
+ ServerInfo,
+)
+from langgraph.stream._mux import StreamMux
+from langgraph.stream._types import StreamTransformer
+from langgraph.stream.run_stream import AsyncGraphRunStream, GraphRunStream
+from langgraph.stream.transformers import (
+ LifecycleTransformer,
+ MessagesTransformer,
+ SubgraphTransformer,
+ ValuesTransformer,
+)
+from langgraph.types import (
+ All,
+ CachePolicy,
+ Checkpointer,
+ Command,
+ Durability,
+ GraphOutput,
+ Interrupt,
+ Send,
+ StateSnapshot,
+ StateUpdate,
+ StreamMode,
+ StreamPart,
+ TimeoutPolicy,
+ ensure_valid_checkpointer,
+)
+from langgraph.typing import ContextT, InputT, OutputT, StateT
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+
+try:
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
+except ImportError:
+ _StreamingCallbackHandler = None # type: ignore
+
+__all__ = ("NodeBuilder", "Pregel")
+
+_WriteValue = Callable[[Input], Output] | Any
+
+
+class NodeBuilder:
+ __slots__ = (
+ "_channels",
+ "_triggers",
+ "_tags",
+ "_metadata",
+ "_writes",
+ "_bound",
+ "_retry_policy",
+ "_cache_policy",
+ "_timeout",
+ )
+
+ _channels: str | list[str]
+ _triggers: list[str]
+ _tags: list[str]
+ _metadata: dict[str, Any]
+ _writes: list[ChannelWriteEntry]
+ _bound: Runnable
+ _retry_policy: list[RetryPolicy]
+ _cache_policy: CachePolicy | None
+ _timeout: TimeoutPolicy | None
+
+ def __init__(
+ self,
+ ) -> None:
+ self._channels = []
+ self._triggers = []
+ self._tags = []
+ self._metadata = {}
+ self._writes = []
+ self._bound = DEFAULT_BOUND
+ self._retry_policy = []
+ self._cache_policy = None
+ self._timeout = None
+
+ def subscribe_only(
+ self,
+ channel: str,
+ ) -> Self:
+ """Subscribe to a single channel."""
+ if not self._channels:
+ self._channels = channel
+ else:
+ raise ValueError(
+ "Cannot subscribe to single channels when other channels are already subscribed to"
+ )
+
+ self._triggers.append(channel)
+
+ return self
+
+ def subscribe_to(
+ self,
+ *channels: str,
+ read: bool = True,
+ ) -> Self:
+ """Add channels to subscribe to.
+
+ Node will be invoked when any of these channels are updated, with a dict of the
+ channel values as input.
+
+ Args:
+ channels: Channel name(s) to subscribe to
+ read: If `True`, the channels will be included in the input to the node.
+ Otherwise, they will trigger the node without being sent in input.
+
+ Returns:
+ Self for chaining
+ """
+ if isinstance(self._channels, str):
+ raise ValueError(
+ "Cannot subscribe to channels when subscribed to a single channel"
+ )
+ if read:
+ if not self._channels:
+ self._channels = list(channels)
+ else:
+ self._channels.extend(channels)
+
+ if isinstance(channels, str):
+ self._triggers.append(channels)
+ else:
+ self._triggers.extend(channels)
+
+ return self
+
+ def read_from(
+ self,
+ *channels: str,
+ ) -> Self:
+ """Adds the specified channels to read from, without subscribing to them."""
+ assert isinstance(self._channels, list), (
+ "Cannot read additional channels when subscribed to single channels"
+ )
+ self._channels.extend(channels)
+ return self
+
+ def do(
+ self,
+ node: RunnableLike,
+ ) -> Self:
+ """Adds the specified node."""
+ if self._bound is not DEFAULT_BOUND:
+ self._bound = RunnableSeq(
+ self._bound, coerce_to_runnable(node, name=None, trace=True)
+ )
+ else:
+ self._bound = coerce_to_runnable(node, name=None, trace=True)
+ return self
+
+ def write_to(
+ self,
+ *channels: str | ChannelWriteEntry,
+ **kwargs: _WriteValue,
+ ) -> Self:
+ """Add channel writes.
+
+ Args:
+ *channels: Channel names to write to.
+ **kwargs: Channel name and value mappings.
+
+ Returns:
+ Self for chaining
+ """
+ self._writes.extend(
+ ChannelWriteEntry(c) if isinstance(c, str) else c for c in channels
+ )
+ self._writes.extend(
+ ChannelWriteEntry(k, mapper=v)
+ if callable(v)
+ else ChannelWriteEntry(k, value=v)
+ for k, v in kwargs.items()
+ )
+
+ return self
+
+ def meta(self, *tags: str, **metadata: Any) -> Self:
+ """Add tags or metadata to the node."""
+ self._tags.extend(tags)
+ self._metadata.update(metadata)
+ return self
+
+ def add_retry_policies(self, *policies: RetryPolicy) -> Self:
+ """Adds retry policies to the node."""
+ self._retry_policy.extend(policies)
+ return self
+
+ def add_cache_policy(self, policy: CachePolicy) -> Self:
+ """Adds cache policies to the node."""
+ self._cache_policy = policy
+ return self
+
+ def set_timeout(self, timeout: float | timedelta | TimeoutPolicy | None) -> Self:
+ """Set the per-attempt timeout policy for this node."""
+ self._timeout = coerce_timeout_policy(timeout)
+ return self
+
+ def build(self) -> PregelNode:
+ """Builds the node."""
+ return PregelNode(
+ channels=self._channels,
+ triggers=self._triggers,
+ tags=self._tags,
+ metadata=self._metadata,
+ writers=[ChannelWrite(self._writes)],
+ bound=self._bound,
+ retry_policy=self._retry_policy,
+ cache_policy=self._cache_policy,
+ timeout=self._timeout,
+ )
+
+
+# Kwargs that ``stream_events(version="v3")`` / ``astream_events(version="v3")``
+# manage internally and must not be overridden by callers. ``stream_mode`` is
+# derived from the transformer mux; ``subgraphs`` is forced True so nested
+# namespaces flow through scoped muxes. Forwarding either to the inner
+# ``stream(...)`` would silently break v3's invariants, so we raise instead.
+_V3_INVARIANT_KWARGS: tuple[str, ...] = ("stream_mode", "subgraphs")
+
+
+def _reject_v3_invariant_kwargs(kwargs: dict[str, Any]) -> None:
+ collisions = [k for k in _V3_INVARIANT_KWARGS if k in kwargs]
+ if collisions:
+ raise TypeError(
+ "stream_events(version='v3') / astream_events(version='v3') do "
+ f"not accept {', '.join(collisions)}; v3 owns these "
+ "(stream_mode is built from the transformer mux, subgraphs is "
+ "forced True so nested namespaces flow through scoped muxes)."
+ )
+
+
+def _collect_stream_modes(mux: Any) -> list[StreamMode]:
+ """Return the union of `required_stream_modes` across registered transformers.
+
+ Transformers declare the stream modes they need to function, and
+ `stream_events(version="v3")` asks the graph for exactly that union — no hardcoded
+ default set. If zero transformers declare a given mode, the graph
+ does not stream events for it.
+ """
+ modes: set[StreamMode] = set()
+ for transformer in mux._transformers:
+ modes.update(
+ cast(
+ "tuple[StreamMode, ...]",
+ getattr(transformer, "required_stream_modes", ()),
+ )
+ )
+ return list(modes)
+
+
+def _normalize_stream_transformer_factories(
+ specs: Sequence[Callable[[tuple[str, ...]], Any]] | None,
+) -> list[Callable[[tuple[str, ...]], Any]]:
+ """Normalize stream transformer specs to scoped factories.
+
+ A stream transformer spec is a callable that accepts
+ `scope: tuple[str, ...]` and returns a fresh `StreamTransformer`.
+ Transformer classes work when their constructor follows the same
+ shape. Pre-built instances are rejected because they cannot be
+ cloned into subgraph scopes.
+ """
+ factories: list[Callable[[tuple[str, ...]], Any]] = []
+ for spec in specs or ():
+ if isinstance(spec, StreamTransformer):
+ raise TypeError(
+ "stream_events(version='v3') transformers must be scope-aware callables, "
+ f"got pre-built instance {type(spec).__name__}. Pass the "
+ "transformer class or a factory like "
+ "`lambda scope: MyTransformer(scope, ...)`."
+ )
+ if not callable(spec):
+ raise TypeError(
+ "stream_events(version='v3') transformers must be scope-aware callables, "
+ f"got {type(spec).__name__}."
+ )
+
+ def factory(scope: tuple[str, ...], _spec: Callable[..., Any] = spec) -> Any:
+ return _spec(scope)
+
+ factories.append(factory)
+ return factories
+
+
+class Pregel(
+ PregelProtocol[StateT, ContextT, InputT, OutputT],
+ Generic[StateT, ContextT, InputT, OutputT],
+):
+ """Pregel manages the runtime behavior for LangGraph applications.
+
+ ## Overview
+
+ Pregel combines [**actors**](https://en.wikipedia.org/wiki/Actor_model)
+ and **channels** into a single application.
+ **Actors** read data from channels and write data to channels.
+ Pregel organizes the execution of the application into multiple steps,
+ following the **Pregel Algorithm**/**Bulk Synchronous Parallel** model.
+
+ Each step consists of three phases:
+
+ - **Plan**: Determine which **actors** to execute in this step. For example,
+ in the first step, select the **actors** that subscribe to the special
+ **input** channels; in subsequent steps,
+ select the **actors** that subscribe to channels updated in the previous step.
+ - **Execution**: Execute all selected **actors** in parallel,
+ until all complete, or one fails, or a timeout is reached. During this
+ phase, channel updates are invisible to actors until the next step.
+ - **Update**: Update the channels with the values written by the **actors**
+ in this step.
+
+ Repeat until no **actors** are selected for execution, or a maximum number of
+ steps is reached.
+
+ ## Actors
+
+ An **actor** is a `PregelNode`.
+ It subscribes to channels, reads data from them, and writes data to them.
+ It can be thought of as an **actor** in the Pregel algorithm.
+ `PregelNodes` implement LangChain's
+ Runnable interface.
+
+ ## Channels
+
+ Channels are used to communicate between actors (`PregelNodes`).
+ Each channel has a value type, an update type, and an update function – which
+ takes a sequence of updates and
+ modifies the stored value. Channels can be used to send data from one chain to
+ another, or to send data from a chain to itself in a future step. LangGraph
+ provides a number of built-in channels:
+
+ ### Basic channels: LastValue and Topic
+
+ - `LastValue`: The default channel, stores the last value sent to the channel,
+ useful for input and output values, or for sending data from one step to the next
+ - `Topic`: A configurable PubSub Topic, useful for sending multiple values
+ between *actors*, or for accumulating output. Can be configured to deduplicate
+ values, and/or to accumulate values over the course of multiple steps.
+
+ ### Advanced channels: Context and BinaryOperatorAggregate
+
+ - `Context`: exposes the value of a context manager, managing its lifecycle.
+ Useful for accessing external resources that require setup and/or teardown. e.g.
+ `client = Context(httpx.Client)`
+ - `BinaryOperatorAggregate`: stores a persistent value, updated by applying
+ a binary operator to the current value and each update
+ sent to the channel, useful for computing aggregates over multiple steps. e.g.
+ `total = BinaryOperatorAggregate(int, operator.add)`
+
+ ## Examples
+
+ Most users will interact with Pregel via a
+ [StateGraph (Graph API)][langgraph.graph.StateGraph] or via an
+ [entrypoint (Functional API)][langgraph.func.entrypoint].
+
+ However, for **advanced** use cases, Pregel can be used directly. If you're
+ not sure whether you need to use Pregel directly, then the answer is probably no
+ - you should use the Graph API or Functional API instead. These are higher-level
+ interfaces that will compile down to Pregel under the hood.
+
+ Here are some examples to give you a sense of how it works:
+
+ Example: Single node application
+ ```python
+ from langgraph.channels import EphemeralValue
+ from langgraph.pregel import Pregel, NodeBuilder
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b")
+ )
+
+ app = Pregel(
+ nodes={"node1": node1},
+ channels={
+ "a": EphemeralValue(str),
+ "b": EphemeralValue(str),
+ },
+ input_channels=["a"],
+ output_channels=["b"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```con
+ {'b': 'foofoo'}
+ ```
+
+ Example: Using multiple nodes and multiple output channels
+ ```python
+ from langgraph.channels import LastValue, EphemeralValue
+ from langgraph.pregel import Pregel, NodeBuilder
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b")
+ )
+
+ node2 = (
+ NodeBuilder().subscribe_to("b")
+ .do(lambda x: x["b"] + x["b"])
+ .write_to("c")
+ )
+
+
+ app = Pregel(
+ nodes={"node1": node1, "node2": node2},
+ channels={
+ "a": EphemeralValue(str),
+ "b": LastValue(str),
+ "c": EphemeralValue(str),
+ },
+ input_channels=["a"],
+ output_channels=["b", "c"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```con
+ {'b': 'foofoo', 'c': 'foofoofoofoo'}
+ ```
+
+ Example: Using a Topic channel
+ ```python
+ from langgraph.channels import LastValue, EphemeralValue, Topic
+ from langgraph.pregel import Pregel, NodeBuilder
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b", "c")
+ )
+
+ node2 = (
+ NodeBuilder().subscribe_only("b")
+ .do(lambda x: x + x)
+ .write_to("c")
+ )
+
+
+ app = Pregel(
+ nodes={"node1": node1, "node2": node2},
+ channels={
+ "a": EphemeralValue(str),
+ "b": EphemeralValue(str),
+ "c": Topic(str, accumulate=True),
+ },
+ input_channels=["a"],
+ output_channels=["c"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```pycon
+ {"c": ["foofoo", "foofoofoofoo"]}
+ ```
+
+ Example: Using a `BinaryOperatorAggregate` channel
+ ```python
+ from langgraph.channels import EphemeralValue, BinaryOperatorAggregate
+ from langgraph.pregel import Pregel, NodeBuilder
+
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b", "c")
+ )
+
+ node2 = (
+ NodeBuilder().subscribe_only("b")
+ .do(lambda x: x + x)
+ .write_to("c")
+ )
+
+
+ def reducer(current, update):
+ if current:
+ return current + " | " + update
+ else:
+ return update
+
+
+ app = Pregel(
+ nodes={"node1": node1, "node2": node2},
+ channels={
+ "a": EphemeralValue(str),
+ "b": EphemeralValue(str),
+ "c": BinaryOperatorAggregate(str, operator=reducer),
+ },
+ input_channels=["a"],
+ output_channels=["c"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```con
+ {'c': 'foofoo | foofoofoofoo'}
+ ```
+
+ Example: Introducing a cycle
+ This example demonstrates how to introduce a cycle in the graph, by having
+ a chain write to a channel it subscribes to.
+
+ Execution will continue until a `None` value is written to the channel.
+
+ ```python
+ from langgraph.channels import EphemeralValue
+ from langgraph.pregel import Pregel, NodeBuilder, ChannelWriteEntry
+
+ example_node = (
+ NodeBuilder()
+ .subscribe_only("value")
+ .do(lambda x: x + x if len(x) < 10 else None)
+ .write_to(ChannelWriteEntry(channel="value", skip_none=True))
+ )
+
+ app = Pregel(
+ nodes={"example_node": example_node},
+ channels={
+ "value": EphemeralValue(str),
+ },
+ input_channels=["value"],
+ output_channels=["value"],
+ )
+
+ app.invoke({"value": "a"})
+ ```
+
+ ```con
+ {'value': 'aaaaaaaaaaaaaaaa'}
+ ```
+ """
+
+ nodes: dict[str, PregelNode]
+
+ channels: dict[str, BaseChannel | ManagedValueSpec]
+
+ stream_mode: StreamMode = "values"
+ """Mode to stream output, defaults to 'values'."""
+
+ stream_eager: bool = False
+ """Whether to force emitting stream events eagerly, automatically turned on
+ for stream_mode "messages" and "custom"."""
+
+ output_channels: str | Sequence[str]
+
+ stream_channels: str | Sequence[str] | None = None
+ """Channels to stream, defaults to all channels not in reserved channels"""
+
+ interrupt_after_nodes: All | Sequence[str]
+
+ interrupt_before_nodes: All | Sequence[str]
+
+ input_channels: str | Sequence[str]
+
+ step_timeout: float | None = None
+ """Maximum time to wait for a step to complete, in seconds."""
+
+ debug: bool
+ """Whether to print debug information during execution."""
+
+ checkpointer: Checkpointer = None
+ """`Checkpointer` used to save and load graph state."""
+
+ store: BaseStore | None = None
+ """Memory store to use for SharedValues."""
+
+ cache: BaseCache | None = None
+ """Cache to use for storing node results."""
+
+ retry_policy: Sequence[RetryPolicy] = ()
+ """Retry policies to use when running tasks. Empty set disables retries."""
+
+ cache_policy: CachePolicy | None = None
+ """Cache policy to use for all nodes. Can be overridden by individual nodes."""
+
+ context_schema: type[ContextT] | None = None
+ """Specifies the schema for the context object that will be passed to the workflow."""
+
+ config: RunnableConfig | None = None
+
+ name: str = "LangGraph"
+
+ trigger_to_nodes: Mapping[str, Sequence[str]]
+ node_error_handler_map: Mapping[str, str]
+
+ def __init__(
+ self,
+ *,
+ nodes: dict[str, PregelNode | NodeBuilder],
+ channels: dict[str, BaseChannel | ManagedValueSpec] | None,
+ auto_validate: bool = True,
+ stream_mode: StreamMode = "values",
+ stream_eager: bool = False,
+ output_channels: str | Sequence[str],
+ stream_channels: str | Sequence[str] | None = None,
+ interrupt_after_nodes: All | Sequence[str] = (),
+ interrupt_before_nodes: All | Sequence[str] = (),
+ input_channels: str | Sequence[str],
+ step_timeout: float | None = None,
+ debug: bool | None = None,
+ checkpointer: Checkpointer = None,
+ store: BaseStore | None = None,
+ cache: BaseCache | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ context_schema: type[ContextT] | None = None,
+ config: RunnableConfig | None = None,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ node_error_handler_map: Mapping[str, str] | None = None,
+ name: str = "LangGraph",
+ stream_transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **deprecated_kwargs: Unpack[DeprecatedKwargs],
+ ) -> None:
+ if (
+ config_type := deprecated_kwargs.get("config_type", MISSING)
+ ) is not MISSING:
+ warnings.warn(
+ "`config_type` is deprecated and will be removed. Please use `context_schema` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+
+ if context_schema is None:
+ context_schema = cast(type[ContextT], config_type)
+
+ checkpointer = ensure_valid_checkpointer(checkpointer)
+
+ self.nodes = {
+ k: v.build() if isinstance(v, NodeBuilder) else v for k, v in nodes.items()
+ }
+ self.channels = channels or {}
+ if TASKS in self.channels and not isinstance(self.channels[TASKS], Topic):
+ raise ValueError(
+ f"Channel '{TASKS}' is reserved and cannot be used in the graph."
+ )
+ else:
+ self.channels[TASKS] = Topic(Send, accumulate=False)
+ self.stream_mode = stream_mode
+ self.stream_eager = stream_eager
+ self.output_channels = output_channels
+ self.stream_channels = stream_channels
+ self.interrupt_after_nodes = interrupt_after_nodes
+ self.interrupt_before_nodes = interrupt_before_nodes
+ self.input_channels = input_channels
+ self.step_timeout = step_timeout
+ self.debug = debug if debug is not None else get_debug()
+ self.checkpointer = checkpointer
+ self.store = store
+ self.cache = cache
+ self.retry_policy = (
+ (retry_policy,) if isinstance(retry_policy, RetryPolicy) else retry_policy
+ )
+ self.cache_policy = cache_policy
+ self.context_schema = context_schema
+ self.config = config
+ self.trigger_to_nodes = trigger_to_nodes or {}
+ self.node_error_handler_map = node_error_handler_map or {}
+ self.name = name
+ self.stream_transformers: tuple[Callable[[tuple[str, ...]], Any], ...] = tuple(
+ stream_transformers or ()
+ )
+ self._serde_allowlist: set[tuple[str, ...]] | None = None
+ if auto_validate:
+ self.validate()
+
+ def _apply_checkpointer_allowlist(
+ self, checkpointer: BaseCheckpointSaver | None
+ ) -> BaseCheckpointSaver | None:
+ if not _serde.STRICT_MSGPACK_ENABLED:
+ return checkpointer
+ return _serde.apply_checkpointer_allowlist(checkpointer, self._serde_allowlist)
+
+ def get_graph(
+ self, config: RunnableConfig | None = None, *, xray: int | bool = False
+ ) -> Graph:
+ """Return a drawable representation of the computation graph."""
+ # gather subgraphs
+ if xray:
+ subgraphs = {
+ k: v.get_graph(
+ config,
+ xray=xray if isinstance(xray, bool) or xray <= 0 else xray - 1,
+ )
+ for k, v in self.get_subgraphs()
+ }
+ else:
+ subgraphs = {}
+
+ return draw_graph(
+ merge_configs(self.config, config),
+ nodes=self.nodes,
+ specs=self.channels,
+ input_channels=self.input_channels,
+ interrupt_after_nodes=self.interrupt_after_nodes,
+ interrupt_before_nodes=self.interrupt_before_nodes,
+ trigger_to_nodes=self.trigger_to_nodes,
+ checkpointer=self.checkpointer,
+ subgraphs=subgraphs,
+ )
+
+ async def aget_graph(
+ self, config: RunnableConfig | None = None, *, xray: int | bool = False
+ ) -> Graph:
+ """Return a drawable representation of the computation graph."""
+
+ # gather subgraphs
+ if xray:
+ subpregels: dict[str, PregelProtocol] = {
+ k: v async for k, v in self.aget_subgraphs()
+ }
+ subgraphs = {
+ k: v
+ for k, v in zip(
+ subpregels,
+ await asyncio.gather(
+ *(
+ p.aget_graph(
+ config,
+ xray=xray
+ if isinstance(xray, bool) or xray <= 0
+ else xray - 1,
+ )
+ for p in subpregels.values()
+ )
+ ),
+ )
+ }
+ else:
+ subgraphs = {}
+
+ return draw_graph(
+ merge_configs(self.config, config),
+ nodes=self.nodes,
+ specs=self.channels,
+ input_channels=self.input_channels,
+ interrupt_after_nodes=self.interrupt_after_nodes,
+ interrupt_before_nodes=self.interrupt_before_nodes,
+ trigger_to_nodes=self.trigger_to_nodes,
+ checkpointer=self.checkpointer,
+ subgraphs=subgraphs,
+ )
+
+ def _repr_mimebundle_(self, **kwargs: Any) -> dict[str, Any]:
+ """Mime bundle used by Jupyter to display the graph"""
+ return {
+ "text/plain": repr(self),
+ "image/png": self.get_graph().draw_mermaid_png(),
+ }
+
+ def copy(self, update: dict[str, Any] | None = None) -> Self:
+ attrs = {k: v for k, v in self.__dict__.items() if k != "__orig_class__"}
+ attrs.update(update or {})
+ return self.__class__(**attrs)
+
+ def with_config(self, config: RunnableConfig | None = None, **kwargs: Any) -> Self:
+ """Create a copy of the Pregel object with an updated config."""
+ return self.copy(
+ {"config": merge_configs(self.config, config, cast(RunnableConfig, kwargs))}
+ )
+
+ def validate(self) -> Self:
+ for name, node in self.nodes.items():
+ if node.timeout is not None:
+ validate_timeout_supported(node.node or node.bound, name=name)
+ validate_graph(
+ self.nodes,
+ {k: v for k, v in self.channels.items() if isinstance(v, BaseChannel)},
+ {k: v for k, v in self.channels.items() if not isinstance(v, BaseChannel)},
+ self.input_channels,
+ self.output_channels,
+ self.stream_channels,
+ self.interrupt_after_nodes,
+ self.interrupt_before_nodes,
+ )
+ self.trigger_to_nodes = _trigger_to_nodes(self.nodes)
+ return self
+
+ @deprecated(
+ "`config_schema` is deprecated. Use `get_context_jsonschema` for the relevant schema instead.",
+ category=None,
+ )
+ def config_schema(self, *, include: Sequence[str] | None = None) -> type[BaseModel]:
+ warnings.warn(
+ "`config_schema` is deprecated. Use `get_context_jsonschema` for the relevant schema instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+
+ include = include or []
+ fields = {
+ **(
+ {"configurable": (self.context_schema, None)}
+ if self.context_schema
+ else {}
+ ),
+ **{
+ field_name: (field_type, None)
+ for field_name, field_type in get_type_hints(RunnableConfig).items()
+ if field_name in [i for i in include if i != "configurable"]
+ },
+ }
+ return create_model(self.get_name("Config"), field_definitions=fields)
+
+ @deprecated(
+ "`get_config_jsonschema` is deprecated. Use `get_context_jsonschema` instead.",
+ category=None,
+ )
+ def get_config_jsonschema(
+ self, *, include: Sequence[str] | None = None
+ ) -> dict[str, Any]:
+ warnings.warn(
+ "`get_config_jsonschema` is deprecated. Use `get_context_jsonschema` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=LangGraphDeprecatedSinceV10)
+ schema = self.config_schema(include=include)
+ return schema.model_json_schema()
+
+ def get_context_jsonschema(self) -> dict[str, Any] | None:
+ if (context_schema := self.context_schema) is None:
+ return None
+
+ if isclass(context_schema) and issubclass(context_schema, BaseModel):
+ return context_schema.model_json_schema()
+ elif is_typeddict(context_schema) or is_dataclass(context_schema):
+ return TypeAdapter(context_schema).json_schema()
+ else:
+ raise ValueError(
+ f"Invalid context schema type: {context_schema}. Must be a BaseModel, TypedDict or dataclass."
+ )
+
+ @property
+ def InputType(self) -> Any:
+ if isinstance(self.input_channels, str):
+ channel = self.channels[self.input_channels]
+ if isinstance(channel, BaseChannel):
+ return channel.UpdateType
+
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ config = merge_configs(self.config, config)
+ if isinstance(self.input_channels, str):
+ return super().get_input_schema(config)
+ else:
+ return create_model(
+ self.get_name("Input"),
+ field_definitions={
+ k: (c.UpdateType, None)
+ for k in self.input_channels or self.channels.keys()
+ if (c := self.channels[k]) and isinstance(c, BaseChannel)
+ },
+ )
+
+ def get_input_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ schema = self.get_input_schema(config)
+ return schema.model_json_schema()
+
+ @property
+ def OutputType(self) -> Any:
+ if isinstance(self.output_channels, str):
+ channel = self.channels[self.output_channels]
+ if isinstance(channel, BaseChannel):
+ return channel.ValueType
+
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ config = merge_configs(self.config, config)
+ if isinstance(self.output_channels, str):
+ return super().get_output_schema(config)
+ else:
+ return create_model(
+ self.get_name("Output"),
+ field_definitions={
+ k: (c.ValueType, None)
+ for k in self.output_channels
+ if (c := self.channels[k]) and isinstance(c, BaseChannel)
+ },
+ )
+
+ def get_output_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ schema = self.get_output_schema(config)
+ return schema.model_json_schema()
+
+ @property
+ def stream_channels_list(self) -> Sequence[str]:
+ stream_channels = self.stream_channels_asis
+ return (
+ [stream_channels] if isinstance(stream_channels, str) else stream_channels
+ )
+
+ @property
+ def stream_channels_asis(self) -> str | Sequence[str]:
+ return self.stream_channels or [
+ k for k in self.channels if isinstance(self.channels[k], BaseChannel)
+ ]
+
+ def get_subgraphs(
+ self, *, namespace: str | None = None, recurse: bool = False
+ ) -> Iterator[tuple[str, PregelProtocol]]:
+ """Get the subgraphs of the graph.
+
+ Args:
+ namespace: The namespace to filter the subgraphs by.
+ recurse: Whether to recurse into the subgraphs.
+ If `False`, only the immediate subgraphs will be returned.
+
+ Returns:
+ An iterator of the `(namespace, subgraph)` pairs.
+ """
+ for name, node in self.nodes.items():
+ # filter by prefix
+ if namespace is not None:
+ if not namespace.startswith(name):
+ continue
+
+ # find the subgraph, if any
+ graph = node.subgraphs[0] if node.subgraphs else None
+
+ # if found, yield recursively
+ if graph:
+ if name == namespace:
+ yield name, graph
+ return # we found it, stop searching
+ if namespace is None:
+ yield name, graph
+ if recurse and isinstance(graph, Pregel):
+ if namespace is not None:
+ namespace = namespace[len(name) + 1 :]
+ yield from (
+ (f"{name}{NS_SEP}{n}", s)
+ for n, s in graph.get_subgraphs(
+ namespace=namespace, recurse=recurse
+ )
+ )
+
+ async def aget_subgraphs(
+ self, *, namespace: str | None = None, recurse: bool = False
+ ) -> AsyncIterator[tuple[str, PregelProtocol]]:
+ """Get the subgraphs of the graph.
+
+ Args:
+ namespace: The namespace to filter the subgraphs by.
+ recurse: Whether to recurse into the subgraphs.
+ If `False`, only the immediate subgraphs will be returned.
+
+ Returns:
+ An iterator of the `(namespace, subgraph)` pairs.
+ """
+ for name, node in self.get_subgraphs(namespace=namespace, recurse=recurse):
+ yield name, node
+
+ # Mappers for v2 stream coercion (pydantic/dataclass).
+ # Set by CompiledStateGraph; None for base Pregel.
+ _output_mapper: Callable[[Any], Any] | None = None
+ _state_mapper: Callable[[Any], Any] | None = None
+
+ def _migrate_checkpoint(self, checkpoint: Checkpoint) -> None:
+ """Migrate a saved checkpoint to new channel layout."""
+ if checkpoint["v"] < 4 and checkpoint.get("pending_sends"):
+ pending_sends: list[Send] = checkpoint.pop("pending_sends")
+ checkpoint["channel_values"][TASKS] = pending_sends
+ checkpoint["channel_versions"][TASKS] = max(
+ checkpoint["channel_versions"].values()
+ )
+
+ def _prepare_state_snapshot(
+ self,
+ config: RunnableConfig,
+ saved: CheckpointTuple | None,
+ recurse: BaseCheckpointSaver | None = None,
+ apply_pending_writes: bool = False,
+ ) -> StateSnapshot:
+ if not saved:
+ return StateSnapshot(
+ values={},
+ next=(),
+ config=config,
+ metadata=None,
+ created_at=None,
+ parent_config=None,
+ tasks=(),
+ interrupts=(),
+ )
+
+ # migrate checkpoint if needed
+ self._migrate_checkpoint(saved.checkpoint)
+
+ step = saved.metadata.get("step", -1) + 1
+ stop = step + 2
+ channels, managed = channels_from_checkpoint(
+ self.channels,
+ saved.checkpoint,
+ saver=self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config,
+ )
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ saved.checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step,
+ stop,
+ for_execution=True,
+ store=self.store,
+ checkpointer=(
+ self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None
+ ),
+ manager=None,
+ )
+ # get the subgraphs
+ subgraphs = dict(self.get_subgraphs())
+ parent_ns = saved.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_states: dict[str, RunnableConfig | StateSnapshot] = {}
+ for task in next_tasks.values():
+ if task.name not in subgraphs:
+ continue
+ # assemble checkpoint_ns for this task
+ task_ns = f"{task.name}{NS_END}{task.id}"
+ if parent_ns:
+ task_ns = f"{parent_ns}{NS_SEP}{task_ns}"
+ if not recurse:
+ # set config as signal that subgraph checkpoints exist
+ config = {
+ CONF: {
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = config
+ else:
+ # get the state of the subgraph
+ config = {
+ CONF: {
+ CONFIG_KEY_CHECKPOINTER: recurse,
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = subgraphs[task.name].get_state(
+ config, subgraphs=True
+ )
+ # apply pending writes
+ if null_writes := [
+ w[1:] for w in saved.pending_writes or [] if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ saved.checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ None,
+ self.trigger_to_nodes,
+ )
+ if apply_pending_writes and saved.pending_writes:
+ for tid, k, v in saved.pending_writes:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ if tasks := [t for t in next_tasks.values() if t.writes]:
+ apply_writes(
+ saved.checkpoint, channels, tasks, None, self.trigger_to_nodes
+ )
+ tasks_with_writes = tasks_w_writes(
+ next_tasks.values(),
+ saved.pending_writes,
+ task_states,
+ self.stream_channels_asis,
+ )
+ # assemble the state snapshot
+ return StateSnapshot(
+ read_channels(channels, self.stream_channels_asis),
+ tuple(t.name for t in next_tasks.values() if not t.writes),
+ patch_checkpoint_map(saved.config, saved.metadata),
+ saved.metadata,
+ saved.checkpoint["ts"],
+ patch_checkpoint_map(saved.parent_config, saved.metadata),
+ tasks_with_writes,
+ tuple([i for task in tasks_with_writes for i in task.interrupts]),
+ )
+
+ async def _aprepare_state_snapshot(
+ self,
+ config: RunnableConfig,
+ saved: CheckpointTuple | None,
+ recurse: BaseCheckpointSaver | None = None,
+ apply_pending_writes: bool = False,
+ ) -> StateSnapshot:
+ if not saved:
+ return StateSnapshot(
+ values={},
+ next=(),
+ config=config,
+ metadata=None,
+ created_at=None,
+ parent_config=None,
+ tasks=(),
+ interrupts=(),
+ )
+
+ # migrate checkpoint if needed
+ self._migrate_checkpoint(saved.checkpoint)
+
+ step = saved.metadata.get("step", -1) + 1
+ stop = step + 2
+ channels, managed = await achannels_from_checkpoint(
+ self.channels,
+ saved.checkpoint,
+ saver=self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config,
+ )
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ saved.checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step,
+ stop,
+ for_execution=True,
+ store=self.store,
+ checkpointer=(
+ self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None
+ ),
+ manager=None,
+ )
+ # get the subgraphs
+ subgraphs = {n: g async for n, g in self.aget_subgraphs()}
+ parent_ns = saved.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_states: dict[str, RunnableConfig | StateSnapshot] = {}
+ for task in next_tasks.values():
+ if task.name not in subgraphs:
+ continue
+ # assemble checkpoint_ns for this task
+ task_ns = f"{task.name}{NS_END}{task.id}"
+ if parent_ns:
+ task_ns = f"{parent_ns}{NS_SEP}{task_ns}"
+ if not recurse:
+ # set config as signal that subgraph checkpoints exist
+ config = {
+ CONF: {
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = config
+ else:
+ # get the state of the subgraph
+ config = {
+ CONF: {
+ CONFIG_KEY_CHECKPOINTER: recurse,
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = await subgraphs[task.name].aget_state(
+ config, subgraphs=True
+ )
+ # apply pending writes
+ if null_writes := [
+ w[1:] for w in saved.pending_writes or [] if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ saved.checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ None,
+ self.trigger_to_nodes,
+ )
+ if apply_pending_writes and saved.pending_writes:
+ for tid, k, v in saved.pending_writes:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ if tasks := [t for t in next_tasks.values() if t.writes]:
+ apply_writes(
+ saved.checkpoint, channels, tasks, None, self.trigger_to_nodes
+ )
+
+ tasks_with_writes = tasks_w_writes(
+ next_tasks.values(),
+ saved.pending_writes,
+ task_states,
+ self.stream_channels_asis,
+ )
+ # assemble the state snapshot
+ return StateSnapshot(
+ read_channels(channels, self.stream_channels_asis),
+ tuple(t.name for t in next_tasks.values() if not t.writes),
+ patch_checkpoint_map(saved.config, saved.metadata),
+ saved.metadata,
+ saved.checkpoint["ts"],
+ patch_checkpoint_map(saved.parent_config, saved.metadata),
+ tasks_with_writes,
+ tuple([i for task in tasks_with_writes for i in task.interrupts]),
+ )
+
+ def get_state(
+ self, config: RunnableConfig, *, subgraphs: bool = False
+ ) -> StateSnapshot:
+ """Get the current state of the graph."""
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ for _, pregel in self.get_subgraphs(namespace=recast, recurse=True):
+ return pregel.get_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ subgraphs=subgraphs,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(self.config, config) if self.config else config
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config = merge_configs(
+ config, {CONF: {CONFIG_KEY_CHECKPOINT_NS: recast_checkpoint_ns(ns)}}
+ )
+ thread_id = config[CONF][CONFIG_KEY_THREAD_ID]
+ if not isinstance(thread_id, str):
+ config[CONF][CONFIG_KEY_THREAD_ID] = str(thread_id)
+
+ saved = checkpointer.get_tuple(config)
+ return self._prepare_state_snapshot(
+ config,
+ saved,
+ recurse=checkpointer if subgraphs else None,
+ apply_pending_writes=CONFIG_KEY_CHECKPOINT_ID not in config[CONF],
+ )
+
+ async def aget_state(
+ self, config: RunnableConfig, *, subgraphs: bool = False
+ ) -> StateSnapshot:
+ """Get the current state of the graph."""
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ async for _, pregel in self.aget_subgraphs(namespace=recast, recurse=True):
+ return await pregel.aget_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ subgraphs=subgraphs,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(self.config, config) if self.config else config
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config = merge_configs(
+ config, {CONF: {CONFIG_KEY_CHECKPOINT_NS: recast_checkpoint_ns(ns)}}
+ )
+ thread_id = config[CONF][CONFIG_KEY_THREAD_ID]
+ if not isinstance(thread_id, str):
+ config[CONF][CONFIG_KEY_THREAD_ID] = str(thread_id)
+
+ saved = await checkpointer.aget_tuple(config)
+ return await self._aprepare_state_snapshot(
+ config,
+ saved,
+ recurse=checkpointer if subgraphs else None,
+ apply_pending_writes=CONFIG_KEY_CHECKPOINT_ID not in config[CONF],
+ )
+
+ def get_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> Iterator[StateSnapshot]:
+ """Get the history of the state of the graph."""
+ config = ensure_config(config)
+ checkpointer: BaseCheckpointSaver | None = config[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ for _, pregel in self.get_subgraphs(namespace=recast, recurse=True):
+ yield from pregel.get_state_history(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ filter=filter,
+ before=before,
+ limit=limit,
+ )
+ return
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(
+ self.config,
+ config,
+ {
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: checkpoint_ns,
+ CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID]),
+ }
+ },
+ )
+ # eagerly consume list() to avoid holding up the db cursor
+ for checkpoint_tuple in list(
+ checkpointer.list(config, before=before, limit=limit, filter=filter)
+ ):
+ yield self._prepare_state_snapshot(
+ checkpoint_tuple.config, checkpoint_tuple
+ )
+
+ async def aget_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> AsyncIterator[StateSnapshot]:
+ """Asynchronously get the history of the state of the graph."""
+ config = ensure_config(config)
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ async for _, pregel in self.aget_subgraphs(namespace=recast, recurse=True):
+ async for state in pregel.aget_state_history(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ filter=filter,
+ before=before,
+ limit=limit,
+ ):
+ yield state
+ return
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(
+ self.config,
+ config,
+ {
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: checkpoint_ns,
+ CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID]),
+ }
+ },
+ )
+ # eagerly consume list() to avoid holding up the db cursor
+ for checkpoint_tuple in [
+ c
+ async for c in checkpointer.alist(
+ config, before=before, limit=limit, filter=filter
+ )
+ ]:
+ yield await self._aprepare_state_snapshot(
+ checkpoint_tuple.config, checkpoint_tuple
+ )
+
+ def bulk_update_state(
+ self,
+ config: RunnableConfig,
+ supersteps: Sequence[Sequence[StateUpdate]],
+ ) -> RunnableConfig:
+ """Apply updates to the graph state in bulk. Requires a checkpointer to be set.
+
+ Args:
+ config: The config to apply the updates to.
+ supersteps: A list of supersteps, each including a list of updates to apply sequentially to a graph state.
+
+ Each update is a tuple of the form `(values, as_node, task_id)` where `task_id` is optional.
+
+ Raises:
+ ValueError: If no checkpointer is set or no updates are provided.
+ InvalidUpdateError: If an invalid update is provided.
+
+ Returns:
+ RunnableConfig: The updated config.
+ """
+
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if len(supersteps) == 0:
+ raise ValueError("No supersteps provided")
+
+ if any(len(u) == 0 for u in supersteps):
+ raise ValueError("No updates provided")
+
+ # delegate to subgraph
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ for _, pregel in self.get_subgraphs(namespace=recast, recurse=True):
+ return pregel.bulk_update_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ supersteps,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ def perform_superstep(
+ input_config: RunnableConfig, updates: Sequence[StateUpdate]
+ ) -> RunnableConfig:
+ # get last checkpoint
+ config = ensure_config(self.config, input_config)
+ saved = checkpointer.get_tuple(config)
+ if saved is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ checkpoint = (
+ copy_checkpoint(saved.checkpoint) if saved else empty_checkpoint()
+ )
+ checkpoint_previous_versions = (
+ saved.checkpoint["channel_versions"].copy() if saved else {}
+ )
+ step = saved.metadata.get("step", -1) if saved else -1
+ # merge configurable fields with previous checkpoint config
+ checkpoint_config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ )
+ },
+ )
+ if saved:
+ checkpoint_config = patch_configurable(config, saved.config[CONF])
+ channels, managed = channels_from_checkpoint(
+ self.channels,
+ checkpoint,
+ saver=self.checkpointer
+ if saved is not None
+ and isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config if saved is not None else None,
+ )
+ values, as_node = updates[0][:2]
+
+ # no values as END, just clear all tasks
+ if values is None and as_node == END:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when clearing state"
+ )
+
+ if saved is not None:
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # apply null writes
+ if null_writes := [
+ w[1:]
+ for w in saved.pending_writes or []
+ if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # apply writes from tasks that already ran
+ for tid, k, v in saved.pending_writes or []:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ # clear all current tasks
+ apply_writes(
+ checkpoint,
+ channels,
+ next_tasks.values(),
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # save checkpoint
+ next_config = checkpointer.put(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, step),
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions,
+ checkpoint["channel_versions"],
+ ),
+ )
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+
+ # act as an input
+ if as_node == INPUT:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when updating as input"
+ )
+
+ if input_writes := deque(map_input(self.input_channels, values)):
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, input_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+
+ # apply input write to channels
+ next_step = (
+ step + 1
+ if saved and saved.metadata.get("step") is not None
+ else -1
+ )
+ next_config = checkpointer.put(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, next_step),
+ {
+ "source": "input",
+ "step": next_step,
+ "parents": saved.metadata.get("parents", {})
+ if saved
+ else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions,
+ checkpoint["channel_versions"],
+ ),
+ )
+
+ # store the writes
+ checkpointer.put_writes(
+ next_config,
+ input_writes,
+ str(uuid5(UUID(checkpoint["id"]), INPUT)),
+ )
+
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+ else:
+ raise InvalidUpdateError(
+ f"Received no input writes for {self.input_channels}"
+ )
+
+ # copy checkpoint
+ if as_node == "__copy__":
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot copy checkpoint with multiple updates"
+ )
+
+ if saved is None:
+ raise InvalidUpdateError("Cannot copy a non-existent checkpoint")
+
+ next_checkpoint = create_checkpoint(checkpoint, None, step)
+
+ # copy checkpoint
+ next_config = checkpointer.put(
+ saved.parent_config
+ or patch_configurable(
+ saved.config, {CONFIG_KEY_CHECKPOINT_ID: None}
+ ),
+ next_checkpoint,
+ {
+ "source": "fork",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}),
+ },
+ {},
+ )
+
+ # we want to both clone a checkpoint and update state in one go.
+ # reuse the same task ID if possible.
+ if isinstance(values, list) and len(values) > 0:
+ # figure out the task IDs for the next update checkpoint
+ next_tasks = prepare_next_tasks(
+ next_checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ next_config,
+ step + 2,
+ step + 4,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+
+ tasks_group_by = defaultdict(list)
+ user_group_by: dict[str, list[StateUpdate]] = defaultdict(list)
+
+ for task in next_tasks.values():
+ tasks_group_by[task.name].append(task.id)
+
+ for item in values:
+ if not isinstance(item, Sequence):
+ raise InvalidUpdateError(
+ f"Invalid update item: {item} when copying checkpoint"
+ )
+
+ values, as_node = item[:2]
+
+ user_group = user_group_by[as_node]
+ tasks_group = tasks_group_by[as_node]
+
+ target_idx = len(user_group)
+ task_id = (
+ tasks_group[target_idx]
+ if target_idx < len(tasks_group)
+ else None
+ )
+
+ user_group_by[as_node].append(
+ StateUpdate(values=values, as_node=as_node, task_id=task_id)
+ )
+
+ return perform_superstep(
+ patch_checkpoint_map(next_config, saved.metadata),
+ [item for lst in user_group_by.values() for item in lst],
+ )
+
+ return patch_checkpoint_map(next_config, saved.metadata)
+
+ # task ids can be provided in the StateUpdate, but if not,
+ # we use the task id generated by prepare_next_tasks
+ node_to_task_ids: dict[str, deque[str]] = defaultdict(deque)
+ if saved is not None and saved.pending_writes is not None:
+ # we call prepare_next_tasks to discover the task IDs that
+ # would have been generated, so we can reuse them and
+ # properly populate task.result in state history
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes,
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # collect task ids to reuse so we can properly attach task results
+ for t in next_tasks.values():
+ node_to_task_ids[t.name].append(t.id)
+
+ valid_updates: list[tuple[str, dict[str, Any] | None, str | None]] = []
+ if len(updates) == 1:
+ values, as_node, task_id = updates[0]
+ # find last node that updated the state, if not provided
+ if as_node is None and len(self.nodes) == 1:
+ as_node = tuple(self.nodes)[0]
+ elif as_node is None and not any(
+ v
+ for vv in checkpoint["versions_seen"].values()
+ for v in vv.values()
+ ):
+ if (
+ isinstance(self.input_channels, str)
+ and self.input_channels in self.nodes
+ ):
+ as_node = self.input_channels
+ elif as_node is None:
+ last_seen_by_node = sorted(
+ (v, n)
+ for n, seen in checkpoint["versions_seen"].items()
+ if n in self.nodes
+ for v in seen.values()
+ )
+ # if two nodes updated the state at the same time, it's ambiguous
+ if last_seen_by_node:
+ if len(last_seen_by_node) == 1:
+ as_node = last_seen_by_node[0][1]
+ elif last_seen_by_node[-1][0] != last_seen_by_node[-2][0]:
+ as_node = last_seen_by_node[-1][1]
+ if as_node is None:
+ raise InvalidUpdateError("Ambiguous update, specify as_node")
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+ valid_updates.append((as_node, values, task_id))
+ else:
+ for values, as_node, task_id in updates:
+ if as_node is None:
+ raise InvalidUpdateError(
+ "as_node is required when applying multiple updates"
+ )
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+
+ valid_updates.append((as_node, values, task_id))
+
+ run_tasks: list[PregelTaskWrites] = []
+ run_task_ids: list[str] = []
+
+ for as_node, values, provided_task_id in valid_updates:
+ # create task to run all writers of the chosen node
+ writers = self.nodes[as_node].flat_writers
+ if not writers:
+ raise InvalidUpdateError(f"Node {as_node} has no writers")
+ writes: deque[tuple[str, Any]] = deque()
+ task = PregelTaskWrites((), as_node, writes, [INTERRUPT])
+ # get the task ids that were prepared for this node
+ # if a task id was provided in the StateUpdate, we use it
+ # otherwise, we use the next available task id
+ prepared_task_ids = node_to_task_ids.get(as_node, deque())
+ task_id = provided_task_id or (
+ prepared_task_ids.popleft()
+ if prepared_task_ids
+ else str(uuid5(UUID(checkpoint["id"]), INTERRUPT))
+ )
+ run_tasks.append(task)
+ run_task_ids.append(task_id)
+ run = RunnableSequence(*writers) if len(writers) > 1 else writers[0]
+ # execute task
+ run.invoke(
+ values,
+ patch_config(
+ config,
+ run_name=self.name + "UpdateState",
+ configurable={
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_TASK_ID: task_id,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ _scratchpad(
+ None,
+ [],
+ task_id,
+ "",
+ None,
+ step,
+ step + 2,
+ ),
+ channels,
+ managed,
+ task,
+ ),
+ },
+ ),
+ )
+ # save task writes
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # channel writes are saved to current checkpoint
+ channel_writes = [w for w in task.writes if w[0] != PUSH]
+ if saved and channel_writes:
+ checkpointer.put_writes(checkpoint_config, channel_writes, task_id)
+ # apply to checkpoint and save
+ apply_writes(
+ checkpoint,
+ channels,
+ run_tasks,
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ checkpoint = create_checkpoint(checkpoint, channels, step + 1)
+ next_config = checkpointer.put(
+ checkpoint_config,
+ checkpoint,
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions, checkpoint["channel_versions"]
+ ),
+ )
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # save push writes
+ if push_writes := [w for w in task.writes if w[0] == PUSH]:
+ checkpointer.put_writes(next_config, push_writes, task_id)
+
+ return patch_checkpoint_map(next_config, saved.metadata if saved else None)
+
+ current_config = patch_configurable(
+ config, {CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID])}
+ )
+ for superstep in supersteps:
+ current_config = perform_superstep(current_config, superstep)
+ return current_config
+
+ async def abulk_update_state(
+ self,
+ config: RunnableConfig,
+ supersteps: Sequence[Sequence[StateUpdate]],
+ ) -> RunnableConfig:
+ """Asynchronously apply updates to the graph state in bulk. Requires a checkpointer to be set.
+
+ Args:
+ config: The config to apply the updates to.
+ supersteps: A list of supersteps, each including a list of updates to apply sequentially to a graph state.
+
+ Each update is a tuple of the form `(values, as_node, task_id)` where `task_id` is optional.
+
+ Raises:
+ ValueError: If no checkpointer is set or no updates are provided.
+ InvalidUpdateError: If an invalid update is provided.
+
+ Returns:
+ RunnableConfig: The updated config.
+ """
+
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if len(supersteps) == 0:
+ raise ValueError("No supersteps provided")
+
+ if any(len(u) == 0 for u in supersteps):
+ raise ValueError("No updates provided")
+
+ # delegate to subgraph
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ async for _, pregel in self.aget_subgraphs(namespace=recast, recurse=True):
+ return await pregel.abulk_update_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ supersteps,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ async def aperform_superstep(
+ input_config: RunnableConfig, updates: Sequence[StateUpdate]
+ ) -> RunnableConfig:
+ # get last checkpoint
+ config = ensure_config(self.config, input_config)
+ saved = await checkpointer.aget_tuple(config)
+ if saved is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ checkpoint = (
+ copy_checkpoint(saved.checkpoint) if saved else empty_checkpoint()
+ )
+ checkpoint_previous_versions = (
+ saved.checkpoint["channel_versions"].copy() if saved else {}
+ )
+ step = saved.metadata.get("step", -1) if saved else -1
+ # merge configurable fields with previous checkpoint config
+ checkpoint_config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ )
+ },
+ )
+ if saved:
+ checkpoint_config = patch_configurable(config, saved.config[CONF])
+ channels, managed = await achannels_from_checkpoint(
+ self.channels,
+ checkpoint,
+ saver=self.checkpointer
+ if saved is not None
+ and isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config if saved is not None else None,
+ )
+ values, as_node = updates[0][:2]
+ # no values, just clear all tasks
+ if values is None and as_node == END:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when clearing state"
+ )
+ if saved is not None:
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # apply null writes
+ if null_writes := [
+ w[1:]
+ for w in saved.pending_writes or []
+ if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # apply writes from tasks that already ran
+ for tid, k, v in saved.pending_writes or []:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ # clear all current tasks
+ apply_writes(
+ checkpoint,
+ channels,
+ next_tasks.values(),
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # save checkpoint
+ next_config = await checkpointer.aput(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, step),
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions, checkpoint["channel_versions"]
+ ),
+ )
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+
+ # act as an input
+ if as_node == INPUT:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when updating as input"
+ )
+
+ if input_writes := deque(map_input(self.input_channels, values)):
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, input_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+
+ # apply input write to channels
+ next_step = (
+ step + 1
+ if saved and saved.metadata.get("step") is not None
+ else -1
+ )
+ next_config = await checkpointer.aput(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, next_step),
+ {
+ "source": "input",
+ "step": next_step,
+ "parents": saved.metadata.get("parents", {})
+ if saved
+ else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions,
+ checkpoint["channel_versions"],
+ ),
+ )
+
+ # store the writes
+ await checkpointer.aput_writes(
+ next_config,
+ input_writes,
+ str(uuid5(UUID(checkpoint["id"]), INPUT)),
+ )
+
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+ else:
+ raise InvalidUpdateError(
+ f"Received no input writes for {self.input_channels}"
+ )
+
+ # no values, copy checkpoint
+ if as_node == "__copy__":
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot copy checkpoint with multiple updates"
+ )
+
+ if saved is None:
+ raise InvalidUpdateError("Cannot copy a non-existent checkpoint")
+
+ next_checkpoint = create_checkpoint(checkpoint, None, step)
+
+ # copy checkpoint
+ next_config = await checkpointer.aput(
+ saved.parent_config
+ or patch_configurable(
+ saved.config, {CONFIG_KEY_CHECKPOINT_ID: None}
+ ),
+ next_checkpoint,
+ {
+ "source": "fork",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}),
+ },
+ {},
+ )
+
+ # we want to both clone a checkpoint and update state in one go.
+ # reuse the same task ID if possible.
+ if isinstance(values, list) and len(values) > 0:
+ # figure out the task IDs for the next update checkpoint
+ next_tasks = prepare_next_tasks(
+ next_checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ next_config,
+ step + 2,
+ step + 4,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+
+ tasks_group_by = defaultdict(list)
+ user_group_by: dict[str, list[StateUpdate]] = defaultdict(list)
+
+ for task in next_tasks.values():
+ tasks_group_by[task.name].append(task.id)
+
+ for item in values:
+ if not isinstance(item, Sequence):
+ raise InvalidUpdateError(
+ f"Invalid update item: {item} when copying checkpoint"
+ )
+
+ values, as_node = item[:2]
+ user_group = user_group_by[as_node]
+ tasks_group = tasks_group_by[as_node]
+
+ target_idx = len(user_group)
+ task_id = (
+ tasks_group[target_idx]
+ if target_idx < len(tasks_group)
+ else None
+ )
+
+ user_group_by[as_node].append(
+ StateUpdate(values=values, as_node=as_node, task_id=task_id)
+ )
+
+ return await aperform_superstep(
+ patch_checkpoint_map(next_config, saved.metadata),
+ [item for lst in user_group_by.values() for item in lst],
+ )
+
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+
+ # task ids can be provided in the StateUpdate, but if not,
+ # we use the task id generated by prepare_next_tasks
+ node_to_task_ids: dict[str, deque[str]] = defaultdict(deque)
+ if saved is not None and saved.pending_writes is not None:
+ # we call prepare_next_tasks to discover the task IDs that
+ # would have been generated, so we can reuse them and
+ # properly populate task.result in state history
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes,
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # collect task ids to reuse so we can properly attach task results
+ for t in next_tasks.values():
+ node_to_task_ids[t.name].append(t.id)
+
+ valid_updates: list[tuple[str, dict[str, Any] | None, str | None]] = []
+ if len(updates) == 1:
+ values, as_node, task_id = updates[0]
+ # find last node that updated the state, if not provided
+ if as_node is None and len(self.nodes) == 1:
+ as_node = tuple(self.nodes)[0]
+ elif as_node is None and not saved:
+ if (
+ isinstance(self.input_channels, str)
+ and self.input_channels in self.nodes
+ ):
+ as_node = self.input_channels
+ elif as_node is None:
+ last_seen_by_node = sorted(
+ (v, n)
+ for n, seen in checkpoint["versions_seen"].items()
+ if n in self.nodes
+ for v in seen.values()
+ )
+ # if two nodes updated the state at the same time, it's ambiguous
+ if last_seen_by_node:
+ if len(last_seen_by_node) == 1:
+ as_node = last_seen_by_node[0][1]
+ elif last_seen_by_node[-1][0] != last_seen_by_node[-2][0]:
+ as_node = last_seen_by_node[-1][1]
+ if as_node is None:
+ raise InvalidUpdateError("Ambiguous update, specify as_node")
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+ valid_updates.append((as_node, values, task_id))
+ else:
+ for values, as_node, task_id in updates:
+ if as_node is None:
+ raise InvalidUpdateError(
+ "as_node is required when applying multiple updates"
+ )
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+
+ valid_updates.append((as_node, values, task_id))
+
+ run_tasks: list[PregelTaskWrites] = []
+ run_task_ids: list[str] = []
+
+ for as_node, values, provided_task_id in valid_updates:
+ # create task to run all writers of the chosen node
+ writers = self.nodes[as_node].flat_writers
+ if not writers:
+ raise InvalidUpdateError(f"Node {as_node} has no writers")
+ writes: deque[tuple[str, Any]] = deque()
+ task = PregelTaskWrites((), as_node, writes, [INTERRUPT])
+ # get the task ids that were prepared for this node
+ # if a task id was provided in the StateUpdate, we use it
+ # otherwise, we use the next available task id
+ prepared_task_ids = node_to_task_ids.get(as_node, deque())
+ task_id = provided_task_id or (
+ prepared_task_ids.popleft()
+ if prepared_task_ids
+ else str(uuid5(UUID(checkpoint["id"]), INTERRUPT))
+ )
+ run_tasks.append(task)
+ run_task_ids.append(task_id)
+ run = RunnableSequence(*writers) if len(writers) > 1 else writers[0]
+ # execute task
+ await run.ainvoke(
+ values,
+ patch_config(
+ config,
+ run_name=self.name + "UpdateState",
+ configurable={
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_TASK_ID: task_id,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ _scratchpad(
+ None,
+ [],
+ task_id,
+ "",
+ None,
+ step,
+ step + 2,
+ ),
+ channels,
+ managed,
+ task,
+ ),
+ },
+ ),
+ )
+ # save task writes
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # channel writes are saved to current checkpoint
+ channel_writes = [w for w in task.writes if w[0] != PUSH]
+ if saved and channel_writes:
+ await checkpointer.aput_writes(
+ checkpoint_config, channel_writes, task_id
+ )
+ # apply to checkpoint and save
+ apply_writes(
+ checkpoint,
+ channels,
+ run_tasks,
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ checkpoint = create_checkpoint(checkpoint, channels, step + 1)
+ # save checkpoint, after applying writes
+ next_config = await checkpointer.aput(
+ checkpoint_config,
+ checkpoint,
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions, checkpoint["channel_versions"]
+ ),
+ )
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # save push writes
+ if push_writes := [w for w in task.writes if w[0] == PUSH]:
+ await checkpointer.aput_writes(next_config, push_writes, task_id)
+ return patch_checkpoint_map(next_config, saved.metadata if saved else None)
+
+ current_config = patch_configurable(
+ config, {CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID])}
+ )
+ for superstep in supersteps:
+ current_config = await aperform_superstep(current_config, superstep)
+ return current_config
+
+ def update_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ task_id: str | None = None,
+ ) -> RunnableConfig:
+ """Update the state of the graph with the given values, as if they came from
+ node `as_node`. If `as_node` is not provided, it will be set to the last node
+ that updated the state, if not ambiguous.
+ """
+ return self.bulk_update_state(config, [[StateUpdate(values, as_node, task_id)]])
+
+ async def aupdate_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any,
+ as_node: str | None = None,
+ task_id: str | None = None,
+ ) -> RunnableConfig:
+ """Asynchronously update the state of the graph with the given values, as if they came from
+ node `as_node`. If `as_node` is not provided, it will be set to the last node
+ that updated the state, if not ambiguous.
+ """
+ return await self.abulk_update_state(
+ config, [[StateUpdate(values, as_node, task_id)]]
+ )
+
+ def _defaults(
+ self,
+ config: RunnableConfig,
+ *,
+ stream_mode: StreamMode | Sequence[StreamMode],
+ print_mode: StreamMode | Sequence[StreamMode],
+ output_keys: str | Sequence[str] | None,
+ interrupt_before: All | Sequence[str] | None,
+ interrupt_after: All | Sequence[str] | None,
+ durability: Durability | None = None,
+ ) -> tuple[
+ set[StreamMode],
+ str | Sequence[str],
+ All | Sequence[str],
+ All | Sequence[str],
+ BaseCheckpointSaver | None,
+ BaseStore | None,
+ BaseCache | None,
+ Durability,
+ ]:
+ if config["recursion_limit"] < 1:
+ raise ValueError("recursion_limit must be at least 1")
+ if output_keys is None:
+ output_keys = self.stream_channels_asis
+ else:
+ validate_keys(output_keys, self.channels)
+ interrupt_before = interrupt_before or self.interrupt_before_nodes
+ interrupt_after = interrupt_after or self.interrupt_after_nodes
+ if isinstance(stream_mode, str):
+ stream_modes = {stream_mode}
+ else:
+ stream_modes = set(stream_mode)
+ if isinstance(print_mode, str):
+ stream_modes.add(print_mode)
+ else:
+ stream_modes.update(print_mode)
+ if self.checkpointer is False:
+ checkpointer: BaseCheckpointSaver | None = None
+ elif CONFIG_KEY_CHECKPOINTER in config.get(CONF, {}):
+ checkpointer = config[CONF][CONFIG_KEY_CHECKPOINTER]
+ elif self.checkpointer is True:
+ raise RuntimeError("checkpointer=True cannot be used for root graphs.")
+ else:
+ checkpointer = self.checkpointer
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if checkpointer and not config.get(CONF):
+ raise ValueError(
+ "Checkpointer requires one or more of the following 'configurable' "
+ "keys: thread_id, checkpoint_ns, checkpoint_id"
+ )
+ if CONFIG_KEY_RUNTIME in config.get(CONF, {}):
+ store: BaseStore | None = config[CONF][CONFIG_KEY_RUNTIME].store
+ else:
+ store = self.store
+ if CONFIG_KEY_CACHE in config.get(CONF, {}):
+ cache: BaseCache | None = config[CONF][CONFIG_KEY_CACHE]
+ else:
+ cache = self.cache
+ if durability is None:
+ durability = config.get(CONF, {}).get(CONFIG_KEY_DURABILITY, "async")
+ return (
+ stream_modes,
+ output_keys,
+ interrupt_before,
+ interrupt_after,
+ checkpointer,
+ store,
+ cache,
+ durability,
+ )
+
+ @overload
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v2"],
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Iterator[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Iterator[dict[str, Any] | Any]: ...
+
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Iterator[dict[str, Any] | Any]:
+ """Stream graph steps for a single input.
+
+ Args:
+ input: The input to the graph.
+ config: The configuration to use for the run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The mode to stream output, defaults to `self.stream_mode`.
+
+ Options are:
+
+ - `"values"`: Emit all values in the state after each step, including interrupts.
+ When used with functional API, values are emitted once at the end of the workflow.
+ - `"updates"`: Emit only the node or task names and updates returned by the nodes or tasks after each step.
+ If multiple updates are made in the same step (e.g. multiple nodes are run) then those updates are emitted separately.
+ - `"custom"`: Emit custom data from inside nodes or tasks using `StreamWriter`.
+ - `"messages"`: Emit LLM messages token-by-token together with metadata for any LLM invocations inside nodes or tasks.
+ - Will be emitted as 2-tuples `(LLM token, metadata)`.
+ - `"checkpoints"`: Emit an event when a checkpoint is created, in the same format as returned by `get_state()`.
+ - `"tasks"`: Emit events when tasks start and finish, including their results and errors.
+ - `"debug"`: Emit debug events with as much information as possible for each step.
+
+ You can pass a list as the `stream_mode` parameter to stream multiple modes at once.
+ The streamed outputs will be tuples of `(mode, data)`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The keys to stream, defaults to all non-context channels.
+ interrupt_before: Nodes to interrupt before, defaults to all nodes in the graph.
+ interrupt_after: Nodes to interrupt after, defaults to all nodes in the graph.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ subgraphs: Whether to stream events from inside subgraphs, defaults to `False`.
+
+ If `True`, the events will be emitted as tuples `(namespace, data)`,
+ or `(namespace, mode, data)` if `stream_mode` is a list,
+ where `namespace` is a tuple with the path to the node where a subgraph is invoked,
+ e.g. `("parent_node:", "child_node:")`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+
+ Yields:
+ The output of each step in the graph. The output shape depends on the `stream_mode`.
+ """
+ if (checkpoint_during := kwargs.get("checkpoint_during")) is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed. Please use `durability` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+ if durability is not None:
+ raise ValueError(
+ "Cannot use both `checkpoint_during` and `durability` parameters. Please use `durability` instead."
+ )
+ durability = "async" if checkpoint_during else "exit"
+
+ if stream_mode is None:
+ # if being called as a node in another graph, default to values mode
+ # but don't overwrite stream_mode arg if provided
+ stream_mode = (
+ "values"
+ if config is not None and CONFIG_KEY_TASK_ID in config.get(CONF, {})
+ else self.stream_mode
+ )
+ if debug or self.debug:
+ print_mode = ["updates", "values"]
+
+ stream = SyncQueue()
+
+ config = ensure_config(self.config, config)
+ run_manager = None
+ try:
+ # assign defaults
+ (
+ stream_modes,
+ output_keys,
+ interrupt_before_,
+ interrupt_after_,
+ checkpointer,
+ store,
+ cache,
+ durability_,
+ ) = self._defaults(
+ config,
+ stream_mode=stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ )
+ callback_manager = get_callback_manager_for_config(config)
+ if "messages" in stream_modes and version != "v2":
+ # Strip any inherited v2 messages handler so a v1 stream
+ # does not get routed through the content-block event
+ # protocol. Leave v1 handlers in place — an outer
+ # stream(stream_mode="messages", subgraphs=True) relies
+ # on its inheritable handler to observe events emitted
+ # by inner stream(stream_mode="messages") calls.
+ callback_manager.handlers = [
+ h
+ for h in callback_manager.handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ callback_manager.inheritable_handlers = [
+ h
+ for h in callback_manager.inheritable_handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ if "ls_integration" not in callback_manager.metadata:
+ callback_manager.add_metadata({"ls_integration": "langgraph"})
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name", self.get_name()),
+ run_id=config.get("run_id"),
+ )
+ graph_callback_manager = get_sync_graph_callback_manager_for_config(
+ config,
+ run_id=run_manager.run_id,
+ )
+ if checkpointer is None and durability is not None:
+ warnings.warn(
+ "`durability` has no effect when no checkpointer is present.",
+ )
+ # set up subgraph checkpointing
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config[CONF][CONFIG_KEY_CHECKPOINT_NS] = recast_checkpoint_ns(ns)
+ # set up messages stream mode
+ if "messages" in stream_modes:
+ ns_ = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ use_stream_messages_v2 = bool(
+ version == "v2" and config[CONF].get(CONFIG_KEY_STREAM_MESSAGES_V2)
+ )
+ messages_handler_cls = (
+ StreamMessagesHandlerV2
+ if use_stream_messages_v2
+ else StreamMessagesHandler
+ )
+ run_manager.inheritable_handlers.append(
+ messages_handler_cls(
+ stream.put,
+ subgraphs,
+ parent_ns=tuple(ns_.split(NS_SEP)) if ns_ else None,
+ )
+ )
+
+ # set up tools stream mode
+ if "tools" in stream_modes:
+ ns_tools = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ run_manager.inheritable_handlers.append(
+ StreamToolCallHandler(
+ stream.put,
+ subgraphs,
+ parent_ns=tuple(ns_tools.split(NS_SEP)) if ns_tools else None,
+ )
+ )
+
+ # set up custom stream mode
+ if "custom" in stream_modes:
+
+ def stream_writer(c: Any) -> None:
+ stream.put(
+ (
+ tuple(
+ get_config()[CONF][CONFIG_KEY_CHECKPOINT_NS].split(
+ NS_SEP
+ )[:-1]
+ ),
+ "custom",
+ c,
+ )
+ )
+ elif CONFIG_KEY_STREAM in config[CONF]:
+ stream_writer = config[CONF][CONFIG_KEY_RUNTIME].stream_writer
+ else:
+
+ def stream_writer(c: Any) -> None:
+ pass
+
+ # set durability mode for subgraphs
+ if durability is not None:
+ config[CONF][CONFIG_KEY_DURABILITY] = durability_
+
+ # build server_info from metadata + parent runtime
+ parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
+ server_info = _build_server_info(config, parent_runtime)
+
+ runtime = Runtime(
+ context=_coerce_context(self.context_schema, context),
+ store=store,
+ stream_writer=stream_writer,
+ previous=None,
+ execution_info=None,
+ server_info=server_info,
+ control=control or parent_runtime.control or RunControl(),
+ )
+ runtime = parent_runtime.merge(runtime)
+ config[CONF][CONFIG_KEY_RUNTIME] = runtime
+
+ # resolve mappers for v2 stream coercion
+ _output_mapper = self._output_mapper if version == "v2" else None
+ _state_mapper = self._state_mapper if version == "v2" else None
+
+ def emit_graph_lifecycle_events(loop: SyncPregelLoop) -> None:
+ while (event := loop._pop_lifecycle_event()) is not None:
+ if isinstance(event, GraphResumeEvent):
+ graph_callback_manager.on_resume(
+ replace(event, run_id=graph_callback_manager.run_id)
+ )
+ else:
+ graph_callback_manager.on_interrupt(
+ replace(event, run_id=graph_callback_manager.run_id)
+ )
+
+ with SyncPregelLoop(
+ input,
+ stream=StreamProtocol(stream.put, stream_modes),
+ config=config,
+ store=store,
+ cache=cache,
+ checkpointer=checkpointer,
+ nodes=self.nodes,
+ specs=self.channels,
+ output_keys=output_keys,
+ input_keys=self.input_channels,
+ stream_keys=self.stream_channels_asis,
+ interrupt_before=interrupt_before_,
+ interrupt_after=interrupt_after_,
+ manager=run_manager,
+ durability=durability_,
+ trigger_to_nodes=self.trigger_to_nodes,
+ migrate_checkpoint=self._migrate_checkpoint,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ has_graph_lifecycle_callbacks=bool(graph_callback_manager.handlers),
+ ) as loop:
+ emit_graph_lifecycle_events(loop)
+ # create runner
+ runner = PregelRunner(
+ submit=config[CONF].get(
+ CONFIG_KEY_RUNNER_SUBMIT, weakref.WeakMethod(loop.submit)
+ ),
+ put_writes=weakref.WeakMethod(loop.put_writes),
+ node_finished=config[CONF].get(CONFIG_KEY_NODE_FINISHED),
+ node_error_handler_map=self.node_error_handler_map,
+ schedule_error_handler=loop.schedule_error_handler,
+ )
+ # enable subgraph streaming
+ if subgraphs:
+ loop.config[CONF][CONFIG_KEY_STREAM] = loop.stream
+ # enable concurrent streaming
+ get_waiter: Callable[[], concurrent.futures.Future[None]] | None = None
+ if (
+ self.stream_eager
+ or subgraphs
+ or "messages" in stream_modes
+ or "custom" in stream_modes
+ ):
+ # we are careful to have a single waiter live at any one time
+ # because on exit we increment semaphore count by exactly 1
+ waiter: concurrent.futures.Future | None = None
+ # because sync futures cannot be cancelled, we instead
+ # release the stream semaphore on exit, which will cause
+ # a pending waiter to return immediately
+ loop.stack.callback(stream._count.release)
+
+ def get_waiter() -> concurrent.futures.Future[None]:
+ nonlocal waiter
+ if waiter is None or waiter.done():
+ waiter = loop.submit(stream.wait)
+ return waiter
+ else:
+ return waiter
+
+ # Similarly to Bulk Synchronous Parallel / Pregel model
+ # computation proceeds in steps, while there are channel updates.
+ # Channel updates from step N are only visible in step N+1
+ # channels are guaranteed to be immutable for the duration of the step,
+ # with channel updates applied only at the transition between steps.
+ while loop.tick():
+ for task in loop.match_cached_writes():
+ loop.output_writes(task.id, task.writes, cached=True)
+ for _ in runner.tick(
+ [t for t in loop.tasks.values() if not t.writes],
+ timeout=self.step_timeout,
+ get_waiter=get_waiter,
+ schedule_task=loop.accept_push,
+ ):
+ # emit output
+ yield from _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get,
+ queue.Empty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ )
+ loop.after_tick()
+ emit_graph_lifecycle_events(loop)
+ # wait for checkpoint
+ if durability_ == "sync":
+ loop._put_checkpoint_fut.result()
+ emit_graph_lifecycle_events(loop)
+ # emit output
+ yield from _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get,
+ queue.Empty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ )
+ # handle exit
+ if loop.status == "out_of_steps":
+ msg = create_error_message(
+ message=(
+ f"Recursion limit of {config['recursion_limit']} reached "
+ "without hitting a stop condition. You can increase the "
+ "limit by setting the `recursion_limit` config key."
+ ),
+ error_code=ErrorCode.GRAPH_RECURSION_LIMIT,
+ )
+ raise GraphRecursionError(msg)
+ elif loop.status == "draining":
+ if loop.control is None:
+ raise RuntimeError("Draining status requires run control")
+ raise GraphDrained(loop.control.drain_reason or "shutdown")
+ # set final channel values as run output
+ run_manager.on_chain_end(loop.output)
+ except BaseException as e:
+ if run_manager is not None:
+ run_manager.on_chain_error(e)
+ raise
+
+ @overload
+ def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v2"],
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> AsyncIterator[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> AsyncIterator[dict[str, Any] | Any]: ...
+
+ async def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> AsyncIterator[dict[str, Any] | Any]:
+ """Asynchronously stream graph steps for a single input.
+
+ Args:
+ input: The input to the graph.
+ config: The configuration to use for the run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The mode to stream output, defaults to `self.stream_mode`.
+
+ Options are:
+
+ - `"values"`: Emit all values in the state after each step, including interrupts.
+ When used with functional API, values are emitted once at the end of the workflow.
+ - `"updates"`: Emit only the node or task names and updates returned by the nodes or tasks after each step.
+ If multiple updates are made in the same step (e.g. multiple nodes are run) then those updates are emitted separately.
+ - `"custom"`: Emit custom data from inside nodes or tasks using `StreamWriter`.
+ - `"messages"`: Emit LLM messages token-by-token together with metadata for any LLM invocations inside nodes or tasks.
+ - Will be emitted as 2-tuples `(LLM token, metadata)`.
+ - `"checkpoints"`: Emit an event when a checkpoint is created, in the same format as returned by `get_state()`.
+ - `"tasks"`: Emit events when tasks start and finish, including their results and errors.
+ - `"debug"`: Emit debug events with as much information as possible for each step.
+
+ You can pass a list as the `stream_mode` parameter to stream multiple modes at once.
+ The streamed outputs will be tuples of `(mode, data)`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The keys to stream, defaults to all non-context channels.
+ interrupt_before: Nodes to interrupt before, defaults to all nodes in the graph.
+ interrupt_after: Nodes to interrupt after, defaults to all nodes in the graph.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ subgraphs: Whether to stream events from inside subgraphs, defaults to `False`.
+
+ If `True`, the events will be emitted as tuples `(namespace, data)`,
+ or `(namespace, mode, data)` if `stream_mode` is a list,
+ where `namespace` is a tuple with the path to the node where a subgraph is invoked,
+ e.g. `("parent_node:", "child_node:")`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+
+ Yields:
+ The output of each step in the graph. The output shape depends on the `stream_mode`.
+ """
+ if (checkpoint_during := kwargs.get("checkpoint_during")) is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed. Please use `durability` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+ if durability is not None:
+ raise ValueError(
+ "Cannot use both `checkpoint_during` and `durability` parameters. Please use `durability` instead."
+ )
+ durability = "async" if checkpoint_during else "exit"
+
+ if stream_mode is None:
+ # if being called as a node in another graph, default to values mode
+ # but don't overwrite stream_mode arg if provided
+ stream_mode = (
+ "values"
+ if config is not None and CONFIG_KEY_TASK_ID in config.get(CONF, {})
+ else self.stream_mode
+ )
+ if debug or self.debug:
+ print_mode = ["updates", "values"]
+
+ stream = AsyncQueue()
+ aioloop = asyncio.get_running_loop()
+ stream_put = cast(
+ Callable[[StreamChunk], None],
+ partial(aioloop.call_soon_threadsafe, stream.put_nowait),
+ )
+
+ config = ensure_config(self.config, config)
+ run_manager = None
+ try:
+ # assign defaults
+ (
+ stream_modes,
+ output_keys,
+ interrupt_before_,
+ interrupt_after_,
+ checkpointer,
+ store,
+ cache,
+ durability_,
+ ) = self._defaults(
+ config,
+ stream_mode=stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ )
+ callback_manager = get_async_callback_manager_for_config(config)
+ if "messages" in stream_modes and version != "v2":
+ # Strip any inherited v2 messages handler so a v1 stream
+ # does not get routed through the content-block event
+ # protocol. Leave v1 handlers in place — an outer
+ # astream(stream_mode="messages", subgraphs=True) relies
+ # on its inheritable handler to observe events emitted
+ # by inner astream(stream_mode="messages") calls.
+ callback_manager.handlers = [
+ h
+ for h in callback_manager.handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ callback_manager.inheritable_handlers = [
+ h
+ for h in callback_manager.inheritable_handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ if "ls_integration" not in callback_manager.metadata:
+ callback_manager.add_metadata({"ls_integration": "langgraph"})
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name", self.get_name()),
+ run_id=config.get("run_id"),
+ )
+ graph_callback_manager = get_async_graph_callback_manager_for_config(
+ config,
+ run_id=run_manager.run_id,
+ )
+ # if running from astream_log() run each proc with streaming
+ do_stream = (
+ next(
+ (
+ True
+ for h in run_manager.handlers
+ if isinstance(h, _StreamingCallbackHandler)
+ and not isinstance(h, StreamMessagesHandler)
+ ),
+ False,
+ )
+ if _StreamingCallbackHandler is not None
+ else False
+ )
+ if checkpointer is None and durability is not None:
+ warnings.warn(
+ "`durability` has no effect when no checkpointer is present.",
+ )
+ # set up subgraph checkpointing
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config[CONF][CONFIG_KEY_CHECKPOINT_NS] = recast_checkpoint_ns(ns)
+ # set up messages stream mode
+ if "messages" in stream_modes:
+ # namespace can be None in a root level graph?
+ ns_ = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ use_stream_messages_v2 = bool(
+ version == "v2" and config[CONF].get(CONFIG_KEY_STREAM_MESSAGES_V2)
+ )
+ messages_handler_cls = (
+ StreamMessagesHandlerV2
+ if use_stream_messages_v2
+ else StreamMessagesHandler
+ )
+ run_manager.inheritable_handlers.append(
+ messages_handler_cls(
+ stream_put,
+ subgraphs,
+ parent_ns=tuple(ns_.split(NS_SEP)) if ns_ else None,
+ )
+ )
+
+ # set up tools stream mode
+ if "tools" in stream_modes:
+ ns_tools = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ run_manager.inheritable_handlers.append(
+ StreamToolCallHandler(
+ stream_put,
+ subgraphs,
+ parent_ns=tuple(ns_tools.split(NS_SEP)) if ns_tools else None,
+ )
+ )
+
+ # set up custom stream mode
+ def stream_writer(c: Any) -> None:
+ aioloop.call_soon_threadsafe(
+ stream.put_nowait,
+ (
+ tuple(
+ get_config()[CONF][CONFIG_KEY_CHECKPOINT_NS].split(NS_SEP)[
+ :-1
+ ]
+ ),
+ "custom",
+ c,
+ ),
+ )
+
+ if "custom" in stream_modes:
+
+ def stream_writer(c: Any) -> None:
+ aioloop.call_soon_threadsafe(
+ stream.put_nowait,
+ (
+ tuple(
+ get_config()[CONF][CONFIG_KEY_CHECKPOINT_NS].split(
+ NS_SEP
+ )[:-1]
+ ),
+ "custom",
+ c,
+ ),
+ )
+ elif CONFIG_KEY_STREAM in config[CONF]:
+ stream_writer = config[CONF][CONFIG_KEY_RUNTIME].stream_writer
+ else:
+
+ def stream_writer(c: Any) -> None:
+ pass
+
+ # set durability mode for subgraphs
+ if durability is not None:
+ config[CONF][CONFIG_KEY_DURABILITY] = durability_
+
+ # build server_info from metadata + parent runtime
+ parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
+ server_info = _build_server_info(config, parent_runtime)
+
+ runtime = Runtime(
+ context=_coerce_context(self.context_schema, context),
+ store=store,
+ stream_writer=stream_writer,
+ previous=None,
+ execution_info=None,
+ server_info=server_info,
+ control=control or parent_runtime.control or RunControl(),
+ )
+ runtime = parent_runtime.merge(runtime)
+ config[CONF][CONFIG_KEY_RUNTIME] = runtime
+
+ # resolve mappers for v2 stream coercion
+ _output_mapper = self._output_mapper if version == "v2" else None
+ _state_mapper = self._state_mapper if version == "v2" else None
+
+ async def aemit_graph_lifecycle_events(loop: AsyncPregelLoop) -> None:
+ while (event := loop._pop_lifecycle_event()) is not None:
+ if isinstance(event, GraphResumeEvent):
+ await graph_callback_manager.on_resume(
+ GraphResumeEvent(
+ run_id=graph_callback_manager.run_id,
+ status=event.status,
+ checkpoint_id=event.checkpoint_id,
+ checkpoint_ns=event.checkpoint_ns,
+ )
+ )
+ else:
+ await graph_callback_manager.on_interrupt(
+ GraphInterruptEvent(
+ run_id=graph_callback_manager.run_id,
+ status=event.status,
+ checkpoint_id=event.checkpoint_id,
+ checkpoint_ns=event.checkpoint_ns,
+ interrupts=event.interrupts,
+ )
+ )
+
+ async with AsyncPregelLoop(
+ input,
+ stream=StreamProtocol(stream.put_nowait, stream_modes),
+ config=config,
+ store=store,
+ cache=cache,
+ checkpointer=checkpointer,
+ nodes=self.nodes,
+ specs=self.channels,
+ output_keys=output_keys,
+ input_keys=self.input_channels,
+ stream_keys=self.stream_channels_asis,
+ interrupt_before=interrupt_before_,
+ interrupt_after=interrupt_after_,
+ manager=run_manager,
+ durability=durability_,
+ trigger_to_nodes=self.trigger_to_nodes,
+ migrate_checkpoint=self._migrate_checkpoint,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ has_graph_lifecycle_callbacks=bool(graph_callback_manager.handlers),
+ ) as loop:
+ await aemit_graph_lifecycle_events(loop)
+ # create runner
+ runner = PregelRunner(
+ submit=config[CONF].get(
+ CONFIG_KEY_RUNNER_SUBMIT, weakref.WeakMethod(loop.submit)
+ ),
+ put_writes=weakref.WeakMethod(loop.put_writes),
+ use_astream=do_stream,
+ node_finished=config[CONF].get(CONFIG_KEY_NODE_FINISHED),
+ node_error_handler_map=self.node_error_handler_map,
+ aschedule_error_handler=loop.aschedule_error_handler,
+ )
+ # enable subgraph streaming
+ if subgraphs:
+ loop.config[CONF][CONFIG_KEY_STREAM] = StreamProtocol(
+ stream_put, stream_modes
+ )
+ # enable concurrent streaming
+ get_waiter: Callable[[], asyncio.Task[None]] | None = None
+ _cleanup_waiter: Callable[[], Awaitable[None]] | None = None
+ if (
+ self.stream_eager
+ or subgraphs
+ or "messages" in stream_modes
+ or "custom" in stream_modes
+ ):
+ # Keep a single waiter task alive; ensure cleanup on exit.
+ waiter: asyncio.Task[None] | None = None
+
+ def get_waiter() -> asyncio.Task[None]:
+ nonlocal waiter
+ if waiter is None or waiter.done():
+ waiter = aioloop.create_task(stream.wait())
+
+ def _clear(t: asyncio.Task[None]) -> None:
+ nonlocal waiter
+ if waiter is t:
+ waiter = None
+
+ waiter.add_done_callback(_clear)
+ return waiter
+
+ async def _cleanup_waiter() -> None:
+ """Wake pending waiter and/or cancel+await to avoid pending tasks."""
+ nonlocal waiter
+ # Try to wake via semaphore like SyncPregelLoop
+ with contextlib.suppress(Exception):
+ if hasattr(stream, "_count"):
+ stream._count.release()
+ t = waiter
+ waiter = None
+ if t is not None and not t.done():
+ t.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await t
+
+ # Similarly to Bulk Synchronous Parallel / Pregel model
+ # computation proceeds in steps, while there are channel updates
+ # channel updates from step N are only visible in step N+1
+ # channels are guaranteed to be immutable for the duration of the step,
+ # with channel updates applied only at the transition between steps
+ try:
+ while loop.tick():
+ for task in await loop.amatch_cached_writes():
+ loop.output_writes(task.id, task.writes, cached=True)
+ async for _ in runner.atick(
+ [t for t in loop.tasks.values() if not t.writes],
+ timeout=self.step_timeout,
+ get_waiter=get_waiter,
+ schedule_task=loop.aaccept_push,
+ ):
+ # emit output
+ for o in _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get_nowait,
+ asyncio.QueueEmpty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ ):
+ yield o
+ loop.after_tick()
+ await aemit_graph_lifecycle_events(loop)
+ # wait for checkpoint
+ if durability_ == "sync":
+ await cast(asyncio.Future, loop._put_checkpoint_fut)
+ finally:
+ # ensure waiter doesn't remain pending on cancel/shutdown
+ if _cleanup_waiter is not None:
+ await _cleanup_waiter()
+
+ await aemit_graph_lifecycle_events(loop)
+
+ # emit output
+ for o in _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get_nowait,
+ asyncio.QueueEmpty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ ):
+ yield o
+ # handle exit
+ if loop.status == "out_of_steps":
+ msg = create_error_message(
+ message=(
+ f"Recursion limit of {config['recursion_limit']} reached "
+ "without hitting a stop condition. You can increase the "
+ "limit by setting the `recursion_limit` config key."
+ ),
+ error_code=ErrorCode.GRAPH_RECURSION_LIMIT,
+ )
+ raise GraphRecursionError(msg)
+ elif loop.status == "draining":
+ if loop.control is None:
+ raise RuntimeError("Draining status requires run control")
+ raise GraphDrained(loop.control.drain_reason or "shutdown")
+ # set final channel values as run output
+ await run_manager.on_chain_end(loop.output)
+ except BaseException as e:
+ if run_manager is not None:
+ await asyncio.shield(run_manager.on_chain_error(e))
+ raise
+
+ @beta(message="The v3 streaming protocol on Pregel is experimental.")
+ def _pregel_stream_v3(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Internal v3 sync streaming implementation. Public entry: stream_events(version='v3').
+
+ Extra keyword arguments are forwarded to the underlying ``stream(...)``
+ call. The dispatcher in ``stream_events`` rejects ``stream_mode`` and
+ ``subgraphs`` since v3 owns them (``stream_mode`` is derived from the
+ transformer mux; ``subgraphs`` is always True so nested namespaces
+ flow through scoped muxes).
+
+ !!! warning
+
+ The v3 streaming protocol is experimental and may change.
+ """
+ parent_ns = _resolve_parent_ns(self.config, config)
+ compiled_factories = _normalize_stream_transformer_factories(
+ self.stream_transformers
+ )
+ extra_factories = _normalize_stream_transformer_factories(transformers)
+ mux = StreamMux(
+ factories=[
+ ValuesTransformer,
+ MessagesTransformer,
+ LifecycleTransformer,
+ SubgraphTransformer,
+ *compiled_factories,
+ *extra_factories,
+ ],
+ scope=parent_ns,
+ is_async=False,
+ )
+ graph_iter = iter(
+ self.stream(
+ input,
+ patch_configurable(config, {CONFIG_KEY_STREAM_MESSAGES_V2: True}),
+ stream_mode=_collect_stream_modes(mux),
+ subgraphs=True,
+ version="v2",
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ **kwargs,
+ )
+ )
+ return GraphRunStream(graph_iter, mux)
+
+ @beta(message="The v3 streaming protocol on Pregel is experimental.")
+ async def _apregel_stream_v3(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Internal v3 async streaming implementation. Public entry: astream_events(version='v3').
+
+ Extra keyword arguments are forwarded to the underlying ``astream(...)``
+ call. The dispatcher in ``astream_events`` rejects ``stream_mode`` and
+ ``subgraphs`` since v3 owns them (``stream_mode`` is derived from the
+ transformer mux; ``subgraphs`` is always True so nested namespaces
+ flow through scoped muxes).
+
+ !!! warning
+
+ The v3 streaming protocol is experimental and may change.
+ """
+ parent_ns = _resolve_parent_ns(self.config, config)
+ compiled_factories = _normalize_stream_transformer_factories(
+ self.stream_transformers
+ )
+ extra_factories = _normalize_stream_transformer_factories(transformers)
+ mux = StreamMux(
+ factories=[
+ ValuesTransformer,
+ MessagesTransformer,
+ LifecycleTransformer,
+ SubgraphTransformer,
+ *compiled_factories,
+ *extra_factories,
+ ],
+ scope=parent_ns,
+ is_async=True,
+ )
+ graph_aiter = self.astream(
+ input,
+ patch_configurable(config, {CONFIG_KEY_STREAM_MESSAGES_V2: True}),
+ stream_mode=_collect_stream_modes(mux),
+ subgraphs=True,
+ version="v2",
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ **kwargs,
+ ).__aiter__()
+ return AsyncGraphRunStream(graph_aiter, mux)
+
+ @overload
+ def stream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any: ...
+
+ def stream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Stream events from this graph.
+
+ For `version="v1"` / `"v2"`, yields `StreamEvent` dicts (see
+ `Runnable.stream_events`). For `version="v3"`, returns a
+ `GraphRunStream` whose typed projections the caller drives by
+ iterating — no background thread.
+
+ !!! warning
+
+ The `version="v3"` API is experimental and may change.
+
+ Builds a `StreamMux` from the built-in transformers, this
+ graph's compile-time `stream_transformers`, and any additional
+ `transformers=` supplied at the call site. `run.output`,
+ `run.interrupted`, and `run.interrupts` work regardless of
+ which transformers are registered.
+
+ Note:
+ Nesting v1 `stream(stream_mode="messages")` inside a node
+ of a `stream_events(version="v3")` run is not fully
+ supported. The outer v3 messages handler reroutes
+ `BaseChatModel.invoke` through the v2 event protocol, so
+ the inner v1 handler does not see `on_llm_new_token`
+ chunks. The inner stream still yields a finalized message
+ via `on_llm_end`. Use `stream_events(version="v3")` for the
+ inner graph as well, or call `chat_model.stream(...)`
+ explicitly, to get token-level streaming.
+
+ Args:
+ input: Graph input.
+ config: Optional runnable config.
+ version: Streaming-event schema version. `"v3"` selects the
+ content-block-centric streaming protocol.
+ interrupt_before: Nodes to interrupt before, if any. Only
+ used for `version="v3"`.
+ interrupt_after: Nodes to interrupt after, if any. Only
+ used for `version="v3"`.
+ control: Optional run control used to request cooperative
+ drain. Only used for `version="v3"`.
+ transformers: Extra transformer classes or configured
+ factories appended after compile-time
+ `stream_transformers`. Factories are called as
+ `factory(scope)` so they can propagate to subgraph
+ scopes. Only used for `version="v3"`.
+ **kwargs: For `version="v1"`/`"v2"`, forwarded to
+ `Runnable.stream_events`. For `version="v3"`, forwarded
+ to the underlying `stream(...)` call (e.g. `context`,
+ `durability`, `output_keys`, `print_mode`, `debug`).
+ `stream_mode` and `subgraphs` are not accepted under
+ `version="v3"` and raise `TypeError` if supplied; v3
+ owns them.
+
+ Returns:
+ For `version="v3"`, a `GraphRunStream` the caller iterates
+ to drive the run. Otherwise an `Iterator[StreamEvent]`.
+ """
+ if version == "v3":
+ _reject_v3_invariant_kwargs(kwargs)
+ return self._pregel_stream_v3(
+ input,
+ config,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ transformers=transformers,
+ **kwargs,
+ )
+ return super().stream_events(input, config, version=version, **kwargs)
+
+ @overload
+ def astream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Awaitable[Any]: ...
+
+ def astream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ """Async variant of `stream_events`.
+
+ For `version="v3"`, returns an `AsyncGraphRunStream` whose
+ projections can be awaited concurrently; each subscribed cursor
+ drives the pump when its buffer is empty. The same nesting
+ limitation as the sync path applies — see `stream_events` for
+ details.
+
+ !!! warning
+
+ The `version="v3"` API is experimental and may change.
+
+ See `stream_events` for full argument and return documentation.
+ """
+ if version == "v3":
+ _reject_v3_invariant_kwargs(kwargs)
+ return self._apregel_stream_v3(
+ input,
+ config,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ transformers=transformers,
+ **kwargs,
+ )
+ return super().astream_events(input, config, version=version, **kwargs)
+
+ @overload
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: Literal["values"] = ...,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[OutputT]: ...
+
+ @overload
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> list[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Run the graph with a single input and config.
+
+ Args:
+ input: The input data for the graph. It can be a dictionary or any other type.
+ config: The configuration for the graph run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The stream mode for the graph run.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The output keys to retrieve from the graph run.
+ interrupt_before: The nodes to interrupt the graph run before.
+ interrupt_after: The nodes to interrupt the graph run after.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts when
+ `stream_mode` is not `"values"`.
+ **kwargs: Additional keyword arguments to pass to the graph run.
+
+ Returns:
+ The output of the graph run. If `stream_mode` is `"values"`, it returns the latest output.
+ If `stream_mode` is not `"values"`, it returns a list of output chunks.
+ """
+ output_keys = output_keys if output_keys is not None else self.output_channels
+
+ latest: dict[str, Any] | Any = None
+ chunks: list[dict[str, Any] | Any] = []
+ interrupts: list[Interrupt] = []
+
+ if version == "v2":
+ # v2: values stream parts carry interrupts directly
+ for chunk in self.stream(
+ input,
+ config,
+ context=context,
+ stream_mode="values" if stream_mode == "values" else stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ version=version,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ latest = chunk["data"]
+ if chunk_ints := chunk.get("interrupts", ()):
+ interrupts.extend(chunk_ints) # type: ignore[arg-type]
+ else:
+ chunks.append(chunk)
+ else:
+ # v1: collect interrupts from updates stream
+ for chunk in self.stream(
+ input,
+ config,
+ context=context,
+ stream_mode=(
+ ["updates", "values"] if stream_mode == "values" else stream_mode
+ ),
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ if len(chunk) == 2:
+ mode, payload = cast(tuple[StreamMode, Any], chunk)
+ else:
+ _, mode, payload = cast(
+ tuple[tuple[str, ...], StreamMode, Any], chunk
+ )
+ if (
+ mode == "updates"
+ and isinstance(payload, dict)
+ and (ints := payload.get(INTERRUPT)) is not None
+ ):
+ interrupts.extend(ints)
+ elif mode == "values":
+ latest = payload
+ else:
+ chunks.append(chunk)
+
+ if stream_mode == "values":
+ if version == "v2":
+ return GraphOutput(value=latest, interrupts=tuple(interrupts))
+ if interrupts:
+ return (
+ {**latest, INTERRUPT: interrupts}
+ if isinstance(latest, dict)
+ else {INTERRUPT: interrupts}
+ )
+ return latest
+ else:
+ return chunks
+
+ @overload
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: Literal["values"] = ...,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[OutputT]: ...
+
+ @overload
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> list[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Asynchronously run the graph with a single input and config.
+
+ Args:
+ input: The input data for the graph. It can be a dictionary or any other type.
+ config: The configuration for the graph run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The stream mode for the graph run.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The output keys to retrieve from the graph run.
+ interrupt_before: The nodes to interrupt the graph run before.
+ interrupt_after: The nodes to interrupt the graph run after.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts when
+ `stream_mode` is not `"values"`.
+ **kwargs: Additional keyword arguments to pass to the graph run.
+
+ Returns:
+ The output of the graph run. If `stream_mode` is `"values"`, it returns the latest output.
+ If `stream_mode` is not `"values"`, it returns a list of output chunks.
+ """
+ output_keys = output_keys if output_keys is not None else self.output_channels
+
+ latest: dict[str, Any] | Any = None
+ chunks: list[dict[str, Any] | Any] = []
+ interrupts: list[Interrupt] = []
+
+ if version == "v2":
+ # v2: values stream parts carry interrupts directly
+ async for chunk in self.astream(
+ input,
+ config,
+ context=context,
+ stream_mode="values" if stream_mode == "values" else stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ version=version,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ latest = chunk["data"]
+ if chunk_ints := chunk.get("interrupts", ()):
+ interrupts.extend(chunk_ints) # type: ignore[arg-type]
+ else:
+ chunks.append(chunk)
+ else:
+ # v1: collect interrupts from updates stream
+ async for chunk in self.astream(
+ input,
+ config,
+ context=context,
+ stream_mode=(
+ ["updates", "values"] if stream_mode == "values" else stream_mode
+ ),
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ if len(chunk) == 2:
+ mode, payload = cast(tuple[StreamMode, Any], chunk)
+ else:
+ _, mode, payload = cast(
+ tuple[tuple[str, ...], StreamMode, Any], chunk
+ )
+ if (
+ mode == "updates"
+ and isinstance(payload, dict)
+ and (ints := payload.get(INTERRUPT)) is not None
+ ):
+ interrupts.extend(ints)
+ elif mode == "values":
+ latest = payload
+ else:
+ chunks.append(chunk)
+
+ if stream_mode == "values":
+ if version == "v2":
+ return GraphOutput(value=latest, interrupts=tuple(interrupts))
+ if interrupts:
+ return (
+ {**latest, INTERRUPT: interrupts}
+ if isinstance(latest, dict)
+ else {INTERRUPT: interrupts}
+ )
+ return latest
+ else:
+ return chunks
+
+ def clear_cache(self, nodes: Sequence[str] | None = None) -> None:
+ """Clear the cache for the given nodes."""
+ if not self.cache:
+ raise ValueError("No cache is set for this graph. Cannot clear cache.")
+ nodes = nodes or self.nodes.keys()
+ # collect namespaces to clear
+ namespaces: list[tuple[str, ...]] = []
+ for node in nodes:
+ if node in self.nodes:
+ namespaces.append(
+ (
+ CACHE_NS_WRITES,
+ (identifier(self.nodes[node]) or "__dynamic__"),
+ node,
+ ),
+ )
+ # clear cache
+ self.cache.clear(namespaces)
+
+ async def aclear_cache(self, nodes: Sequence[str] | None = None) -> None:
+ """Asynchronously clear the cache for the given nodes."""
+ if not self.cache:
+ raise ValueError("No cache is set for this graph. Cannot clear cache.")
+ nodes = nodes or self.nodes.keys()
+ # collect namespaces to clear
+ namespaces: list[tuple[str, ...]] = []
+ for node in nodes:
+ if node in self.nodes:
+ namespaces.append(
+ (
+ CACHE_NS_WRITES,
+ (identifier(self.nodes[node]) or "__dynamic__"),
+ node,
+ ),
+ )
+ # clear cache
+ await self.cache.aclear(namespaces)
+
+
+def _trigger_to_nodes(nodes: dict[str, PregelNode]) -> Mapping[str, Sequence[str]]:
+ """Index from a trigger to nodes that depend on it."""
+ trigger_to_nodes: defaultdict[str, list[str]] = defaultdict(list)
+ for name, node in nodes.items():
+ for trigger in node.triggers:
+ trigger_to_nodes[trigger].append(name)
+ return dict(trigger_to_nodes)
+
+
+def _output(
+ stream_mode: StreamMode | Sequence[StreamMode],
+ print_mode: StreamMode | Sequence[StreamMode],
+ stream_subgraphs: bool,
+ getter: Callable[[], tuple[tuple[str, ...], str, Any]],
+ empty_exc: type[Exception],
+ version: Literal["v1", "v2"] = "v1",
+ output_mapper: Callable[[Any], Any] | None = None,
+ state_mapper: Callable[[Any], Any] | None = None,
+) -> Iterator:
+ while True:
+ try:
+ ns, mode, payload = getter()
+ except empty_exc:
+ break
+ if mode in print_mode:
+ if stream_subgraphs and ns:
+ print(
+ " ".join(
+ (
+ get_bolded_text(f"[{mode}]"),
+ get_colored_text(f"[graph={ns}]", color="yellow"),
+ repr(payload),
+ )
+ )
+ )
+ else:
+ print(
+ " ".join(
+ (
+ get_bolded_text(f"[{mode}]"),
+ repr(payload),
+ )
+ )
+ )
+ if mode in stream_mode:
+ if version == "v2":
+ if mode == "values":
+ # pop __interrupt__ into typed field, coerce data
+ ints: tuple[Interrupt, ...] = ()
+ if isinstance(payload, dict):
+ ints = payload.pop(INTERRUPT, ())
+ if output_mapper:
+ payload = output_mapper(payload)
+ yield {"type": mode, "ns": ns, "data": payload, "interrupts": ints}
+ elif mode in ("checkpoints", "debug"):
+ # coerce state values in checkpoint/debug payloads
+ if state_mapper:
+ _coerce_checkpoint_values(payload, state_mapper)
+ yield {"type": mode, "ns": ns, "data": payload}
+ else:
+ yield {"type": mode, "ns": ns, "data": payload}
+ elif stream_subgraphs and isinstance(stream_mode, list):
+ yield (ns, mode, payload)
+ elif isinstance(stream_mode, list):
+ yield (mode, payload)
+ elif stream_subgraphs:
+ yield (ns, payload)
+ else:
+ yield payload
+
+
+def _coerce_checkpoint_values(payload: Any, mapper: Callable[[Any], Any]) -> None:
+ """Coerce `values` dicts inside checkpoint or debug payloads in-place.
+
+ Skips the initial checkpoint (where next contains ``__start__``) because
+ not all channels are populated yet and coercion would fail.
+ """
+ _START = "__start__"
+ # debug wrapper: {"type": "checkpoint", "payload": {"values": dict, ...}}
+ if (
+ isinstance(payload, dict)
+ and payload.get("type") == "checkpoint"
+ and isinstance(payload.get("payload"), dict)
+ and isinstance(payload["payload"].get("values"), dict)
+ and _START not in payload["payload"].get("next", ())
+ ):
+ payload["payload"]["values"] = mapper(payload["payload"]["values"])
+ # direct checkpoint payload: {"values": dict, ...}
+ elif (
+ isinstance(payload, dict)
+ and isinstance(payload.get("values"), dict)
+ and _START not in payload.get("next", ())
+ ):
+ payload["values"] = mapper(payload["values"])
+
+
+def _resolve_parent_ns(
+ graph_config: RunnableConfig | None, call_config: RunnableConfig | None
+) -> tuple[str, ...]:
+ """Return the checkpoint namespace the caller is running under.
+
+ `stream_events(version="v3")` uses this to scope its native projections
+ (`ValuesTransformer`, `MessagesTransformer`) to events emitted at
+ the run's own level. A root call resolves to `()`; a call made
+ from inside a node carries the outer graph's task namespace so the
+ projection still matches its own root-level events.
+ """
+ merged = ensure_config(graph_config, call_config)
+ ns = merged.get(CONF, {}).get(CONFIG_KEY_CHECKPOINT_NS)
+ if not ns:
+ return ()
+ return tuple(ns.split(NS_SEP))
+
+
+def _build_server_info(
+ config: RunnableConfig, parent_runtime: Runtime[Any]
+) -> ServerInfo | None:
+ """Build ServerInfo from config configurable.
+
+ The server puts assistant_id/graph_id in config configurable and the
+ authenticated user dict in configurable["langgraph_auth_user"].
+ """
+ configurable = config.get(CONF) or {}
+ assistant_id = configurable.get("assistant_id")
+ graph_id = configurable.get("graph_id")
+
+ # Read authenticated user from configurable (set by LangGraph Server).
+ # We prefer isinstance(BaseUser) but fall back to hasattr("identity")
+ # because the server's ProxyUser provides `permissions` via __getattr__,
+ # which Python's runtime_checkable Protocol check doesn't see.
+ auth_user_data = configurable.get("langgraph_auth_user")
+ user: BaseUser | None = None
+ if auth_user_data is not None:
+ if isinstance(auth_user_data, BaseUser) or hasattr(auth_user_data, "identity"):
+ user = cast(BaseUser, auth_user_data)
+
+ if assistant_id is not None or graph_id is not None or user is not None:
+ return ServerInfo(
+ assistant_id=str(assistant_id) if assistant_id else "",
+ graph_id=str(graph_id) if graph_id else "",
+ user=user,
+ )
+ return None
+
+
+def _coerce_context(
+ context_schema: type[ContextT] | None, context: Any
+) -> ContextT | None:
+ """Coerce context input to the appropriate schema type.
+
+ If context is a dict and context_schema is a dataclass or pydantic model, we coerce.
+ Else, we return the context as-is.
+
+ Args:
+ context_schema: The schema type to coerce to (BaseModel, dataclass, or TypedDict)
+ context: The context value to coerce
+
+ Returns:
+ The coerced context value or None if context is None
+ """
+ if context is None:
+ return None
+
+ if context_schema is None:
+ return context
+
+ schema_is_class = issubclass(context_schema, BaseModel) or is_dataclass(
+ context_schema
+ )
+ if isinstance(context, dict) and schema_is_class:
+ return context_schema(**context) # type: ignore[misc]
+
+ return cast(ContextT, context)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/remote.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/remote.py
new file mode 100644
index 0000000000000000000000000000000000000000..973768a4ad4444dbe3ba7b2275ac34c78bc13671
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/remote.py
@@ -0,0 +1,1191 @@
+from __future__ import annotations
+
+import logging
+from collections.abc import AsyncIterator, Iterator, Sequence
+from dataclasses import asdict
+from typing import (
+ Any,
+ Literal,
+ cast,
+ overload,
+)
+from uuid import UUID
+
+import langsmith as ls
+from langchain_core.runnables import RunnableConfig
+from langchain_core.runnables.graph import (
+ Edge as DrawableEdge,
+)
+from langchain_core.runnables.graph import (
+ Graph as DrawableGraph,
+)
+from langchain_core.runnables.graph import (
+ Node as DrawableNode,
+)
+from langgraph.checkpoint.base import CheckpointMetadata
+from langgraph_sdk.client import (
+ LangGraphClient,
+ SyncLangGraphClient,
+ get_client,
+ get_sync_client,
+)
+from langgraph_sdk.schema import (
+ Checkpoint,
+ Context,
+ QueryParamTypes,
+ ThreadState,
+)
+from langgraph_sdk.schema import (
+ Command as CommandSDK,
+)
+from langgraph_sdk.schema import (
+ StreamMode as StreamModeSDK,
+)
+from typing_extensions import Self
+
+from langgraph._internal._config import merge_configs
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_TASK_ID,
+ INTERRUPT,
+ NS_SEP,
+)
+from langgraph.errors import GraphInterrupt, ParentCommand
+from langgraph.pregel.protocol import PregelProtocol, StreamProtocol
+from langgraph.types import (
+ All,
+ Command,
+ GraphOutput,
+ Interrupt,
+ PregelTask,
+ StateSnapshot,
+ StreamMode,
+ StreamPart,
+)
+
+logger = logging.getLogger(__name__)
+
+__all__ = ("RemoteGraph", "RemoteException")
+
+_CONF_DROPLIST = frozenset(
+ (
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_TASK_ID,
+ ),
+)
+
+
+def _sanitize_config_value(v: Any) -> Any:
+ """Recursively sanitize a config value to ensure it contains only primitives."""
+ if isinstance(v, (str, int, float, bool, UUID)):
+ return v
+ elif isinstance(v, dict):
+ sanitized_dict = {}
+ for k, val in v.items():
+ if isinstance(k, str):
+ sanitized_value = _sanitize_config_value(val)
+ if sanitized_value is not None:
+ sanitized_dict[k] = sanitized_value
+ return sanitized_dict
+ elif isinstance(v, (list, tuple)):
+ sanitized_list = []
+ for item in v:
+ sanitized_item = _sanitize_config_value(item)
+ if sanitized_item is not None:
+ sanitized_list.append(sanitized_item)
+ return sanitized_list
+ return None
+
+
+class RemoteException(Exception):
+ """Exception raised when an error occurs in the remote graph."""
+
+ pass
+
+
+class RemoteGraph(PregelProtocol):
+ """The `RemoteGraph` class is a client implementation for calling remote
+ APIs that implement the LangGraph Server API specification.
+
+ For example, the `RemoteGraph` class can be used to call APIs from deployments
+ on LangSmith Deployment.
+
+ `RemoteGraph` behaves the same way as a `Graph` and can be used directly as
+ a node in another `Graph`.
+ """
+
+ assistant_id: str
+ name: str | None
+
+ def __init__(
+ self,
+ assistant_id: str, # graph_id
+ /,
+ *,
+ url: str | None = None,
+ api_key: str | None = None,
+ headers: dict[str, str] | None = None,
+ client: LangGraphClient | None = None,
+ sync_client: SyncLangGraphClient | None = None,
+ config: RunnableConfig | None = None,
+ name: str | None = None,
+ distributed_tracing: bool = False,
+ ):
+ """Specify `url`, `api_key`, and/or `headers` to create default sync and async clients.
+
+ If `client` or `sync_client` are provided, they will be used instead of the default clients.
+ See `LangGraphClient` and `SyncLangGraphClient` for details on the default clients. At least
+ one of `url`, `client`, or `sync_client` must be provided.
+
+ Args:
+ assistant_id: The assistant ID or graph name of the remote graph to use.
+ url: The URL of the remote API.
+ api_key: The API key to use for authentication. If not provided, it will be read from the environment (`LANGGRAPH_API_KEY`, `LANGSMITH_API_KEY`, or `LANGCHAIN_API_KEY`).
+ headers: Additional headers to include in the requests.
+ client: A `LangGraphClient` instance to use instead of creating a default client.
+ sync_client: A `SyncLangGraphClient` instance to use instead of creating a default client.
+ config: An optional `RunnableConfig` instance with additional configuration.
+ name: Human-readable name to attach to the RemoteGraph instance.
+ This is useful for adding `RemoteGraph` as a subgraph via `graph.add_node(remote_graph)`.
+ If not provided, defaults to the assistant ID.
+ distributed_tracing: Whether to enable sending LangSmith distributed tracing headers.
+ """
+ self.assistant_id = assistant_id
+ if name is None:
+ self.name = assistant_id
+ else:
+ self.name = name
+ self.config = config
+ self.distributed_tracing = distributed_tracing
+
+ if client is None and url is not None:
+ client = get_client(url=url, api_key=api_key, headers=headers)
+ self.client = client
+
+ if sync_client is None and url is not None:
+ sync_client = get_sync_client(url=url, api_key=api_key, headers=headers)
+ self.sync_client = sync_client
+
+ def _validate_client(self) -> LangGraphClient:
+ if self.client is None:
+ raise ValueError(
+ "Async client is not initialized: please provide `url` or `client` when initializing `RemoteGraph`."
+ )
+ return self.client
+
+ def _validate_sync_client(self) -> SyncLangGraphClient:
+ if self.sync_client is None:
+ raise ValueError(
+ "Sync client is not initialized: please provide `url` or `sync_client` when initializing `RemoteGraph`."
+ )
+ return self.sync_client
+
+ def copy(self, update: dict[str, Any]) -> Self:
+ attrs = {**self.__dict__, **update}
+ return self.__class__(attrs.pop("assistant_id"), **attrs)
+
+ def with_config(self, config: RunnableConfig | None = None, **kwargs: Any) -> Self:
+ return self.copy(
+ {"config": merge_configs(self.config, config, cast(RunnableConfig, kwargs))}
+ )
+
+ def _get_drawable_nodes(
+ self, graph: dict[str, list[dict[str, Any]]]
+ ) -> dict[str, DrawableNode]:
+ nodes = {}
+ for node in graph["nodes"]:
+ node_id = str(node["id"])
+ node_data = node.get("data", {})
+
+ # Get node name from node_data if available. If not, use node_id.
+ node_name = node.get("name")
+ if node_name is None:
+ if isinstance(node_data, dict):
+ node_name = node_data.get("name", node_id)
+ else:
+ node_name = node_id
+
+ nodes[node_id] = DrawableNode(
+ id=node_id,
+ name=node_name,
+ data=node_data,
+ metadata=node.get("metadata"),
+ )
+ return nodes
+
+ def get_graph(
+ self,
+ config: RunnableConfig | None = None,
+ *,
+ xray: int | bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> DrawableGraph:
+ """Get graph by graph name.
+
+ This method calls `GET /assistants/{assistant_id}/graph`.
+
+ Args:
+ config: This parameter is not used.
+ xray: Include graph representation of subgraphs. If an integer
+ value is provided, only subgraphs with a depth less than or
+ equal to the value will be included.
+
+ Returns:
+ The graph information for the assistant in JSON format.
+ """
+ sync_client = self._validate_sync_client()
+ graph = sync_client.assistants.get_graph(
+ assistant_id=self.assistant_id,
+ xray=xray,
+ headers=headers,
+ params=params,
+ )
+ return DrawableGraph(
+ nodes=self._get_drawable_nodes(graph),
+ edges=[DrawableEdge(**edge) for edge in graph["edges"]],
+ )
+
+ async def aget_graph(
+ self,
+ config: RunnableConfig | None = None,
+ *,
+ xray: int | bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> DrawableGraph:
+ """Get graph by graph name.
+
+ This method calls `GET /assistants/{assistant_id}/graph`.
+
+ Args:
+ config: This parameter is not used.
+ xray: Include graph representation of subgraphs. If an integer
+ value is provided, only subgraphs with a depth less than or
+ equal to the value will be included.
+
+ Returns:
+ The graph information for the assistant in JSON format.
+ """
+ client = self._validate_client()
+ graph = await client.assistants.get_graph(
+ assistant_id=self.assistant_id,
+ xray=xray,
+ headers=headers,
+ params=params,
+ )
+ return DrawableGraph(
+ nodes=self._get_drawable_nodes(graph),
+ edges=[DrawableEdge(**edge) for edge in graph["edges"]],
+ )
+
+ def _create_state_snapshot(self, state: ThreadState) -> StateSnapshot:
+ tasks: list[PregelTask] = []
+ for task in state["tasks"]:
+ interrupts = tuple(
+ Interrupt(**interrupt) for interrupt in task["interrupts"]
+ )
+
+ tasks.append(
+ PregelTask(
+ id=task["id"],
+ name=task["name"],
+ path=tuple(),
+ error=Exception(task["error"]) if task["error"] else None,
+ interrupts=interrupts,
+ state=(
+ self._create_state_snapshot(task["state"])
+ if task["state"]
+ else (
+ cast(RunnableConfig, {"configurable": task["checkpoint"]})
+ if task["checkpoint"]
+ else None
+ )
+ ),
+ result=task.get("result"),
+ )
+ )
+
+ return StateSnapshot(
+ values=state["values"],
+ next=tuple(state["next"]) if state["next"] else tuple(),
+ config={
+ "configurable": {
+ "thread_id": state["checkpoint"]["thread_id"],
+ "checkpoint_ns": state["checkpoint"]["checkpoint_ns"],
+ "checkpoint_id": state["checkpoint"]["checkpoint_id"],
+ "checkpoint_map": state["checkpoint"].get("checkpoint_map", {}),
+ }
+ },
+ metadata=CheckpointMetadata(**state["metadata"]),
+ created_at=state["created_at"],
+ parent_config=(
+ {
+ "configurable": {
+ "thread_id": state["parent_checkpoint"]["thread_id"],
+ "checkpoint_ns": state["parent_checkpoint"]["checkpoint_ns"],
+ "checkpoint_id": state["parent_checkpoint"]["checkpoint_id"],
+ "checkpoint_map": state["parent_checkpoint"].get(
+ "checkpoint_map", {}
+ ),
+ }
+ }
+ if state["parent_checkpoint"]
+ else None
+ ),
+ tasks=tuple(tasks),
+ interrupts=tuple([i for task in tasks for i in task.interrupts]),
+ )
+
+ def _get_checkpoint(self, config: RunnableConfig | None) -> Checkpoint | None:
+ if config is None:
+ return None
+
+ checkpoint = {}
+
+ if "thread_id" in config["configurable"]:
+ checkpoint["thread_id"] = config["configurable"]["thread_id"]
+ if "checkpoint_ns" in config["configurable"]:
+ checkpoint["checkpoint_ns"] = config["configurable"]["checkpoint_ns"]
+ if "checkpoint_id" in config["configurable"]:
+ checkpoint["checkpoint_id"] = config["configurable"]["checkpoint_id"]
+ if "checkpoint_map" in config["configurable"]:
+ checkpoint["checkpoint_map"] = config["configurable"]["checkpoint_map"]
+
+ return checkpoint if checkpoint else None
+
+ def _get_config(self, checkpoint: Checkpoint) -> RunnableConfig:
+ return {
+ "configurable": {
+ "thread_id": checkpoint["thread_id"],
+ "checkpoint_ns": checkpoint["checkpoint_ns"],
+ "checkpoint_id": checkpoint["checkpoint_id"],
+ "checkpoint_map": checkpoint.get("checkpoint_map", {}),
+ }
+ }
+
+ def _sanitize_config(self, config: RunnableConfig) -> RunnableConfig:
+ """Sanitize the config to remove non-serializable fields."""
+ sanitized: RunnableConfig = {}
+ if "recursion_limit" in config:
+ sanitized["recursion_limit"] = config["recursion_limit"]
+ if "tags" in config:
+ sanitized["tags"] = [tag for tag in config["tags"] if isinstance(tag, str)]
+
+ if "metadata" in config:
+ sanitized["metadata"] = {}
+ for k, v in config["metadata"].items():
+ if (
+ isinstance(k, str)
+ and (sanitized_value := _sanitize_config_value(v)) is not None
+ ):
+ sanitized["metadata"][k] = sanitized_value
+
+ if "configurable" in config:
+ sanitized["configurable"] = {}
+ for k, v in config["configurable"].items():
+ if (
+ isinstance(k, str)
+ and k not in _CONF_DROPLIST
+ and (sanitized_value := _sanitize_config_value(v)) is not None
+ ):
+ sanitized["configurable"][k] = sanitized_value
+
+ return sanitized
+
+ def get_state(
+ self,
+ config: RunnableConfig,
+ *,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> StateSnapshot:
+ """Get the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state/checkpoint` if a
+ checkpoint is specified in the config or `GET /threads/{thread_id}/state`
+ if no checkpoint is specified.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ subgraphs: Include subgraphs in the state.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The latest state of the thread.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+
+ state = sync_client.threads.get_state(
+ thread_id=merged_config["configurable"]["thread_id"],
+ checkpoint=self._get_checkpoint(merged_config),
+ subgraphs=subgraphs,
+ headers=headers,
+ params=params,
+ )
+ return self._create_state_snapshot(state)
+
+ async def aget_state(
+ self,
+ config: RunnableConfig,
+ *,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> StateSnapshot:
+ """Get the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state/checkpoint` if a
+ checkpoint is specified in the config or `GET /threads/{thread_id}/state`
+ if no checkpoint is specified.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ subgraphs: Include subgraphs in the state.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The latest state of the thread.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+
+ state = await client.threads.get_state(
+ thread_id=merged_config["configurable"]["thread_id"],
+ checkpoint=self._get_checkpoint(merged_config),
+ subgraphs=subgraphs,
+ headers=headers,
+ params=params,
+ )
+ return self._create_state_snapshot(state)
+
+ def get_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Iterator[StateSnapshot]:
+ """Get the state history of a thread.
+
+ This method calls `POST /threads/{thread_id}/history`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ filter: Metadata to filter on.
+ before: A `RunnableConfig` that includes checkpoint metadata.
+ limit: Max number of states to return.
+
+ Returns:
+ States of the thread.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+
+ states = sync_client.threads.get_history(
+ thread_id=merged_config["configurable"]["thread_id"],
+ limit=limit if limit else 10,
+ before=self._get_checkpoint(before),
+ metadata=filter,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ for state in states:
+ yield self._create_state_snapshot(state)
+
+ async def aget_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> AsyncIterator[StateSnapshot]:
+ """Get the state history of a thread.
+
+ This method calls `POST /threads/{thread_id}/history`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ filter: Metadata to filter on.
+ before: A `RunnableConfig` that includes checkpoint metadata.
+ limit: Max number of states to return.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ States of the thread.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+
+ states = await client.threads.get_history(
+ thread_id=merged_config["configurable"]["thread_id"],
+ limit=limit if limit else 10,
+ before=self._get_checkpoint(before),
+ metadata=filter,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ for state in states:
+ yield self._create_state_snapshot(state)
+
+ def bulk_update_state(
+ self,
+ config: RunnableConfig,
+ updates: list[tuple[dict[str, Any] | None, str | None]],
+ ) -> RunnableConfig:
+ raise NotImplementedError
+
+ async def abulk_update_state(
+ self,
+ config: RunnableConfig,
+ updates: list[tuple[dict[str, Any] | None, str | None]],
+ ) -> RunnableConfig:
+ raise NotImplementedError
+
+ def update_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ *,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> RunnableConfig:
+ """Update the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ values: Values to update to the state.
+ as_node: Update the state as if this node had just executed.
+
+ Returns:
+ `RunnableConfig` for the updated thread.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+
+ response: dict = sync_client.threads.update_state( # type: ignore
+ thread_id=merged_config["configurable"]["thread_id"],
+ values=values,
+ as_node=as_node,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ return self._get_config(response["checkpoint"])
+
+ async def aupdate_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ *,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> RunnableConfig:
+ """Update the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ values: Values to update to the state.
+ as_node: Update the state as if this node had just executed.
+
+ Returns:
+ `RunnableConfig` for the updated thread.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+
+ response: dict = await client.threads.update_state( # type: ignore
+ thread_id=merged_config["configurable"]["thread_id"],
+ values=values,
+ as_node=as_node,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ return self._get_config(response["checkpoint"])
+
+ def _get_stream_modes(
+ self,
+ stream_mode: StreamMode | list[StreamMode] | None,
+ config: RunnableConfig | None,
+ default: StreamMode = "updates",
+ ) -> tuple[list[StreamModeSDK], list[StreamModeSDK], bool, StreamProtocol | None]:
+ """Return a tuple of the final list of stream modes sent to the
+ remote graph and a boolean flag indicating if stream mode 'updates'
+ was present in the original list of stream modes.
+
+ 'updates' mode is added to the list of stream modes so that interrupts
+ can be detected in the remote graph.
+ """
+ updated_stream_modes: list[StreamModeSDK] = []
+ req_single = True
+ # coerce to list, or add default stream mode
+ if stream_mode:
+ if isinstance(stream_mode, str):
+ updated_stream_modes.append(stream_mode)
+ else:
+ req_single = False
+ updated_stream_modes.extend(stream_mode)
+ else:
+ updated_stream_modes.append(default)
+ requested_stream_modes = updated_stream_modes.copy()
+ # add any from parent graph
+ stream: StreamProtocol | None = (
+ (config or {}).get(CONF, {}).get(CONFIG_KEY_STREAM)
+ )
+ if stream:
+ updated_stream_modes.extend(stream.modes)
+ # map "messages" to "messages-tuple"
+ if "messages" in updated_stream_modes:
+ updated_stream_modes.remove("messages")
+ updated_stream_modes.append("messages-tuple")
+
+ # if requested "messages-tuple",
+ # map to "messages" in requested_stream_modes
+ if "messages-tuple" in requested_stream_modes:
+ requested_stream_modes.remove("messages-tuple")
+ requested_stream_modes.append("messages")
+
+ # add 'updates' mode if not present
+ if "updates" not in updated_stream_modes:
+ updated_stream_modes.append("updates")
+
+ # remove 'events', as it's not supported in Pregel
+ if "events" in updated_stream_modes:
+ updated_stream_modes.remove("events")
+ return (updated_stream_modes, requested_stream_modes, req_single, stream)
+
+ @overload
+ def stream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> Iterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any] | Any]: ...
+
+ def stream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any] | Any]:
+ """Create a run and stream the results.
+
+ This method calls `POST /threads/{thread_id}/runs/stream` if a `thread_id`
+ is specified in the `configurable` field of the config or
+ `POST /runs/stream` otherwise.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ stream_mode: Stream mode(s) to use.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ subgraphs: Stream from subgraphs.
+ headers: Additional headers to pass to the request.
+ **kwargs: Additional params to pass to client.runs.stream.
+
+ Yields:
+ The output of the graph.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+ sanitized_config = self._sanitize_config(merged_config)
+ stream_modes, requested, req_single, stream = self._get_stream_modes(
+ stream_mode, config
+ )
+ if isinstance(input, Command):
+ command: CommandSDK | None = cast(CommandSDK, asdict(input))
+ input = None
+ else:
+ command = None
+ thread_id = sanitized_config.get("configurable", {}).pop("thread_id", None)
+
+ for chunk in sync_client.runs.stream(
+ thread_id=thread_id,
+ assistant_id=self.assistant_id,
+ input=input,
+ command=command,
+ config=sanitized_config,
+ context=context,
+ stream_mode=stream_modes,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ stream_subgraphs=subgraphs or stream is not None,
+ if_not_exists="create",
+ headers=(
+ _merge_tracing_headers(headers) if self.distributed_tracing else headers
+ ),
+ params=params,
+ **kwargs,
+ ):
+ # split mode and ns
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ # raise ParentCommand exception for command events
+ if mode == "command" and chunk.data.get("graph") == Command.PARENT:
+ raise ParentCommand(Command(**chunk.data))
+ # prepend caller ns (as it is not passed to remote graph)
+ if caller_ns := (config or {}).get(CONF, {}).get(CONFIG_KEY_CHECKPOINT_NS):
+ caller_ns = tuple(caller_ns.split(NS_SEP))
+ ns = caller_ns + ns
+ # stream to parent stream
+ if stream is not None and mode in stream.modes:
+ stream((ns, mode, chunk.data))
+ # raise interrupt or errors
+ if chunk.event.startswith("updates"):
+ if isinstance(chunk.data, dict) and INTERRUPT in chunk.data:
+ if caller_ns:
+ raise GraphInterrupt(
+ [Interrupt(**i) for i in chunk.data[INTERRUPT]]
+ )
+ elif chunk.event.startswith("error"):
+ raise RemoteException(chunk.data)
+ # filter for what was actually requested
+ if mode not in requested:
+ continue
+
+ if chunk.event.startswith("messages"):
+ chunk = chunk._replace(data=tuple(chunk.data))
+
+ # emit chunk
+ if version == "v2":
+ ints: tuple[Interrupt, ...] = ()
+ if mode == "values" and isinstance(chunk.data, dict):
+ ints = tuple(
+ Interrupt(**i) if isinstance(i, dict) else i
+ for i in chunk.data.pop(INTERRUPT, ())
+ )
+ yield {"type": mode, "ns": ns, "data": chunk.data, "interrupts": ints}
+ elif subgraphs:
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ if req_single:
+ yield ns, chunk.data
+ else:
+ yield ns, mode, chunk.data
+ elif req_single:
+ yield chunk.data
+ else:
+ yield chunk
+
+ @overload
+ def astream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamPart]: ...
+
+ @overload
+ def astream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any] | Any]: ...
+
+ async def astream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any] | Any]:
+ """Create a run and stream the results.
+
+ This method calls `POST /threads/{thread_id}/runs/stream` if a `thread_id`
+ is specified in the `configurable` field of the config or
+ `POST /runs/stream` otherwise.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ stream_mode: Stream mode(s) to use.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ subgraphs: Stream from subgraphs.
+ headers: Additional headers to pass to the request.
+ **kwargs: Additional params to pass to client.runs.stream.
+
+ Yields:
+ The output of the graph.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+ sanitized_config = self._sanitize_config(merged_config)
+ stream_modes, requested, req_single, stream = self._get_stream_modes(
+ stream_mode, config
+ )
+ if isinstance(input, Command):
+ command: CommandSDK | None = cast(CommandSDK, asdict(input))
+ input = None
+ else:
+ command = None
+ thread_id = sanitized_config.get("configurable", {}).pop("thread_id", None)
+
+ async for chunk in client.runs.stream(
+ thread_id=thread_id,
+ assistant_id=self.assistant_id,
+ input=input,
+ command=command,
+ config=sanitized_config,
+ context=context,
+ stream_mode=stream_modes,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ stream_subgraphs=subgraphs or stream is not None,
+ if_not_exists="create",
+ headers=(
+ _merge_tracing_headers(headers) if self.distributed_tracing else headers
+ ),
+ params=params,
+ **kwargs,
+ ):
+ # split mode and ns
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ # raise ParentCommand exception for command events
+ if mode == "command" and chunk.data.get("graph") == Command.PARENT:
+ raise ParentCommand(Command(**chunk.data))
+ # prepend caller ns (as it is not passed to remote graph)
+ if caller_ns := (config or {}).get(CONF, {}).get(CONFIG_KEY_CHECKPOINT_NS):
+ caller_ns = tuple(caller_ns.split(NS_SEP))
+ ns = caller_ns + ns
+ # stream to parent stream
+ if stream is not None and mode in stream.modes:
+ stream((ns, mode, chunk.data))
+ # raise interrupt or errors
+ if chunk.event.startswith("updates"):
+ if isinstance(chunk.data, dict) and INTERRUPT in chunk.data:
+ if caller_ns:
+ raise GraphInterrupt(
+ [Interrupt(**i) for i in chunk.data[INTERRUPT]]
+ )
+ elif chunk.event.startswith("error"):
+ raise RemoteException(chunk.data)
+ # filter for what was actually requested
+ if mode not in requested:
+ continue
+
+ if chunk.event.startswith("messages"):
+ chunk = chunk._replace(data=tuple(chunk.data))
+
+ # emit chunk
+ if version == "v2":
+ ints: tuple[Interrupt, ...] = ()
+ if mode == "values" and isinstance(chunk.data, dict):
+ ints = tuple(
+ Interrupt(**i) if isinstance(i, dict) else i
+ for i in chunk.data.pop(INTERRUPT, ())
+ )
+ yield {"type": mode, "ns": ns, "data": chunk.data, "interrupts": ints}
+ elif subgraphs:
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ if req_single:
+ yield ns, chunk.data
+ else:
+ yield ns, mode, chunk.data
+ elif req_single:
+ yield chunk.data
+ else:
+ yield chunk
+
+ async def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"],
+ include_names: Sequence[All] | None = None,
+ include_types: Sequence[All] | None = None,
+ include_tags: Sequence[All] | None = None,
+ exclude_names: Sequence[All] | None = None,
+ exclude_types: Sequence[All] | None = None,
+ exclude_tags: Sequence[All] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ raise NotImplementedError
+
+ @overload
+ def invoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[dict[str, Any]]: ...
+
+ @overload
+ def invoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ def invoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Create a run, wait until it finishes and return the final state.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ headers: Additional headers to pass to the request.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts.
+ **kwargs: Additional params to pass to RemoteGraph.stream.
+
+ Returns:
+ The output of the graph.
+ """
+ for chunk in self.stream( # type: ignore[misc, call-overload]
+ input,
+ config=config,
+ context=context,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ headers=headers,
+ stream_mode="values",
+ params=params,
+ version=version,
+ **kwargs,
+ ):
+ pass
+ try:
+ if version == "v2":
+ return GraphOutput(
+ value=chunk["data"],
+ interrupts=tuple(chunk.get("interrupts", ())),
+ )
+ return chunk
+ except UnboundLocalError:
+ logger.warning("No events received from remote graph")
+ return None
+
+ @overload
+ async def ainvoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[dict[str, Any]]: ...
+
+ @overload
+ async def ainvoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ async def ainvoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Create a run, wait until it finishes and return the final state.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ headers: Additional headers to pass to the request.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts.
+ **kwargs: Additional params to pass to RemoteGraph.astream.
+
+ Returns:
+ The output of the graph.
+ """
+ async for chunk in self.astream( # type: ignore[misc, call-overload]
+ input,
+ config=config,
+ context=context,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ headers=headers,
+ stream_mode="values",
+ params=params,
+ version=version,
+ **kwargs,
+ ):
+ pass
+ try:
+ if version == "v2":
+ return GraphOutput(
+ value=chunk["data"],
+ interrupts=tuple(chunk.get("interrupts", ())),
+ )
+ return chunk
+ except UnboundLocalError:
+ logger.warning("No events received from remote graph")
+ return None
+
+
+def _merge_tracing_headers(headers: dict[str, str] | None) -> dict[str, str] | None:
+ if rt := ls.get_current_run_tree():
+ tracing_headers = rt.to_headers()
+ if headers:
+ if "baggage" in headers:
+ tracing_headers["baggage"] = (
+ f"{headers['baggage']},{tracing_headers['baggage']}"
+ )
+ headers.update(tracing_headers)
+ else:
+ headers = tracing_headers
+ return headers
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..39a36df68787da3cf33bbfd8a9ca8ab8b14874a2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/types.py
@@ -0,0 +1,38 @@
+"""Re-export types moved to langgraph.types"""
+
+from langgraph.types import (
+ All,
+ CachePolicy,
+ PregelExecutableTask,
+ PregelTask,
+ RetryPolicy,
+ StateSnapshot,
+ StateUpdate,
+ StreamMode,
+ StreamWriter,
+ default_retry_on,
+)
+
+__all__ = [
+ "All",
+ "StateUpdate",
+ "CachePolicy",
+ "PregelExecutableTask",
+ "PregelTask",
+ "RetryPolicy",
+ "StateSnapshot",
+ "StreamMode",
+ "StreamWriter",
+ "default_retry_on",
+]
+
+from warnings import warn
+
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+
+warn(
+ "Importing from langgraph.pregel.types is deprecated. "
+ "Please use 'from langgraph.types import ...' instead.",
+ LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+)