google-cloud-agentplatform 2.10.0__tar.gz → 2.11.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. {google_cloud_agentplatform-2.10.0/google_cloud_agentplatform.egg-info → google_cloud_agentplatform-2.11.0}/PKG-INFO +1 -1
  2. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_common.py +1 -0
  3. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_metric_loaders.py +1 -1
  4. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_prompt_optimizer_utils.py +7 -6
  5. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_runtimes_utils.py +203 -9
  6. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_transformers.py +1 -0
  7. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/client.py +25 -0
  8. google_cloud_agentplatform-2.11.0/agentplatform/_genai/detections.py +214 -0
  9. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/evals.py +383 -52
  10. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/memory_banks.py +3 -0
  11. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/prompts.py +4 -4
  12. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/runtimes.py +2 -0
  13. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/types/__init__.py +65 -3
  14. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/types/common.py +724 -133
  15. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/frameworks/adk.py +94 -21
  16. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/frameworks/ag2.py +37 -14
  17. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/version.py +1 -1
  18. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0/google_cloud_agentplatform.egg-info}/PKG-INFO +1 -1
  19. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/google_cloud_agentplatform.egg-info/SOURCES.txt +1 -0
  20. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/LICENSE +0 -0
  21. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/README.md +0 -0
  22. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/__init__.py +0 -0
  23. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/__init__.py +0 -0
  24. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_bigquery_utils.py +0 -0
  25. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_datasets_utils.py +0 -0
  26. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_builtin_tools.py +0 -0
  27. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_constant.py +0 -0
  28. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_data_converters.py +0 -0
  29. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_metric_handlers.py +0 -0
  30. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_utils.py +0 -0
  31. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_evals_visualization.py +0 -0
  32. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_gcs_utils.py +0 -0
  33. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_logging_utils.py +0 -0
  34. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_memory_bank_utils.py +0 -0
  35. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_observability_data_converter.py +0 -0
  36. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_operations_utils.py +0 -0
  37. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_prompt_management_utils.py +0 -0
  38. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/_skills_utils.py +0 -0
  39. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/a2a_task_events.py +0 -0
  40. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/a2a_tasks.py +0 -0
  41. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/datasets.py +0 -0
  42. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/endpoints.py +0 -0
  43. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/example_stores.py +0 -0
  44. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/feedback_contexts.py +0 -0
  45. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/feedback_entries.py +0 -0
  46. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/live.py +0 -0
  47. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/live_runtimes.py +0 -0
  48. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/memories.py +0 -0
  49. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/memory_revisions.py +0 -0
  50. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/model_garden.py +0 -0
  51. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/prompt_optimizer.py +0 -0
  52. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/rag.py +0 -0
  53. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/runtime_revisions.py +0 -0
  54. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/sandbox_snapshots.py +0 -0
  55. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/sandbox_templates.py +0 -0
  56. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/sandboxes.py +0 -0
  57. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/serving_profiles.py +0 -0
  58. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/session_events.py +0 -0
  59. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/sessions.py +0 -0
  60. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/skill_revisions.py +0 -0
  61. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/skills.py +0 -0
  62. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/types/agent_engines.py +0 -0
  63. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/types/evals.py +29 -29
  64. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/types/prompt_optimizer.py +0 -0
  65. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/_genai/types/prompts.py +0 -0
  66. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/frameworks/__init__.py +0 -0
  67. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/frameworks/a2a.py +0 -0
  68. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/frameworks/langchain.py +0 -0
  69. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/frameworks/langgraph.py +0 -0
  70. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/agentplatform/frameworks/llama_index.py +0 -0
  71. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/google_cloud_agentplatform.egg-info/dependency_links.txt +0 -0
  72. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/google_cloud_agentplatform.egg-info/requires.txt +0 -0
  73. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/google_cloud_agentplatform.egg-info/top_level.txt +0 -0
  74. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/pyproject.toml +0 -0
  75. {google_cloud_agentplatform-2.10.0 → google_cloud_agentplatform-2.11.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: google-cloud-agentplatform
3
- Version: 2.10.0
3
+ Version: 2.11.0
4
4
  Summary: Google Cloud Agent Platform Client Library
5
5
  Author-email: Google LLC <googleapis-packages@google.com>
6
6
  License: Apache-2.0
@@ -1610,6 +1610,7 @@ _MANAGED_AGENT_SUPPORTED_METRICS = frozenset(
1610
1610
  {
1611
1611
  "safety_v1",
1612
1612
  "final_response_quality_v1",
1613
+ "final_response_quality_v2",
1613
1614
  "multi_turn_task_success_v1",
1614
1615
  }
1615
1616
  )
@@ -357,7 +357,7 @@ class PrebuiltMetricLoader:
357
357
 
358
358
  @property
359
359
  def FINAL_RESPONSE_QUALITY(self) -> LazyLoadedPrebuiltMetric:
360
- return self.__getattr__("FINAL_RESPONSE_QUALITY", version="v1")
360
+ return self.__getattr__("FINAL_RESPONSE_QUALITY")
361
361
 
362
362
  @property
363
363
  def HALLUCINATION(self) -> LazyLoadedPrebuiltMetric:
@@ -149,8 +149,12 @@ def _get_few_shot_prompt(
149
149
 
150
150
  def _get_service_account(
151
151
  config: types.PromptOptimizerConfigOrDict,
152
- ) -> str:
153
- """Get the service account from the config for the custom job."""
152
+ ) -> Optional[str]:
153
+ """Get the service account from the config for the custom job.
154
+
155
+ Returns None when neither field is set, so the job runs as the Vertex AI
156
+ service agent.
157
+ """
154
158
  if isinstance(config, dict):
155
159
  config = types.PromptOptimizerConfig.model_validate(config)
156
160
 
@@ -165,10 +169,7 @@ def _get_service_account(
165
169
  return config.service_account # pytype: disable=attribute-error
166
170
  elif config.service_account_project_number: # pytype: disable=attribute-error
167
171
  return f"{config.service_account_project_number}-compute@developer.gserviceaccount.com" # pytype: disable=attribute-error
168
- else:
169
- raise ValueError(
170
- "Either service_account or service_account_project_number " "is required."
171
- )
172
+ return None
172
173
 
173
174
 
174
175
  def _clean_and_parse_optimized_prompt(output_str: str) -> Optional[Any]:
@@ -36,6 +36,7 @@ from typing import (
36
36
  Callable,
37
37
  Coroutine,
38
38
  Dict,
39
+ Iterable,
39
40
  Iterator,
40
41
  List,
41
42
  Mapping,
@@ -46,8 +47,7 @@ from typing import (
46
47
  TypedDict,
47
48
  Union,
48
49
  )
49
-
50
- import httpx
50
+ import urllib.parse
51
51
 
52
52
  import proto
53
53
 
@@ -112,6 +112,12 @@ else:
112
112
  _SpecifierSet: type[Any] = Any # type: ignore[no-redef]
113
113
 
114
114
 
115
+ try:
116
+ import httpx # pylint: disable=g-import-not-at-top
117
+ except ImportError:
118
+ # Only A2A operations use httpx, and a2a-sdk requires it.
119
+ httpx = None # type: ignore[assignment]
120
+
115
121
  try:
116
122
  from a2a.types import AgentCard
117
123
  from a2a.client import ClientConfig, ClientFactory
@@ -175,6 +181,8 @@ _SUPPORTED_AGENT_FRAMEWORKS = frozenset(
175
181
  "llama-index",
176
182
  "custom",
177
183
  "a2a",
184
+ "claude-sdk",
185
+ "openai-sdk",
178
186
  ]
179
187
  )
180
188
  _DEFAULT_ASYNC_METHOD_NAME = "async_query"
@@ -1752,6 +1760,61 @@ def _wrap_async_stream_query_operation(
1752
1760
  return _method
1753
1761
 
1754
1762
 
1763
+ def _get_url_origin(url: str) -> tuple[str, str, Optional[int]]:
1764
+ """Returns the normalized `(scheme, hostname, port)` origin of `url`."""
1765
+ try:
1766
+ parsed = urllib.parse.urlsplit(str(url))
1767
+ port = parsed.port
1768
+ except ValueError:
1769
+ return ("", "", None)
1770
+ scheme = parsed.scheme.lower()
1771
+ hostname = (parsed.hostname or "").lower()
1772
+ if port is None:
1773
+ if scheme == "https":
1774
+ port = 443
1775
+ elif scheme == "http":
1776
+ port = 80
1777
+ return (scheme, hostname, port)
1778
+
1779
+
1780
+ def _create_origin_pinned_auth(
1781
+ target_url: str, token: Any
1782
+ ) -> tuple[Callable[[Any], Any], dict[str, list[Callable[[Any], Any]]]]:
1783
+ """Creates an httpx auth callable and request event hook pinned to `target_url`."""
1784
+ expected_origin = _get_url_origin(target_url)
1785
+ expected_path = urllib.parse.urlsplit(str(target_url)).path.rstrip("/")
1786
+
1787
+ def _pin_request_credentials(request: Any) -> Any:
1788
+ request_url = str(request.url)
1789
+ request_origin = _get_url_origin(request_url)
1790
+ raw_path = urllib.parse.urlsplit(request_url).path
1791
+ unquoted_segments = urllib.parse.unquote(raw_path).split("/")
1792
+ path_matches = (
1793
+ bool(expected_path)
1794
+ and ".." not in unquoted_segments
1795
+ and (raw_path == expected_path or raw_path.startswith(expected_path + "/"))
1796
+ )
1797
+ if (
1798
+ not expected_origin[0]
1799
+ or not expected_origin[1]
1800
+ or request_origin != expected_origin
1801
+ or not path_matches
1802
+ ):
1803
+ request.headers.pop("Authorization", None)
1804
+ raise ValueError(
1805
+ f"Outbound A2A request URL {request_url!r} does not match "
1806
+ f"expected origin {expected_origin} and path prefix "
1807
+ f"{expected_path!r}."
1808
+ )
1809
+ request.headers["Authorization"] = f"Bearer {token}"
1810
+ return request
1811
+
1812
+ async def _on_request(request: Any) -> None:
1813
+ _pin_request_credentials(request)
1814
+
1815
+ return _pin_request_credentials, {"request": [_on_request]}
1816
+
1817
+
1755
1818
  def _wrap_a2a_operation(method_name: str, agent_card: str) -> Callable[..., list[Any]]:
1756
1819
  """Wraps an Agent Runtime method, creating a callable for A2A API.
1757
1820
 
@@ -1798,8 +1861,14 @@ def _wrap_a2a_operation(method_name: str, agent_card: str) -> Callable[..., list
1798
1861
 
1799
1862
  base_url = self.api_client._api_client._http_options.base_url.rstrip("/")
1800
1863
  api_version = self.api_client._api_client._http_options.api_version
1801
- a2a_agent_card.supported_interfaces[0].url = (
1802
- f"{base_url}/{api_version}/{self.api_resource.name}/a2a"
1864
+ target_url = f"{base_url}/{api_version}/{self.api_resource.name}/a2a"
1865
+ a2a_agent_card.supported_interfaces[0].url = target_url
1866
+ a2a_agent_card.supported_interfaces[0].tenant = ""
1867
+ del a2a_agent_card.supported_interfaces[1:]
1868
+
1869
+ auth, event_hooks = _create_origin_pinned_auth(
1870
+ target_url,
1871
+ self.api_client._api_client._credentials.token, # pylint: disable=protected-access
1803
1872
  )
1804
1873
 
1805
1874
  config = ClientConfig(
@@ -1808,11 +1877,8 @@ def _wrap_a2a_operation(method_name: str, agent_card: str) -> Callable[..., list
1808
1877
  ],
1809
1878
  use_client_preference=True,
1810
1879
  httpx_client=httpx.AsyncClient(
1811
- headers={
1812
- "Authorization": (
1813
- f"Bearer {self.api_client._api_client._credentials.token}"
1814
- )
1815
- },
1880
+ auth=auth,
1881
+ event_hooks=event_hooks,
1816
1882
  timeout=kwargs.pop("timeout", None)
1817
1883
  or (
1818
1884
  self.api_client._api_client._http_options.timeout / 1000.0
@@ -1888,6 +1954,62 @@ def _strip_sse_framing(line: str) -> str:
1888
1954
  return payload[1:] if payload.startswith(" ") else payload
1889
1955
 
1890
1956
 
1957
+ _STREAM_ERROR_KEYS = frozenset({"code", "message", "errorCode", "errorMessage"})
1958
+ _STREAM_ERROR_STATUS_CODES = {
1959
+ "INVALID_ARGUMENT": 400,
1960
+ "UNAUTHENTICATED": 401,
1961
+ "PERMISSION_DENIED": 403,
1962
+ "NOT_FOUND": 404,
1963
+ "RESOURCE_EXHAUSTED": 429,
1964
+ "UNAVAILABLE": 503,
1965
+ "DEADLINE_EXCEEDED": 504,
1966
+ }
1967
+
1968
+
1969
+ def _raise_for_stream_error(parsed: Any) -> None:
1970
+ """Raises `APIError` if `parsed` is a terminal stream error frame."""
1971
+ if (
1972
+ not isinstance(parsed, dict)
1973
+ or "errorCode" not in parsed
1974
+ or ("errorMessage" not in parsed and "message" not in parsed)
1975
+ or not parsed.keys() <= _STREAM_ERROR_KEYS
1976
+ ):
1977
+ return
1978
+ raw_code = parsed["errorCode"]
1979
+ if raw_code is None or (isinstance(raw_code, str) and not raw_code.strip()):
1980
+ raw_code = parsed.get("code")
1981
+ if isinstance(raw_code, bool) or not raw_code:
1982
+ return
1983
+ raw_str = str(raw_code).strip()
1984
+ upper = raw_str.upper().removeprefix("STATUSCODE.")
1985
+ if upper in ("", "0", "OK"):
1986
+ return
1987
+ status: Optional[str] = None
1988
+ if upper in _STREAM_ERROR_STATUS_CODES:
1989
+ status_code, status = _STREAM_ERROR_STATUS_CODES[upper], upper
1990
+ elif raw_str.isascii() and raw_str.isdigit():
1991
+ num = int(raw_str)
1992
+ if num == 0 or 200 <= num < 300:
1993
+ return
1994
+ if 400 <= num < 600:
1995
+ status_code = num
1996
+ else:
1997
+ status_code, status = 500, raw_str
1998
+ else:
1999
+ status_code = 500
2000
+ if upper != "NONE":
2001
+ status = upper
2002
+ message = parsed.get("errorMessage") or parsed.get("message") or ""
2003
+ error_body: dict[str, Any] = {"code": status_code, "message": str(message)}
2004
+ if status:
2005
+ error_body["status"] = status
2006
+ google_genai_errors.APIError.raise_error(
2007
+ status_code,
2008
+ {"error": error_body},
2009
+ None,
2010
+ )
2011
+
2012
+
1891
2013
  def _yield_parsed_json(http_response: google_genai_types.HttpResponse) -> Iterator[Any]:
1892
2014
  """Converts the body of the HTTP Response message to JSON format.
1893
2015
 
@@ -1897,6 +2019,10 @@ def _yield_parsed_json(http_response: google_genai_types.HttpResponse) -> Iterat
1897
2019
 
1898
2020
  Yields:
1899
2021
  Any: A JSON object or line of the original body or None.
2022
+
2023
+ Raises:
2024
+ google.genai.errors.APIError: If the stream emits a terminal error
2025
+ frame.
1900
2026
  """
1901
2027
  if not http_response.body:
1902
2028
  yield None
@@ -1912,6 +2038,7 @@ def _yield_parsed_json(http_response: google_genai_types.HttpResponse) -> Iterat
1912
2038
  line = json.loads(line)
1913
2039
  except Exception as e:
1914
2040
  logger.warning(f"failed to parse json: {line}. Exception: {e}")
2041
+ _raise_for_stream_error(line)
1915
2042
  yield line
1916
2043
 
1917
2044
 
@@ -1930,6 +2057,10 @@ def _yield_parsed_json_from_httpbody(body: httpbody_pb2.HttpBody) -> Iterator[An
1930
2057
  Yields:
1931
2058
  Any: A JSON object, a line of the original body, or the original body if
1932
2059
  it is not JSON, or None.
2060
+
2061
+ Raises:
2062
+ google.genai.errors.APIError: If the stream emits a terminal error
2063
+ frame.
1933
2064
  """
1934
2065
  content_type = getattr(body, "content_type", None)
1935
2066
  data = getattr(body, "data", None)
@@ -1963,6 +2094,7 @@ def _yield_parsed_json_from_httpbody(body: httpbody_pb2.HttpBody) -> Iterator[An
1963
2094
  line = json.loads(line)
1964
2095
  except Exception as e:
1965
2096
  logger.warning(f"failed to parse json: {line}. Exception: {e}")
2097
+ _raise_for_stream_error(line)
1966
2098
  yield line
1967
2099
 
1968
2100
 
@@ -2082,6 +2214,68 @@ def _add_telemetry_enablement_env(
2082
2214
  return env_vars | env_to_add
2083
2215
 
2084
2216
 
2217
+ # Mirrors the Agent Engine service's reserved environment variable names, so
2218
+ # that a reserved name is rejected before the agent is packaged and uploaded.
2219
+ _RESERVED_ENV_VAR_PREFIX = "GOOGLE_CLOUD_AGENT_ENGINE"
2220
+ _RESERVED_X_GOOGLE_ENV_VAR_PREFIX = "X_GOOGLE_"
2221
+ _ALLOWED_RESERVED_PREFIX_ENV_VAR_NAMES = frozenset(
2222
+ {
2223
+ "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY",
2224
+ "GOOGLE_CLOUD_AGENT_ENGINE_RUN_SYNC_IN_THREADPOOL",
2225
+ }
2226
+ )
2227
+ _RESERVED_ENV_VAR_NAMES = frozenset(
2228
+ {
2229
+ "GOOGLE_CLOUD_QUOTA_PROJECT",
2230
+ "GOOGLE_CLOUD_PROJECT",
2231
+ "EXTENSION_APP_FILE",
2232
+ "PORT",
2233
+ "K_SERVICE",
2234
+ "K_REVISION",
2235
+ "K_CONFIGURATION",
2236
+ "GOOGLE_APPLICATION_CREDENTIALS",
2237
+ }
2238
+ )
2239
+
2240
+
2241
+ def _validate_env_var_names_or_raise(env_var_names: Iterable[Any]) -> None:
2242
+ """Validates that none of the environment variable names are reserved.
2243
+
2244
+ Non-string entries are skipped here so downstream type checks raise the
2245
+ existing TypeError instead of an AttributeError.
2246
+
2247
+ Args:
2248
+ env_var_names: The environment variable names provided by the caller.
2249
+
2250
+ Raises:
2251
+ ValueError: If a name is reserved, or uses a reserved prefix.
2252
+ """
2253
+
2254
+ for name in env_var_names:
2255
+ if not isinstance(name, str):
2256
+ continue
2257
+ if (
2258
+ name.startswith(_RESERVED_ENV_VAR_PREFIX)
2259
+ and name not in _ALLOWED_RESERVED_PREFIX_ENV_VAR_NAMES
2260
+ ):
2261
+ raise ValueError(
2262
+ f"Environment variable name {name!r} uses the reserved prefix"
2263
+ f" {_RESERVED_ENV_VAR_PREFIX!r}. Please rename the variable in"
2264
+ " `env_vars`."
2265
+ )
2266
+ if name in _RESERVED_ENV_VAR_NAMES:
2267
+ raise ValueError(
2268
+ f"Environment variable name {name!r} is reserved. Please rename"
2269
+ " the variable in `env_vars`."
2270
+ )
2271
+ if name.startswith(_RESERVED_X_GOOGLE_ENV_VAR_PREFIX):
2272
+ raise ValueError(
2273
+ f"Environment variable name {name!r} uses the reserved prefix"
2274
+ f" {_RESERVED_X_GOOGLE_ENV_VAR_PREFIX!r}, which is for internal"
2275
+ " use only. Please rename the variable in `env_vars`."
2276
+ )
2277
+
2278
+
2085
2279
  def _dataclass_to_dict_or_raise(obj: Any) -> Dict[str, Any]:
2086
2280
  """Converts a dataclass to a JSON dictionary."""
2087
2281
  if not dataclasses.is_dataclass(obj):
@@ -19,6 +19,7 @@ import re
19
19
  from typing import Any
20
20
 
21
21
  from google.genai._common import get_value_by_path as getv
22
+ from google.genai._transformers import t_content, t_model # noqa: F401
22
23
 
23
24
  from . import _evals_constant
24
25
  from . import _evals_data_converters
@@ -65,6 +65,9 @@ if TYPE_CHECKING:
65
65
  from agentplatform._genai import (
66
66
  serving_profiles as serving_profiles_module,
67
67
  )
68
+ from agentplatform._genai import (
69
+ detections as detections_module,
70
+ )
68
71
 
69
72
 
70
73
  _GENAI_MODULES_TELEMETRY_HEADER = "vertex-genai-modules"
@@ -117,6 +120,7 @@ class AsyncClient:
117
120
  self._sandboxes: Optional[ModuleType] = None
118
121
  self._memory_banks: Optional[ModuleType] = None
119
122
  self._serving_profiles: Optional[ModuleType] = None
123
+ self._detections: Optional[ModuleType] = None
120
124
 
121
125
  @property
122
126
  @_common.experimental_warning(
@@ -303,6 +307,17 @@ class AsyncClient:
303
307
  )
304
308
  return self._serving_profiles.AsyncServingProfiles(self._api_client) # type: ignore[no-any-return]
305
309
 
310
+ @property
311
+ def detections(
312
+ self,
313
+ ) -> "detections_module.AsyncDetections":
314
+ if self._detections is None:
315
+ self._detections = importlib.import_module(
316
+ ".detections",
317
+ __package__,
318
+ )
319
+ return self._detections.AsyncDetections(self._api_client) # type: ignore[no-any-return]
320
+
306
321
  async def aclose(self) -> None:
307
322
  """Closes the async client explicitly.
308
323
 
@@ -416,6 +431,7 @@ class Client:
416
431
  self._sandboxes: Optional[ModuleType] = None
417
432
  self._memory_banks: Optional[ModuleType] = None
418
433
  self._serving_profiles: Optional[ModuleType] = None
434
+ self._detections: Optional[ModuleType] = None
419
435
 
420
436
  @property
421
437
  def evals(self) -> "evals_module.Evals":
@@ -624,3 +640,12 @@ class Client:
624
640
  __package__,
625
641
  )
626
642
  return self._serving_profiles.ServingProfiles(self._api_client) # type: ignore[no-any-return]
643
+
644
+ @property
645
+ def detections(self) -> "detections_module.Detections":
646
+ if self._detections is None:
647
+ self._detections = importlib.import_module(
648
+ ".detections",
649
+ __package__,
650
+ )
651
+ return self._detections.Detections(self._api_client) # type: ignore[no-any-return]
@@ -0,0 +1,214 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+
16
+ # Code generated by the Google Gen AI SDK generator DO NOT EDIT.
17
+
18
+ import json
19
+ import logging
20
+ from typing import Any, Optional, Union
21
+ from urllib.parse import urlencode
22
+
23
+ from google.genai import _api_module
24
+ from google.genai import _common
25
+ from google.genai import types as genai_types
26
+ from google.genai._api_client import BaseApiClient
27
+ from google.genai._common import get_value_by_path as getv
28
+ from google.genai._common import set_value_by_path as setv
29
+
30
+ from . import _transformers as t
31
+ from . import types
32
+
33
+ logger = logging.getLogger("agentplatform_genai.detections")
34
+
35
+
36
+ def _DetectContentParameters_to_vertex(
37
+ api_client: BaseApiClient,
38
+ from_object: Union[dict[str, Any], object],
39
+ parent_object: Optional[dict[str, Any]] = None,
40
+ ) -> dict[str, Any]:
41
+ to_object: dict[str, Any] = {}
42
+ if getv(from_object, ["model"]) is not None:
43
+ setv(
44
+ to_object,
45
+ ["_url", "model"],
46
+ t.t_model(api_client, getv(from_object, ["model"])),
47
+ )
48
+
49
+ if getv(from_object, ["content"]) is not None:
50
+ setv(to_object, ["content"], t.t_content(getv(from_object, ["content"])))
51
+
52
+ return to_object
53
+
54
+
55
+ class Detections(_api_module.BaseModule):
56
+ """Class for detecting AI-generated content."""
57
+
58
+ def detect_content(
59
+ self,
60
+ *,
61
+ model: str,
62
+ content: Union[genai_types.ContentUnion, genai_types.ContentUnionDict],
63
+ config: Optional[types.DetectContentConfigOrDict] = None,
64
+ ) -> types.DetectContentResponse:
65
+ """
66
+ Detects AI-generated content and C2PA Content Credentials in media inputs.
67
+ """
68
+
69
+ parameter_model = types._DetectContentParameters(
70
+ model=model,
71
+ content=content,
72
+ config=config,
73
+ )
74
+
75
+ request_url_dict: Optional[dict[str, str]]
76
+ if not self._api_client.vertexai:
77
+ raise ValueError(
78
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
79
+ )
80
+ else:
81
+ request_dict = _DetectContentParameters_to_vertex(
82
+ self._api_client, parameter_model
83
+ )
84
+ request_url_dict = request_dict.get("_url")
85
+ if request_url_dict:
86
+ path = "{model}:detectContent".format_map(request_url_dict)
87
+ else:
88
+ path = "{model}:detectContent"
89
+
90
+ query_params = request_dict.get("_query")
91
+ if query_params:
92
+ path = f"{path}?{urlencode(query_params)}"
93
+ # TODO: remove the hack that pops config.
94
+ request_dict.pop("config", None)
95
+
96
+ http_options: Optional[types.HttpOptions] = None
97
+ if (
98
+ parameter_model.config is not None
99
+ and parameter_model.config.http_options is not None
100
+ ):
101
+ http_options = parameter_model.config.http_options
102
+
103
+ request_dict = _common.convert_to_dict(request_dict)
104
+ request_dict = _common.encode_unserializable_types(request_dict)
105
+
106
+ response = self._api_client.request("post", path, request_dict, http_options)
107
+
108
+ response_dict = {} if not response.body else json.loads(response.body)
109
+
110
+ return_value = types.DetectContentResponse._from_response(
111
+ response=response_dict,
112
+ kwargs=(
113
+ {
114
+ "config": {
115
+ "response_schema": getattr(
116
+ parameter_model.config, "response_schema", None
117
+ ),
118
+ "response_json_schema": getattr(
119
+ parameter_model.config, "response_json_schema", None
120
+ ),
121
+ "include_all_fields": getattr(
122
+ parameter_model.config, "include_all_fields", None
123
+ ),
124
+ }
125
+ }
126
+ if getattr(parameter_model, "config", None)
127
+ else {}
128
+ ),
129
+ )
130
+
131
+ self._api_client._verify_response(return_value)
132
+ return return_value
133
+
134
+
135
+ class AsyncDetections(_api_module.BaseModule):
136
+ """Class for detecting AI-generated content."""
137
+
138
+ async def detect_content(
139
+ self,
140
+ *,
141
+ model: str,
142
+ content: Union[genai_types.ContentUnion, genai_types.ContentUnionDict],
143
+ config: Optional[types.DetectContentConfigOrDict] = None,
144
+ ) -> types.DetectContentResponse:
145
+ """
146
+ Detects AI-generated content and C2PA Content Credentials in media inputs.
147
+ """
148
+
149
+ parameter_model = types._DetectContentParameters(
150
+ model=model,
151
+ content=content,
152
+ config=config,
153
+ )
154
+
155
+ request_url_dict: Optional[dict[str, str]]
156
+ if not self._api_client.vertexai:
157
+ raise ValueError(
158
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
159
+ )
160
+ else:
161
+ request_dict = _DetectContentParameters_to_vertex(
162
+ self._api_client, parameter_model
163
+ )
164
+ request_url_dict = request_dict.get("_url")
165
+ if request_url_dict:
166
+ path = "{model}:detectContent".format_map(request_url_dict)
167
+ else:
168
+ path = "{model}:detectContent"
169
+
170
+ query_params = request_dict.get("_query")
171
+ if query_params:
172
+ path = f"{path}?{urlencode(query_params)}"
173
+ # TODO: remove the hack that pops config.
174
+ request_dict.pop("config", None)
175
+
176
+ http_options: Optional[types.HttpOptions] = None
177
+ if (
178
+ parameter_model.config is not None
179
+ and parameter_model.config.http_options is not None
180
+ ):
181
+ http_options = parameter_model.config.http_options
182
+
183
+ request_dict = _common.convert_to_dict(request_dict)
184
+ request_dict = _common.encode_unserializable_types(request_dict)
185
+
186
+ response = await self._api_client.async_request(
187
+ "post", path, request_dict, http_options
188
+ )
189
+
190
+ response_dict = {} if not response.body else json.loads(response.body)
191
+
192
+ return_value = types.DetectContentResponse._from_response(
193
+ response=response_dict,
194
+ kwargs=(
195
+ {
196
+ "config": {
197
+ "response_schema": getattr(
198
+ parameter_model.config, "response_schema", None
199
+ ),
200
+ "response_json_schema": getattr(
201
+ parameter_model.config, "response_json_schema", None
202
+ ),
203
+ "include_all_fields": getattr(
204
+ parameter_model.config, "include_all_fields", None
205
+ ),
206
+ }
207
+ }
208
+ if getattr(parameter_model, "config", None)
209
+ else {}
210
+ ),
211
+ )
212
+
213
+ self._api_client._verify_response(return_value)
214
+ return return_value