google-cloud-agentplatform 1.165.1.dev0__py3-none-any.whl

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 (62) hide show
  1. agentplatform/__init__.py +72 -0
  2. agentplatform/_genai/__init__.py +43 -0
  3. agentplatform/_genai/_agent_engines_utils.py +2341 -0
  4. agentplatform/_genai/_bigquery_utils.py +49 -0
  5. agentplatform/_genai/_datasets_utils.py +344 -0
  6. agentplatform/_genai/_evals_builtin_tools.py +209 -0
  7. agentplatform/_genai/_evals_common.py +4268 -0
  8. agentplatform/_genai/_evals_constant.py +122 -0
  9. agentplatform/_genai/_evals_data_converters.py +926 -0
  10. agentplatform/_genai/_evals_metric_handlers.py +1783 -0
  11. agentplatform/_genai/_evals_metric_loaders.py +401 -0
  12. agentplatform/_genai/_evals_utils.py +1043 -0
  13. agentplatform/_genai/_evals_visualization.py +2070 -0
  14. agentplatform/_genai/_gcs_utils.py +262 -0
  15. agentplatform/_genai/_logging_utils.py +47 -0
  16. agentplatform/_genai/_memory_bank_utils.py +206 -0
  17. agentplatform/_genai/_observability_data_converter.py +186 -0
  18. agentplatform/_genai/_operations_utils.py +94 -0
  19. agentplatform/_genai/_prompt_management_utils.py +147 -0
  20. agentplatform/_genai/_prompt_optimizer_utils.py +215 -0
  21. agentplatform/_genai/_skills_utils.py +69 -0
  22. agentplatform/_genai/_transformers.py +628 -0
  23. agentplatform/_genai/a2a_task_events.py +509 -0
  24. agentplatform/_genai/a2a_tasks.py +861 -0
  25. agentplatform/_genai/agent_engines.py +3931 -0
  26. agentplatform/_genai/client.py +519 -0
  27. agentplatform/_genai/datasets.py +3045 -0
  28. agentplatform/_genai/endpoints.py +1149 -0
  29. agentplatform/_genai/evals.py +6883 -0
  30. agentplatform/_genai/example_stores.py +1445 -0
  31. agentplatform/_genai/feedback_contexts.py +700 -0
  32. agentplatform/_genai/feedback_entries.py +1644 -0
  33. agentplatform/_genai/live.py +64 -0
  34. agentplatform/_genai/live_agent_engines.py +179 -0
  35. agentplatform/_genai/memories.py +2962 -0
  36. agentplatform/_genai/memory_banks.py +1927 -0
  37. agentplatform/_genai/memory_revisions.py +465 -0
  38. agentplatform/_genai/model_garden.py +2638 -0
  39. agentplatform/_genai/prompt_optimizer.py +995 -0
  40. agentplatform/_genai/prompts.py +4515 -0
  41. agentplatform/_genai/rag.py +4961 -0
  42. agentplatform/_genai/runtime_revisions.py +1257 -0
  43. agentplatform/_genai/runtimes.py +78 -0
  44. agentplatform/_genai/sandbox_snapshots.py +1015 -0
  45. agentplatform/_genai/sandbox_templates.py +1088 -0
  46. agentplatform/_genai/sandboxes.py +1604 -0
  47. agentplatform/_genai/session_events.py +543 -0
  48. agentplatform/_genai/sessions.py +1449 -0
  49. agentplatform/_genai/skill_revisions.py +377 -0
  50. agentplatform/_genai/skills.py +1708 -0
  51. agentplatform/_genai/types/__init__.py +4695 -0
  52. agentplatform/_genai/types/agent_engines.py +16 -0
  53. agentplatform/_genai/types/common.py +32784 -0
  54. agentplatform/_genai/types/evals.py +1031 -0
  55. agentplatform/_genai/types/prompt_optimizer.py +107 -0
  56. agentplatform/_genai/types/prompts.py +107 -0
  57. agentplatform/version.py +17 -0
  58. google_cloud_agentplatform-1.165.1.dev0.dist-info/METADATA +79 -0
  59. google_cloud_agentplatform-1.165.1.dev0.dist-info/RECORD +62 -0
  60. google_cloud_agentplatform-1.165.1.dev0.dist-info/WHEEL +5 -0
  61. google_cloud_agentplatform-1.165.1.dev0.dist-info/licenses/LICENSE +202 -0
  62. google_cloud_agentplatform-1.165.1.dev0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1604 @@
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 builtins
19
+ import functools
20
+ import json
21
+ import logging
22
+ import mimetypes
23
+ import secrets
24
+ import time
25
+ from typing import Any, Iterator, Optional, Union
26
+ from urllib.parse import urlencode
27
+
28
+ from google import auth as google_auth
29
+ from google import genai
30
+ from google.auth.transport import requests as google_auth_requests
31
+ from google.genai import _api_module
32
+ from google.genai import _common
33
+ from google.genai import types as genai_types
34
+ from google.genai._common import get_value_by_path as getv
35
+ from google.genai._common import set_value_by_path as setv
36
+ from google.genai.pagers import Pager
37
+
38
+ from . import _agent_engines_utils
39
+ from . import types
40
+
41
+ logger = logging.getLogger("agentplatform_genai.sandboxes")
42
+
43
+ logger.setLevel(logging.INFO)
44
+
45
+
46
+ def _CreateAgentEngineSandboxConfig_to_vertex(
47
+ from_object: Union[dict[str, Any], object],
48
+ parent_object: Optional[dict[str, Any]] = None,
49
+ ) -> dict[str, Any]:
50
+ to_object: dict[str, Any] = {}
51
+
52
+ if getv(from_object, ["display_name"]) is not None:
53
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
54
+
55
+ if getv(from_object, ["description"]) is not None:
56
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
57
+
58
+ if getv(from_object, ["ttl"]) is not None:
59
+ setv(parent_object, ["ttl"], getv(from_object, ["ttl"]))
60
+
61
+ if getv(from_object, ["sandbox_environment_template"]) is not None:
62
+ setv(
63
+ parent_object,
64
+ ["sandboxEnvironmentTemplate"],
65
+ getv(from_object, ["sandbox_environment_template"]),
66
+ )
67
+
68
+ if getv(from_object, ["sandbox_environment_snapshot"]) is not None:
69
+ setv(
70
+ parent_object,
71
+ ["sandboxEnvironmentSnapshot"],
72
+ getv(from_object, ["sandbox_environment_snapshot"]),
73
+ )
74
+
75
+ if getv(from_object, ["owner"]) is not None:
76
+ setv(parent_object, ["owner"], getv(from_object, ["owner"]))
77
+
78
+ return to_object
79
+
80
+
81
+ def _CreateAgentEngineSandboxRequestParameters_to_vertex(
82
+ from_object: Union[dict[str, Any], object],
83
+ parent_object: Optional[dict[str, Any]] = None,
84
+ ) -> dict[str, Any]:
85
+ to_object: dict[str, Any] = {}
86
+ if getv(from_object, ["name"]) is not None:
87
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
88
+
89
+ if getv(from_object, ["spec"]) is not None:
90
+ setv(to_object, ["spec"], getv(from_object, ["spec"]))
91
+
92
+ if getv(from_object, ["config"]) is not None:
93
+ _CreateAgentEngineSandboxConfig_to_vertex(
94
+ getv(from_object, ["config"]), to_object
95
+ )
96
+
97
+ return to_object
98
+
99
+
100
+ def _DeleteAgentEngineSandboxRequestParameters_to_vertex(
101
+ from_object: Union[dict[str, Any], object],
102
+ parent_object: Optional[dict[str, Any]] = None,
103
+ ) -> dict[str, Any]:
104
+ to_object: dict[str, Any] = {}
105
+ if getv(from_object, ["name"]) is not None:
106
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
107
+
108
+ return to_object
109
+
110
+
111
+ def _ExecuteCodeAgentEngineSandboxRequestParameters_to_vertex(
112
+ from_object: Union[dict[str, Any], object],
113
+ parent_object: Optional[dict[str, Any]] = None,
114
+ ) -> dict[str, Any]:
115
+ to_object: dict[str, Any] = {}
116
+ if getv(from_object, ["name"]) is not None:
117
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
118
+
119
+ if getv(from_object, ["inputs"]) is not None:
120
+ setv(to_object, ["inputs"], [item for item in getv(from_object, ["inputs"])])
121
+
122
+ return to_object
123
+
124
+
125
+ def _GetAgentEngineSandboxOperationParameters_to_vertex(
126
+ from_object: Union[dict[str, Any], object],
127
+ parent_object: Optional[dict[str, Any]] = None,
128
+ ) -> dict[str, Any]:
129
+ to_object: dict[str, Any] = {}
130
+ if getv(from_object, ["operation_name"]) is not None:
131
+ setv(
132
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
133
+ )
134
+
135
+ return to_object
136
+
137
+
138
+ def _GetAgentEngineSandboxRequestParameters_to_vertex(
139
+ from_object: Union[dict[str, Any], object],
140
+ parent_object: Optional[dict[str, Any]] = None,
141
+ ) -> dict[str, Any]:
142
+ to_object: dict[str, Any] = {}
143
+ if getv(from_object, ["name"]) is not None:
144
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
145
+
146
+ return to_object
147
+
148
+
149
+ def _ListAgentEngineSandboxesConfig_to_vertex(
150
+ from_object: Union[dict[str, Any], object],
151
+ parent_object: Optional[dict[str, Any]] = None,
152
+ ) -> dict[str, Any]:
153
+ to_object: dict[str, Any] = {}
154
+
155
+ if getv(from_object, ["page_size"]) is not None:
156
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
157
+
158
+ if getv(from_object, ["page_token"]) is not None:
159
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
160
+
161
+ if getv(from_object, ["filter"]) is not None:
162
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
163
+
164
+ return to_object
165
+
166
+
167
+ def _ListAgentEngineSandboxesRequestParameters_to_vertex(
168
+ from_object: Union[dict[str, Any], object],
169
+ parent_object: Optional[dict[str, Any]] = None,
170
+ ) -> dict[str, Any]:
171
+ to_object: dict[str, Any] = {}
172
+ if getv(from_object, ["name"]) is not None:
173
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
174
+
175
+ if getv(from_object, ["config"]) is not None:
176
+ _ListAgentEngineSandboxesConfig_to_vertex(
177
+ getv(from_object, ["config"]), to_object
178
+ )
179
+
180
+ return to_object
181
+
182
+
183
+ class Sandboxes(_api_module.BaseModule):
184
+
185
+ def _create(
186
+ self,
187
+ *,
188
+ name: str,
189
+ spec: Optional[types.SandboxEnvironmentSpecOrDict] = None,
190
+ config: Optional[types.CreateAgentEngineSandboxConfigOrDict] = None,
191
+ ) -> types.AgentEngineSandboxOperation:
192
+ """
193
+ Creates a new sandbox in the Agent Engine.
194
+ """
195
+
196
+ parameter_model = types._CreateAgentEngineSandboxRequestParameters(
197
+ name=name,
198
+ spec=spec,
199
+ config=config,
200
+ )
201
+
202
+ request_url_dict: Optional[dict[str, str]]
203
+ if not self._api_client.vertexai:
204
+ raise ValueError(
205
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
206
+ )
207
+ else:
208
+ request_dict = _CreateAgentEngineSandboxRequestParameters_to_vertex(
209
+ parameter_model
210
+ )
211
+ request_url_dict = request_dict.get("_url")
212
+ if request_url_dict:
213
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
214
+ else:
215
+ path = "{name}/sandboxEnvironments"
216
+
217
+ query_params = request_dict.get("_query")
218
+ if query_params:
219
+ path = f"{path}?{urlencode(query_params)}"
220
+ # TODO: remove the hack that pops config.
221
+ request_dict.pop("config", None)
222
+
223
+ http_options: Optional[types.HttpOptions] = None
224
+ if (
225
+ parameter_model.config is not None
226
+ and parameter_model.config.http_options is not None
227
+ ):
228
+ http_options = parameter_model.config.http_options
229
+
230
+ request_dict = _common.convert_to_dict(request_dict)
231
+ request_dict = _common.encode_unserializable_types(request_dict)
232
+
233
+ response = self._api_client.request("post", path, request_dict, http_options)
234
+
235
+ response_dict = {} if not response.body else json.loads(response.body)
236
+
237
+ return_value = types.AgentEngineSandboxOperation._from_response(
238
+ response=response_dict,
239
+ kwargs=(
240
+ {
241
+ "config": {
242
+ "response_schema": getattr(
243
+ parameter_model.config, "response_schema", None
244
+ ),
245
+ "response_json_schema": getattr(
246
+ parameter_model.config, "response_json_schema", None
247
+ ),
248
+ "include_all_fields": getattr(
249
+ parameter_model.config, "include_all_fields", None
250
+ ),
251
+ }
252
+ }
253
+ if getattr(parameter_model, "config", None)
254
+ else {}
255
+ ),
256
+ )
257
+
258
+ self._api_client._verify_response(return_value)
259
+ return return_value
260
+
261
+ def _delete(
262
+ self,
263
+ *,
264
+ name: str,
265
+ config: Optional[types.DeleteAgentEngineSandboxConfigOrDict] = None,
266
+ ) -> types.DeleteAgentEngineSandboxOperation:
267
+ """
268
+ Delete an Agent Engine sandbox.
269
+
270
+ Args:
271
+ name (str):
272
+ Required. The name of the Agent Engine sandbox to be deleted. Format:
273
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox}`.
274
+
275
+ """
276
+
277
+ parameter_model = types._DeleteAgentEngineSandboxRequestParameters(
278
+ name=name,
279
+ config=config,
280
+ )
281
+
282
+ request_url_dict: Optional[dict[str, str]]
283
+ if not self._api_client.vertexai:
284
+ raise ValueError(
285
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
286
+ )
287
+ else:
288
+ request_dict = _DeleteAgentEngineSandboxRequestParameters_to_vertex(
289
+ parameter_model
290
+ )
291
+ request_url_dict = request_dict.get("_url")
292
+ if request_url_dict:
293
+ path = "{name}".format_map(request_url_dict)
294
+ else:
295
+ path = "{name}"
296
+
297
+ query_params = request_dict.get("_query")
298
+ if query_params:
299
+ path = f"{path}?{urlencode(query_params)}"
300
+ # TODO: remove the hack that pops config.
301
+ request_dict.pop("config", None)
302
+
303
+ http_options: Optional[types.HttpOptions] = None
304
+ if (
305
+ parameter_model.config is not None
306
+ and parameter_model.config.http_options is not None
307
+ ):
308
+ http_options = parameter_model.config.http_options
309
+
310
+ request_dict = _common.convert_to_dict(request_dict)
311
+ request_dict = _common.encode_unserializable_types(request_dict)
312
+
313
+ response = self._api_client.request("delete", path, request_dict, http_options)
314
+
315
+ response_dict = {} if not response.body else json.loads(response.body)
316
+
317
+ return_value = types.DeleteAgentEngineSandboxOperation._from_response(
318
+ response=response_dict,
319
+ kwargs=(
320
+ {
321
+ "config": {
322
+ "response_schema": getattr(
323
+ parameter_model.config, "response_schema", None
324
+ ),
325
+ "response_json_schema": getattr(
326
+ parameter_model.config, "response_json_schema", None
327
+ ),
328
+ "include_all_fields": getattr(
329
+ parameter_model.config, "include_all_fields", None
330
+ ),
331
+ }
332
+ }
333
+ if getattr(parameter_model, "config", None)
334
+ else {}
335
+ ),
336
+ )
337
+
338
+ self._api_client._verify_response(return_value)
339
+ return return_value
340
+
341
+ def _execute_code(
342
+ self,
343
+ *,
344
+ name: str,
345
+ inputs: Optional[builtins.list[types.ChunkOrDict]] = None,
346
+ config: Optional[types.ExecuteCodeAgentEngineSandboxConfigOrDict] = None,
347
+ ) -> types.ExecuteSandboxEnvironmentResponse:
348
+ """
349
+ Execute code in an Agent Engine sandbox.
350
+ """
351
+
352
+ parameter_model = types._ExecuteCodeAgentEngineSandboxRequestParameters(
353
+ name=name,
354
+ inputs=inputs,
355
+ config=config,
356
+ )
357
+
358
+ request_url_dict: Optional[dict[str, str]]
359
+ if not self._api_client.vertexai:
360
+ raise ValueError(
361
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
362
+ )
363
+ else:
364
+ request_dict = _ExecuteCodeAgentEngineSandboxRequestParameters_to_vertex(
365
+ parameter_model
366
+ )
367
+ request_url_dict = request_dict.get("_url")
368
+ if request_url_dict:
369
+ path = "{name}/:execute".format_map(request_url_dict)
370
+ else:
371
+ path = "{name}/:execute"
372
+
373
+ query_params = request_dict.get("_query")
374
+ if query_params:
375
+ path = f"{path}?{urlencode(query_params)}"
376
+ # TODO: remove the hack that pops config.
377
+ request_dict.pop("config", None)
378
+
379
+ http_options: Optional[types.HttpOptions] = None
380
+ if (
381
+ parameter_model.config is not None
382
+ and parameter_model.config.http_options is not None
383
+ ):
384
+ http_options = parameter_model.config.http_options
385
+
386
+ request_dict = _common.convert_to_dict(request_dict)
387
+ request_dict = _common.encode_unserializable_types(request_dict)
388
+
389
+ response = self._api_client.request("post", path, request_dict, http_options)
390
+
391
+ response_dict = {} if not response.body else json.loads(response.body)
392
+
393
+ return_value = types.ExecuteSandboxEnvironmentResponse._from_response(
394
+ response=response_dict,
395
+ kwargs=(
396
+ {
397
+ "config": {
398
+ "response_schema": getattr(
399
+ parameter_model.config, "response_schema", None
400
+ ),
401
+ "response_json_schema": getattr(
402
+ parameter_model.config, "response_json_schema", None
403
+ ),
404
+ "include_all_fields": getattr(
405
+ parameter_model.config, "include_all_fields", None
406
+ ),
407
+ }
408
+ }
409
+ if getattr(parameter_model, "config", None)
410
+ else {}
411
+ ),
412
+ )
413
+
414
+ self._api_client._verify_response(return_value)
415
+ return return_value
416
+
417
+ def _get(
418
+ self,
419
+ *,
420
+ name: str,
421
+ config: Optional[types.GetAgentEngineSandboxConfigOrDict] = None,
422
+ ) -> types.SandboxEnvironment:
423
+ """
424
+ Gets an agent engine sandbox.
425
+
426
+ Args:
427
+ name (str): Required. A fully-qualified resource name or ID such as
428
+ "projects/123/locations/us-central1/reasoningEngines/456/sandboxEnvironments/789"
429
+ or a shortened name such as "reasoningEngines/456/sandboxEnvironments/789".
430
+
431
+ """
432
+
433
+ parameter_model = types._GetAgentEngineSandboxRequestParameters(
434
+ name=name,
435
+ config=config,
436
+ )
437
+
438
+ request_url_dict: Optional[dict[str, str]]
439
+ if not self._api_client.vertexai:
440
+ raise ValueError(
441
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
442
+ )
443
+ else:
444
+ request_dict = _GetAgentEngineSandboxRequestParameters_to_vertex(
445
+ parameter_model
446
+ )
447
+ request_url_dict = request_dict.get("_url")
448
+ if request_url_dict:
449
+ path = "{name}".format_map(request_url_dict)
450
+ else:
451
+ path = "{name}"
452
+
453
+ query_params = request_dict.get("_query")
454
+ if query_params:
455
+ path = f"{path}?{urlencode(query_params)}"
456
+ # TODO: remove the hack that pops config.
457
+ request_dict.pop("config", None)
458
+
459
+ http_options: Optional[types.HttpOptions] = None
460
+ if (
461
+ parameter_model.config is not None
462
+ and parameter_model.config.http_options is not None
463
+ ):
464
+ http_options = parameter_model.config.http_options
465
+
466
+ request_dict = _common.convert_to_dict(request_dict)
467
+ request_dict = _common.encode_unserializable_types(request_dict)
468
+
469
+ response = self._api_client.request("get", path, request_dict, http_options)
470
+
471
+ response_dict = {} if not response.body else json.loads(response.body)
472
+
473
+ return_value = types.SandboxEnvironment._from_response(
474
+ response=response_dict,
475
+ kwargs=(
476
+ {
477
+ "config": {
478
+ "response_schema": getattr(
479
+ parameter_model.config, "response_schema", None
480
+ ),
481
+ "response_json_schema": getattr(
482
+ parameter_model.config, "response_json_schema", None
483
+ ),
484
+ "include_all_fields": getattr(
485
+ parameter_model.config, "include_all_fields", None
486
+ ),
487
+ }
488
+ }
489
+ if getattr(parameter_model, "config", None)
490
+ else {}
491
+ ),
492
+ )
493
+
494
+ self._api_client._verify_response(return_value)
495
+ return return_value
496
+
497
+ def _list(
498
+ self,
499
+ *,
500
+ name: str,
501
+ config: Optional[types.ListAgentEngineSandboxesConfigOrDict] = None,
502
+ ) -> types.ListAgentEngineSandboxesResponse:
503
+ """
504
+ Lists Agent Engine sandboxes.
505
+
506
+ Args:
507
+ name (str): Required. The name of the Agent Engine to list sessions for. Format:
508
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
509
+ config (ListAgentEngineSandboxesConfig):
510
+ Optional. Additional configurations for listing the Agent Engine sandboxes.
511
+
512
+ Returns:
513
+ ListReasoningEnginesSandboxesResponse: The requested Agent Engine sandboxes.
514
+
515
+ """
516
+
517
+ parameter_model = types._ListAgentEngineSandboxesRequestParameters(
518
+ name=name,
519
+ config=config,
520
+ )
521
+
522
+ request_url_dict: Optional[dict[str, str]]
523
+ if not self._api_client.vertexai:
524
+ raise ValueError(
525
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
526
+ )
527
+ else:
528
+ request_dict = _ListAgentEngineSandboxesRequestParameters_to_vertex(
529
+ parameter_model
530
+ )
531
+ request_url_dict = request_dict.get("_url")
532
+ if request_url_dict:
533
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
534
+ else:
535
+ path = "{name}/sandboxEnvironments"
536
+
537
+ query_params = request_dict.get("_query")
538
+ if query_params:
539
+ path = f"{path}?{urlencode(query_params)}"
540
+ # TODO: remove the hack that pops config.
541
+ request_dict.pop("config", None)
542
+
543
+ http_options: Optional[types.HttpOptions] = None
544
+ if (
545
+ parameter_model.config is not None
546
+ and parameter_model.config.http_options is not None
547
+ ):
548
+ http_options = parameter_model.config.http_options
549
+
550
+ request_dict = _common.convert_to_dict(request_dict)
551
+ request_dict = _common.encode_unserializable_types(request_dict)
552
+
553
+ response = self._api_client.request("get", path, request_dict, http_options)
554
+
555
+ response_dict = {} if not response.body else json.loads(response.body)
556
+
557
+ return_value = types.ListAgentEngineSandboxesResponse._from_response(
558
+ response=response_dict,
559
+ kwargs=(
560
+ {
561
+ "config": {
562
+ "response_schema": getattr(
563
+ parameter_model.config, "response_schema", None
564
+ ),
565
+ "response_json_schema": getattr(
566
+ parameter_model.config, "response_json_schema", None
567
+ ),
568
+ "include_all_fields": getattr(
569
+ parameter_model.config, "include_all_fields", None
570
+ ),
571
+ }
572
+ }
573
+ if getattr(parameter_model, "config", None)
574
+ else {}
575
+ ),
576
+ )
577
+
578
+ self._api_client._verify_response(return_value)
579
+ return return_value
580
+
581
+ def _get_sandbox_operation(
582
+ self,
583
+ *,
584
+ operation_name: str,
585
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
586
+ ) -> types.AgentEngineSandboxOperation:
587
+ parameter_model = types._GetAgentEngineSandboxOperationParameters(
588
+ operation_name=operation_name,
589
+ config=config,
590
+ )
591
+
592
+ request_url_dict: Optional[dict[str, str]]
593
+ if not self._api_client.vertexai:
594
+ raise ValueError(
595
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
596
+ )
597
+ else:
598
+ request_dict = _GetAgentEngineSandboxOperationParameters_to_vertex(
599
+ parameter_model
600
+ )
601
+ request_url_dict = request_dict.get("_url")
602
+ if request_url_dict:
603
+ path = "{operationName}".format_map(request_url_dict)
604
+ else:
605
+ path = "{operationName}"
606
+
607
+ query_params = request_dict.get("_query")
608
+ if query_params:
609
+ path = f"{path}?{urlencode(query_params)}"
610
+ # TODO: remove the hack that pops config.
611
+ request_dict.pop("config", None)
612
+
613
+ http_options: Optional[types.HttpOptions] = None
614
+ if (
615
+ parameter_model.config is not None
616
+ and parameter_model.config.http_options is not None
617
+ ):
618
+ http_options = parameter_model.config.http_options
619
+
620
+ request_dict = _common.convert_to_dict(request_dict)
621
+ request_dict = _common.encode_unserializable_types(request_dict)
622
+
623
+ response = self._api_client.request("get", path, request_dict, http_options)
624
+
625
+ response_dict = {} if not response.body else json.loads(response.body)
626
+
627
+ return_value = types.AgentEngineSandboxOperation._from_response(
628
+ response=response_dict,
629
+ kwargs=(
630
+ {
631
+ "config": {
632
+ "response_schema": getattr(
633
+ parameter_model.config, "response_schema", None
634
+ ),
635
+ "response_json_schema": getattr(
636
+ parameter_model.config, "response_json_schema", None
637
+ ),
638
+ "include_all_fields": getattr(
639
+ parameter_model.config, "include_all_fields", None
640
+ ),
641
+ }
642
+ }
643
+ if getattr(parameter_model, "config", None)
644
+ else {}
645
+ ),
646
+ )
647
+
648
+ self._api_client._verify_response(return_value)
649
+ return return_value
650
+
651
+ _templates = None
652
+ _snapshots = None
653
+
654
+ @property
655
+ def templates(self) -> Any:
656
+ if self._templates is None:
657
+ try:
658
+ self._templates = __import__("importlib").import_module(
659
+ ".sandbox_templates", __package__
660
+ )
661
+ except ImportError as e:
662
+ raise ImportError(
663
+ "The 'agent_engines.sandboxes.templates' module requires "
664
+ "additional packages. Please install them using pip install "
665
+ "google-cloud-aiplatform[agent_engines]"
666
+ ) from e
667
+ return self._templates.SandboxTemplates(self._api_client)
668
+
669
+ @property
670
+ def snapshots(self) -> Any:
671
+ if self._snapshots is None:
672
+ try:
673
+ self._snapshots = __import__("importlib").import_module(
674
+ ".sandbox_snapshots", __package__
675
+ )
676
+ except ImportError as e:
677
+ raise ImportError(
678
+ "The 'agent_engines.sandboxes.snapshots' module requires "
679
+ "additional packages. Please install them using pip install "
680
+ "google-cloud-aiplatform[sandbox_snapshots]"
681
+ ) from e
682
+ return self._snapshots.SandboxSnapshots(self._api_client)
683
+
684
+ def create(
685
+ self,
686
+ *,
687
+ name: str,
688
+ poll_interval_seconds: float = 0.1,
689
+ spec: Optional[types.SandboxEnvironmentSpecOrDict] = None,
690
+ config: Optional[types.CreateAgentEngineSandboxConfigOrDict] = None,
691
+ ) -> types.AgentEngineSandboxOperation:
692
+ """Creates a new sandbox in the Agent Engine.
693
+
694
+ Args:
695
+ name (str):
696
+ Required. The name of the agent engine to create sandbox for.
697
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}
698
+ poll_interval_seconds (float):
699
+ Optional. The interval in seconds to poll for sandbox creation
700
+ completion.
701
+ spec (SandboxEnvironmentSpec):
702
+ Optional. The specification for the sandbox to create.
703
+ config (CreateAgentEngineSandboxConfigOrDict):
704
+ Optional. The configuration for the sandbox.
705
+
706
+ Returns:
707
+ AgentEngineSandboxOperation: The operation for creating the sandbox.
708
+ """
709
+ if config is None:
710
+ config = types.CreateAgentEngineSandboxConfig()
711
+ elif isinstance(config, dict):
712
+ config = types.CreateAgentEngineSandboxConfig.model_validate(config)
713
+
714
+ # A sandbox environment must be provided inline via `spec` (with an
715
+ # environment set), or by referencing an existing template or snapshot in
716
+ # `config`.
717
+ spec_has_environment = any(
718
+ _agent_engines_utils.has_field(spec, field_name)
719
+ for field_name in (
720
+ "code_execution_environment",
721
+ "computer_use_environment",
722
+ "shell_environment",
723
+ )
724
+ )
725
+ if (
726
+ not spec_has_environment
727
+ and not config.sandbox_environment_template
728
+ and not config.sandbox_environment_snapshot
729
+ ):
730
+ raise ValueError(
731
+ "A sandbox environment must be provided via `spec`, "
732
+ "`config.sandbox_environment_template`, or "
733
+ "`config.sandbox_environment_snapshot`."
734
+ )
735
+
736
+ if spec:
737
+ # Environments that can auto-provision a default sandbox
738
+ # environment template when the caller does not supply one. Ordered by
739
+ # precedence: the first matching environment is used.
740
+ environments = (
741
+ (
742
+ "shell_environment",
743
+ types.DefaultContainerCategory.DEFAULT_CONTAINER_CATEGORY_SHELL_SANDBOX,
744
+ "shell-sandbox-template",
745
+ ),
746
+ (
747
+ "computer_use_environment",
748
+ types.DefaultContainerCategory.DEFAULT_CONTAINER_CATEGORY_COMPUTER_USE,
749
+ "computer-use-template",
750
+ ),
751
+ )
752
+
753
+ for field_name, category, display_name in environments:
754
+ if not _agent_engines_utils.has_field(spec, field_name):
755
+ continue
756
+
757
+ if (
758
+ not config.sandbox_environment_template
759
+ and not config.sandbox_environment_snapshot
760
+ ):
761
+ default_container_environment = (
762
+ types.SandboxEnvironmentTemplateDefaultContainerEnvironment(
763
+ default_container_category=category,
764
+ )
765
+ )
766
+ template_operation = self.templates.create(
767
+ name=name,
768
+ display_name=display_name,
769
+ config=types.CreateSandboxEnvironmentTemplateConfig(
770
+ default_container_environment=default_container_environment,
771
+ ),
772
+ poll_interval_seconds=poll_interval_seconds,
773
+ )
774
+ if not template_operation.response:
775
+ raise ValueError(f"Error creating {display_name}.")
776
+ config.sandbox_environment_template = (
777
+ template_operation.response.name
778
+ )
779
+ break
780
+
781
+ operation = self._create(
782
+ name=name,
783
+ spec=spec,
784
+ config=config,
785
+ )
786
+ if config.wait_for_completion:
787
+ if not operation.done:
788
+ operation = _agent_engines_utils._await_operation(
789
+ operation_name=operation.name,
790
+ get_operation_fn=self._get_sandbox_operation,
791
+ poll_interval_seconds=poll_interval_seconds,
792
+ )
793
+ # We need to make a call to get the sandbox because the operation
794
+ # response might not contain the relevant fields.
795
+ if not operation.response:
796
+ raise ValueError("Error retrieving sandbox.")
797
+ operation.response = self.get(name=operation.response.name)
798
+ return operation
799
+
800
+ def list(
801
+ self,
802
+ *,
803
+ name: str,
804
+ config: Optional[types.ListAgentEngineSandboxesConfigOrDict] = None,
805
+ ) -> Iterator[types.SandboxEnvironment]:
806
+ """Lists Agent Engine sandboxes.
807
+
808
+ Args:
809
+ name (str):
810
+ Required. The name of the agent engine to list sandboxes for.
811
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}
812
+ config (ListAgentEngineSandboxConfig):
813
+ Optional. The configuration for the sandboxes to list.
814
+
815
+ Returns:
816
+ Iterable[SandboxEnvironment]: An iterable of agent engine sandboxes.
817
+ """
818
+ return Pager(
819
+ "sandbox_environments",
820
+ functools.partial(self._list, name=name),
821
+ self._list(name=name, config=config),
822
+ config,
823
+ )
824
+
825
+ def execute_code(
826
+ self,
827
+ *,
828
+ name: str,
829
+ input_data: dict[str, Any],
830
+ config: Optional[types.ExecuteCodeAgentEngineSandboxConfigOrDict] = None,
831
+ ) -> types.ExecuteSandboxEnvironmentResponse:
832
+ """Executes code in the Agent Engine sandbox.
833
+
834
+ Args:
835
+ name (str):
836
+ Required. The name of the agent engine sandbox to run code in.
837
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/SandboxEnvironments/{sandbox_id}
838
+ input_data (dict[str, Any]):
839
+ Required. The input to the code to execute.
840
+ config (ExecuteCodeAgentEngineSandboxConfigOrDict):
841
+ Optional. The configuration for the sandboxes to run code in.
842
+
843
+ Returns:
844
+ ExecuteSandboxEnvironmentResponse: The response from executing the code.
845
+ """
846
+ input_chunks = []
847
+
848
+ if input_data.get("code") is not None:
849
+ code = input_data.get("code", "")
850
+ json_code = json.dumps({"code": code}).encode("utf-8")
851
+ input_chunks.append(
852
+ types.Chunk(
853
+ mime_type="application/json",
854
+ data=json_code,
855
+ )
856
+ )
857
+
858
+ for file in input_data.get("files", []):
859
+ file_name = file.get("name", "")
860
+ input_chunks.append(
861
+ types.Chunk(
862
+ mime_type=file.get("mimeType", ""),
863
+ data=file.get("content", b""),
864
+ metadata={"attributes": {"file_name": file_name.encode("utf-8")}},
865
+ )
866
+ )
867
+
868
+ response = self._execute_code(
869
+ name=name,
870
+ inputs=input_chunks,
871
+ config=config,
872
+ )
873
+
874
+ output_chunks = []
875
+ if response.outputs is not None:
876
+ for output in response.outputs:
877
+ if output.mime_type is None:
878
+ # if mime_type is not available, try to guess the mime_type from the file_name.
879
+ if (
880
+ output.metadata is not None
881
+ and output.metadata.attributes is not None
882
+ ):
883
+ file_name = output.metadata.attributes.get(
884
+ "file_name", b""
885
+ ).decode("utf-8")
886
+ mime_type, _ = mimetypes.guess_type(file_name)
887
+ output.mime_type = mime_type
888
+ output_chunks.append(output)
889
+
890
+ response = types.ExecuteSandboxEnvironmentResponse(outputs=output_chunks)
891
+
892
+ return response
893
+
894
+ def get(
895
+ self,
896
+ *,
897
+ name: str,
898
+ config: Optional[types.GetAgentEngineSandboxConfigOrDict] = None,
899
+ ) -> types.SandboxEnvironment:
900
+ """Gets an agent engine sandbox.
901
+ Args:
902
+ name (str):
903
+ Required. A fully-qualified resource name or ID such as
904
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/SandboxEnvironments/{sandbox_id}
905
+ or a shortened name such as "reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox_id}".
906
+ config (GetAgentEngineSandboxConfigOrDict):
907
+ Optional. The configuration for the sandbox to get.
908
+
909
+ """
910
+ return self._get(name=name, config=config)
911
+
912
+ def delete(
913
+ self,
914
+ *,
915
+ name: str,
916
+ config: Optional[types.DeleteAgentEngineSandboxConfigOrDict] = None,
917
+ ) -> types.DeleteAgentEngineSandboxOperation:
918
+ """Deletes an agent engine sandbox.
919
+ Args:
920
+ name (str):
921
+ Required. A fully-qualified resource name or ID such as
922
+ projects/{project}/locations/{location}/reasoningEngines/{resource_id}/SandboxEnvironments/{sandbox_id}
923
+ or a shortened name such as "reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox_id}".
924
+ config (DeleteAgentEngineSandboxConfigOrDict):
925
+ Optional. The configuration for the sandbox to delete.
926
+ """
927
+ return self._delete(name=name, config=config)
928
+
929
+ def generate_access_token(
930
+ self,
931
+ service_account_email: str,
932
+ timeout: int = 3600,
933
+ ) -> str:
934
+ """Signs a JWT with a Google Cloud service account.
935
+
936
+ Args:
937
+ service_account_email (str):
938
+ Required. The email of the service account to use for signing.
939
+ timeout (int):
940
+ Optional. The timeout in seconds for the token. Defaults to 3600.
941
+
942
+ Returns:
943
+ str: The signed JWT.
944
+ """
945
+ issued_at = int(time.time())
946
+ payload = {
947
+ "iat": issued_at,
948
+ "exp": issued_at + timeout,
949
+ "iss": service_account_email,
950
+ "sub": service_account_email,
951
+ "nonce": secrets.randbelow(1000000000) + 1,
952
+ "aud": "https://aiplatform.googleapis.com/", # default audience for sandbox proxy
953
+ }
954
+ credentials, _ = google_auth.default(
955
+ scopes=["https://www.googleapis.com/auth/cloud-platform"]
956
+ )
957
+ # Resolve the endpoint against the credentials' universe domain so this
958
+ # keeps working off googleapis.com, the same way google.auth.iam does.
959
+ universe_domain = (
960
+ getattr(credentials, "universe_domain", None) or "googleapis.com"
961
+ )
962
+ session = google_auth_requests.AuthorizedSession(credentials) # type: ignore[no-untyped-call]
963
+ # The generated IAM client this replaced used the mTLS endpoint when
964
+ # client certificates are enabled, and so does the genai client that
965
+ # serves every other call in this module. configure_mtls_channel()
966
+ # self-gates on GOOGLE_API_USE_CLIENT_CERTIFICATE and on discovered
967
+ # workload certificates, so it is a no-op when mTLS is not in use.
968
+ session.configure_mtls_channel() # type: ignore[no-untyped-call]
969
+ # mTLS is only defined on the default universe.
970
+ host = f"iamcredentials.{universe_domain}"
971
+ if session.is_mtls and universe_domain == "googleapis.com":
972
+ host = f"iamcredentials.mtls.{universe_domain}"
973
+ url = (
974
+ f"https://{host}/v1/"
975
+ f"projects/-/serviceAccounts/{service_account_email}:signJwt"
976
+ )
977
+ # The generated IAM client this replaced retried UNAVAILABLE and
978
+ # DEADLINE_EXCEEDED with initial=0.1s and multiplier=1.3 under a 60s
979
+ # total deadline. requests does not retry at all, so reproduce that
980
+ # policy here rather than silently dropping it.
981
+ deadline = time.monotonic() + 60.0
982
+ delay = 0.1
983
+ while True:
984
+ response = session.post(
985
+ url,
986
+ json={"payload": json.dumps(payload)},
987
+ timeout=max(1.0, deadline - time.monotonic()),
988
+ )
989
+ if response.status_code not in (503, 504):
990
+ break
991
+ if deadline - time.monotonic() <= delay:
992
+ break
993
+ time.sleep(delay)
994
+ delay *= 1.3
995
+ response.raise_for_status()
996
+ return response.json()["signedJwt"] # type: ignore[no-any-return]
997
+
998
+ def send_command(
999
+ self,
1000
+ *,
1001
+ http_method: str,
1002
+ access_token: str,
1003
+ sandbox_environment: types.SandboxEnvironment,
1004
+ port: str = "8080",
1005
+ path: Optional[str] = None,
1006
+ query_params: Optional[dict[str, object]] = None,
1007
+ headers: Optional[dict[str, str]] = None,
1008
+ request_dict: Optional[dict[str, object]] = None,
1009
+ ) -> genai_types.HttpResponse:
1010
+ """Sends a command to the sandbox.
1011
+
1012
+ Args:
1013
+ http_method (str):
1014
+ Required. The HTTP method to use for the command.
1015
+ access_token (str):
1016
+ Required. The access token to use for authorization.
1017
+ sandbox_environment (types.SandboxEnvironment):
1018
+ Required. The sandbox environment to send the command to.
1019
+ port (str):
1020
+ Optional. The port to use for the token. Defaults to "8080". This should be one of the ports specified during template creation.
1021
+ path (str):
1022
+ Optional. The path to send the command to.
1023
+ query_params (dict[str, object]):
1024
+ Optional. The query parameters to include in the command.
1025
+ headers (dict[str, str]):
1026
+ Optional. The headers to include in the command.
1027
+ request_dict (dict[str, object]):
1028
+ Optional. The request body to include in the command.
1029
+
1030
+ Returns:
1031
+ genai_types.HttpResponse: The response from the sandbox.
1032
+ """
1033
+ headers = headers or {}
1034
+ request_dict = request_dict or {}
1035
+ connection_info = sandbox_environment.connection_info
1036
+ if not connection_info:
1037
+ raise ValueError("Connection info is not available.")
1038
+ if connection_info.load_balancer_hostname:
1039
+ endpoint = "https://" + connection_info.load_balancer_hostname
1040
+ elif connection_info.load_balancer_ip:
1041
+ endpoint = "http://" + connection_info.load_balancer_ip
1042
+ else:
1043
+ raise ValueError("Load balancer hostname or ip is not available.")
1044
+
1045
+ routing_token = connection_info.routing_token
1046
+ if not routing_token:
1047
+ raise ValueError("Routing token is not available.")
1048
+
1049
+ path = path or ""
1050
+ if query_params:
1051
+ path = f"{path}?{urlencode(query_params)}"
1052
+ headers["Authorization"] = f"Bearer {access_token}"
1053
+ headers["X-Sandbox-Routing-Token"] = routing_token
1054
+ headers["X-Sandbox-Port"] = port
1055
+ endpoint = endpoint + path if path.startswith("/") else endpoint + "/" + path
1056
+ http_options = genai_types.HttpOptions(headers=headers, base_url=endpoint)
1057
+ http_client = genai.Client(vertexai=True, http_options=http_options)
1058
+ # Full path is constructed in this function. The passed in path into request
1059
+ # function will not be used.
1060
+ response = http_client._api_client.request(http_method, path, request_dict)
1061
+ return genai_types.HttpResponse(
1062
+ headers=response.headers,
1063
+ body=response.body,
1064
+ )
1065
+
1066
+ def generate_browser_ws_headers(
1067
+ self,
1068
+ sandbox_environment: types.SandboxEnvironment,
1069
+ service_account_email: str,
1070
+ port: str = "8080",
1071
+ timeout: int = 3600,
1072
+ ) -> tuple[str, dict[str, str]]:
1073
+ """Generates the websocket upgrade headers for the browser.
1074
+
1075
+ Args:
1076
+ sandbox_environment (types.SandboxEnvironment):
1077
+ Required. The sandbox environment to generate websocket headers for.
1078
+ service_account_email (str):
1079
+ Required. The email of the service account to use for signing.
1080
+ port (str):
1081
+ Optional. The port to use for the CDP websocket endpoint url fetching.
1082
+ Defaults to "8080". This should be one of the ports specified during template creation.
1083
+ timeout (int):
1084
+ Optional. The timeout in seconds for the token. Defaults to 3600.
1085
+ Returns:
1086
+ tuple[str, dict[str, str]]: A tuple containing the websocket URL and
1087
+ the headers for websocket upgrade.
1088
+ """
1089
+ if not sandbox_environment.connection_info:
1090
+ raise ValueError("Connection info is not available.")
1091
+
1092
+ connection_info = sandbox_environment.connection_info
1093
+ if connection_info.load_balancer_hostname:
1094
+ ws_base_url = "wss://" + connection_info.load_balancer_hostname
1095
+ elif connection_info.load_balancer_ip:
1096
+ ws_base_url = "ws://" + connection_info.load_balancer_ip
1097
+ else:
1098
+ raise ValueError("Load balancer hostname or ip is not available.")
1099
+
1100
+ http_access_token = self.generate_access_token(service_account_email, timeout)
1101
+ response = self.send_command(
1102
+ http_method="GET",
1103
+ access_token=http_access_token,
1104
+ sandbox_environment=sandbox_environment,
1105
+ port=port,
1106
+ path="/cdp_ws_endpoint",
1107
+ )
1108
+ if not response:
1109
+ raise ValueError("Failed to get the websocket endpoint.")
1110
+ body_dict = json.loads(response.body)
1111
+ ws_path = body_dict["endpoint"]
1112
+ ws_url = ws_base_url + "/" + ws_path
1113
+
1114
+ # port 9222 is the default port for the browser websocket endpoint.
1115
+ ws_access_token = self.generate_access_token(service_account_email, timeout)
1116
+
1117
+ routing_token = connection_info.routing_token
1118
+
1119
+ headers = {}
1120
+ headers["Sec-WebSocket-Protocol"] = (
1121
+ f"v1.stream, {ws_access_token}, {routing_token}, 9222"
1122
+ )
1123
+ return ws_url, headers
1124
+
1125
+
1126
+ class AsyncSandboxes(_api_module.BaseModule):
1127
+
1128
+ async def _create(
1129
+ self,
1130
+ *,
1131
+ name: str,
1132
+ spec: Optional[types.SandboxEnvironmentSpecOrDict] = None,
1133
+ config: Optional[types.CreateAgentEngineSandboxConfigOrDict] = None,
1134
+ ) -> types.AgentEngineSandboxOperation:
1135
+ """
1136
+ Creates a new sandbox in the Agent Engine.
1137
+ """
1138
+
1139
+ parameter_model = types._CreateAgentEngineSandboxRequestParameters(
1140
+ name=name,
1141
+ spec=spec,
1142
+ config=config,
1143
+ )
1144
+
1145
+ request_url_dict: Optional[dict[str, str]]
1146
+ if not self._api_client.vertexai:
1147
+ raise ValueError(
1148
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1149
+ )
1150
+ else:
1151
+ request_dict = _CreateAgentEngineSandboxRequestParameters_to_vertex(
1152
+ parameter_model
1153
+ )
1154
+ request_url_dict = request_dict.get("_url")
1155
+ if request_url_dict:
1156
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
1157
+ else:
1158
+ path = "{name}/sandboxEnvironments"
1159
+
1160
+ query_params = request_dict.get("_query")
1161
+ if query_params:
1162
+ path = f"{path}?{urlencode(query_params)}"
1163
+ # TODO: remove the hack that pops config.
1164
+ request_dict.pop("config", None)
1165
+
1166
+ http_options: Optional[types.HttpOptions] = None
1167
+ if (
1168
+ parameter_model.config is not None
1169
+ and parameter_model.config.http_options is not None
1170
+ ):
1171
+ http_options = parameter_model.config.http_options
1172
+
1173
+ request_dict = _common.convert_to_dict(request_dict)
1174
+ request_dict = _common.encode_unserializable_types(request_dict)
1175
+
1176
+ response = await self._api_client.async_request(
1177
+ "post", path, request_dict, http_options
1178
+ )
1179
+
1180
+ response_dict = {} if not response.body else json.loads(response.body)
1181
+
1182
+ return_value = types.AgentEngineSandboxOperation._from_response(
1183
+ response=response_dict,
1184
+ kwargs=(
1185
+ {
1186
+ "config": {
1187
+ "response_schema": getattr(
1188
+ parameter_model.config, "response_schema", None
1189
+ ),
1190
+ "response_json_schema": getattr(
1191
+ parameter_model.config, "response_json_schema", None
1192
+ ),
1193
+ "include_all_fields": getattr(
1194
+ parameter_model.config, "include_all_fields", None
1195
+ ),
1196
+ }
1197
+ }
1198
+ if getattr(parameter_model, "config", None)
1199
+ else {}
1200
+ ),
1201
+ )
1202
+
1203
+ self._api_client._verify_response(return_value)
1204
+ return return_value
1205
+
1206
+ async def _delete(
1207
+ self,
1208
+ *,
1209
+ name: str,
1210
+ config: Optional[types.DeleteAgentEngineSandboxConfigOrDict] = None,
1211
+ ) -> types.DeleteAgentEngineSandboxOperation:
1212
+ """
1213
+ Delete an Agent Engine sandbox.
1214
+
1215
+ Args:
1216
+ name (str):
1217
+ Required. The name of the Agent Engine sandbox to be deleted. Format:
1218
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/sandboxEnvironments/{sandbox}`.
1219
+
1220
+ """
1221
+
1222
+ parameter_model = types._DeleteAgentEngineSandboxRequestParameters(
1223
+ name=name,
1224
+ config=config,
1225
+ )
1226
+
1227
+ request_url_dict: Optional[dict[str, str]]
1228
+ if not self._api_client.vertexai:
1229
+ raise ValueError(
1230
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1231
+ )
1232
+ else:
1233
+ request_dict = _DeleteAgentEngineSandboxRequestParameters_to_vertex(
1234
+ parameter_model
1235
+ )
1236
+ request_url_dict = request_dict.get("_url")
1237
+ if request_url_dict:
1238
+ path = "{name}".format_map(request_url_dict)
1239
+ else:
1240
+ path = "{name}"
1241
+
1242
+ query_params = request_dict.get("_query")
1243
+ if query_params:
1244
+ path = f"{path}?{urlencode(query_params)}"
1245
+ # TODO: remove the hack that pops config.
1246
+ request_dict.pop("config", None)
1247
+
1248
+ http_options: Optional[types.HttpOptions] = None
1249
+ if (
1250
+ parameter_model.config is not None
1251
+ and parameter_model.config.http_options is not None
1252
+ ):
1253
+ http_options = parameter_model.config.http_options
1254
+
1255
+ request_dict = _common.convert_to_dict(request_dict)
1256
+ request_dict = _common.encode_unserializable_types(request_dict)
1257
+
1258
+ response = await self._api_client.async_request(
1259
+ "delete", path, request_dict, http_options
1260
+ )
1261
+
1262
+ response_dict = {} if not response.body else json.loads(response.body)
1263
+
1264
+ return_value = types.DeleteAgentEngineSandboxOperation._from_response(
1265
+ response=response_dict,
1266
+ kwargs=(
1267
+ {
1268
+ "config": {
1269
+ "response_schema": getattr(
1270
+ parameter_model.config, "response_schema", None
1271
+ ),
1272
+ "response_json_schema": getattr(
1273
+ parameter_model.config, "response_json_schema", None
1274
+ ),
1275
+ "include_all_fields": getattr(
1276
+ parameter_model.config, "include_all_fields", None
1277
+ ),
1278
+ }
1279
+ }
1280
+ if getattr(parameter_model, "config", None)
1281
+ else {}
1282
+ ),
1283
+ )
1284
+
1285
+ self._api_client._verify_response(return_value)
1286
+ return return_value
1287
+
1288
+ async def _execute_code(
1289
+ self,
1290
+ *,
1291
+ name: str,
1292
+ inputs: Optional[builtins.list[types.ChunkOrDict]] = None,
1293
+ config: Optional[types.ExecuteCodeAgentEngineSandboxConfigOrDict] = None,
1294
+ ) -> types.ExecuteSandboxEnvironmentResponse:
1295
+ """
1296
+ Execute code in an Agent Engine sandbox.
1297
+ """
1298
+
1299
+ parameter_model = types._ExecuteCodeAgentEngineSandboxRequestParameters(
1300
+ name=name,
1301
+ inputs=inputs,
1302
+ config=config,
1303
+ )
1304
+
1305
+ request_url_dict: Optional[dict[str, str]]
1306
+ if not self._api_client.vertexai:
1307
+ raise ValueError(
1308
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1309
+ )
1310
+ else:
1311
+ request_dict = _ExecuteCodeAgentEngineSandboxRequestParameters_to_vertex(
1312
+ parameter_model
1313
+ )
1314
+ request_url_dict = request_dict.get("_url")
1315
+ if request_url_dict:
1316
+ path = "{name}/:execute".format_map(request_url_dict)
1317
+ else:
1318
+ path = "{name}/:execute"
1319
+
1320
+ query_params = request_dict.get("_query")
1321
+ if query_params:
1322
+ path = f"{path}?{urlencode(query_params)}"
1323
+ # TODO: remove the hack that pops config.
1324
+ request_dict.pop("config", None)
1325
+
1326
+ http_options: Optional[types.HttpOptions] = None
1327
+ if (
1328
+ parameter_model.config is not None
1329
+ and parameter_model.config.http_options is not None
1330
+ ):
1331
+ http_options = parameter_model.config.http_options
1332
+
1333
+ request_dict = _common.convert_to_dict(request_dict)
1334
+ request_dict = _common.encode_unserializable_types(request_dict)
1335
+
1336
+ response = await self._api_client.async_request(
1337
+ "post", path, request_dict, http_options
1338
+ )
1339
+
1340
+ response_dict = {} if not response.body else json.loads(response.body)
1341
+
1342
+ return_value = types.ExecuteSandboxEnvironmentResponse._from_response(
1343
+ response=response_dict,
1344
+ kwargs=(
1345
+ {
1346
+ "config": {
1347
+ "response_schema": getattr(
1348
+ parameter_model.config, "response_schema", None
1349
+ ),
1350
+ "response_json_schema": getattr(
1351
+ parameter_model.config, "response_json_schema", None
1352
+ ),
1353
+ "include_all_fields": getattr(
1354
+ parameter_model.config, "include_all_fields", None
1355
+ ),
1356
+ }
1357
+ }
1358
+ if getattr(parameter_model, "config", None)
1359
+ else {}
1360
+ ),
1361
+ )
1362
+
1363
+ self._api_client._verify_response(return_value)
1364
+ return return_value
1365
+
1366
+ async def _get(
1367
+ self,
1368
+ *,
1369
+ name: str,
1370
+ config: Optional[types.GetAgentEngineSandboxConfigOrDict] = None,
1371
+ ) -> types.SandboxEnvironment:
1372
+ """
1373
+ Gets an agent engine sandbox.
1374
+
1375
+ Args:
1376
+ name (str): Required. A fully-qualified resource name or ID such as
1377
+ "projects/123/locations/us-central1/reasoningEngines/456/sandboxEnvironments/789"
1378
+ or a shortened name such as "reasoningEngines/456/sandboxEnvironments/789".
1379
+
1380
+ """
1381
+
1382
+ parameter_model = types._GetAgentEngineSandboxRequestParameters(
1383
+ name=name,
1384
+ config=config,
1385
+ )
1386
+
1387
+ request_url_dict: Optional[dict[str, str]]
1388
+ if not self._api_client.vertexai:
1389
+ raise ValueError(
1390
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1391
+ )
1392
+ else:
1393
+ request_dict = _GetAgentEngineSandboxRequestParameters_to_vertex(
1394
+ parameter_model
1395
+ )
1396
+ request_url_dict = request_dict.get("_url")
1397
+ if request_url_dict:
1398
+ path = "{name}".format_map(request_url_dict)
1399
+ else:
1400
+ path = "{name}"
1401
+
1402
+ query_params = request_dict.get("_query")
1403
+ if query_params:
1404
+ path = f"{path}?{urlencode(query_params)}"
1405
+ # TODO: remove the hack that pops config.
1406
+ request_dict.pop("config", None)
1407
+
1408
+ http_options: Optional[types.HttpOptions] = None
1409
+ if (
1410
+ parameter_model.config is not None
1411
+ and parameter_model.config.http_options is not None
1412
+ ):
1413
+ http_options = parameter_model.config.http_options
1414
+
1415
+ request_dict = _common.convert_to_dict(request_dict)
1416
+ request_dict = _common.encode_unserializable_types(request_dict)
1417
+
1418
+ response = await self._api_client.async_request(
1419
+ "get", path, request_dict, http_options
1420
+ )
1421
+
1422
+ response_dict = {} if not response.body else json.loads(response.body)
1423
+
1424
+ return_value = types.SandboxEnvironment._from_response(
1425
+ response=response_dict,
1426
+ kwargs=(
1427
+ {
1428
+ "config": {
1429
+ "response_schema": getattr(
1430
+ parameter_model.config, "response_schema", None
1431
+ ),
1432
+ "response_json_schema": getattr(
1433
+ parameter_model.config, "response_json_schema", None
1434
+ ),
1435
+ "include_all_fields": getattr(
1436
+ parameter_model.config, "include_all_fields", None
1437
+ ),
1438
+ }
1439
+ }
1440
+ if getattr(parameter_model, "config", None)
1441
+ else {}
1442
+ ),
1443
+ )
1444
+
1445
+ self._api_client._verify_response(return_value)
1446
+ return return_value
1447
+
1448
+ async def _list(
1449
+ self,
1450
+ *,
1451
+ name: str,
1452
+ config: Optional[types.ListAgentEngineSandboxesConfigOrDict] = None,
1453
+ ) -> types.ListAgentEngineSandboxesResponse:
1454
+ """
1455
+ Lists Agent Engine sandboxes.
1456
+
1457
+ Args:
1458
+ name (str): Required. The name of the Agent Engine to list sessions for. Format:
1459
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`.
1460
+ config (ListAgentEngineSandboxesConfig):
1461
+ Optional. Additional configurations for listing the Agent Engine sandboxes.
1462
+
1463
+ Returns:
1464
+ ListReasoningEnginesSandboxesResponse: The requested Agent Engine sandboxes.
1465
+
1466
+ """
1467
+
1468
+ parameter_model = types._ListAgentEngineSandboxesRequestParameters(
1469
+ name=name,
1470
+ config=config,
1471
+ )
1472
+
1473
+ request_url_dict: Optional[dict[str, str]]
1474
+ if not self._api_client.vertexai:
1475
+ raise ValueError(
1476
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1477
+ )
1478
+ else:
1479
+ request_dict = _ListAgentEngineSandboxesRequestParameters_to_vertex(
1480
+ parameter_model
1481
+ )
1482
+ request_url_dict = request_dict.get("_url")
1483
+ if request_url_dict:
1484
+ path = "{name}/sandboxEnvironments".format_map(request_url_dict)
1485
+ else:
1486
+ path = "{name}/sandboxEnvironments"
1487
+
1488
+ query_params = request_dict.get("_query")
1489
+ if query_params:
1490
+ path = f"{path}?{urlencode(query_params)}"
1491
+ # TODO: remove the hack that pops config.
1492
+ request_dict.pop("config", None)
1493
+
1494
+ http_options: Optional[types.HttpOptions] = None
1495
+ if (
1496
+ parameter_model.config is not None
1497
+ and parameter_model.config.http_options is not None
1498
+ ):
1499
+ http_options = parameter_model.config.http_options
1500
+
1501
+ request_dict = _common.convert_to_dict(request_dict)
1502
+ request_dict = _common.encode_unserializable_types(request_dict)
1503
+
1504
+ response = await self._api_client.async_request(
1505
+ "get", path, request_dict, http_options
1506
+ )
1507
+
1508
+ response_dict = {} if not response.body else json.loads(response.body)
1509
+
1510
+ return_value = types.ListAgentEngineSandboxesResponse._from_response(
1511
+ response=response_dict,
1512
+ kwargs=(
1513
+ {
1514
+ "config": {
1515
+ "response_schema": getattr(
1516
+ parameter_model.config, "response_schema", None
1517
+ ),
1518
+ "response_json_schema": getattr(
1519
+ parameter_model.config, "response_json_schema", None
1520
+ ),
1521
+ "include_all_fields": getattr(
1522
+ parameter_model.config, "include_all_fields", None
1523
+ ),
1524
+ }
1525
+ }
1526
+ if getattr(parameter_model, "config", None)
1527
+ else {}
1528
+ ),
1529
+ )
1530
+
1531
+ self._api_client._verify_response(return_value)
1532
+ return return_value
1533
+
1534
+ async def _get_sandbox_operation(
1535
+ self,
1536
+ *,
1537
+ operation_name: str,
1538
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
1539
+ ) -> types.AgentEngineSandboxOperation:
1540
+ parameter_model = types._GetAgentEngineSandboxOperationParameters(
1541
+ operation_name=operation_name,
1542
+ config=config,
1543
+ )
1544
+
1545
+ request_url_dict: Optional[dict[str, str]]
1546
+ if not self._api_client.vertexai:
1547
+ raise ValueError(
1548
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1549
+ )
1550
+ else:
1551
+ request_dict = _GetAgentEngineSandboxOperationParameters_to_vertex(
1552
+ parameter_model
1553
+ )
1554
+ request_url_dict = request_dict.get("_url")
1555
+ if request_url_dict:
1556
+ path = "{operationName}".format_map(request_url_dict)
1557
+ else:
1558
+ path = "{operationName}"
1559
+
1560
+ query_params = request_dict.get("_query")
1561
+ if query_params:
1562
+ path = f"{path}?{urlencode(query_params)}"
1563
+ # TODO: remove the hack that pops config.
1564
+ request_dict.pop("config", None)
1565
+
1566
+ http_options: Optional[types.HttpOptions] = None
1567
+ if (
1568
+ parameter_model.config is not None
1569
+ and parameter_model.config.http_options is not None
1570
+ ):
1571
+ http_options = parameter_model.config.http_options
1572
+
1573
+ request_dict = _common.convert_to_dict(request_dict)
1574
+ request_dict = _common.encode_unserializable_types(request_dict)
1575
+
1576
+ response = await self._api_client.async_request(
1577
+ "get", path, request_dict, http_options
1578
+ )
1579
+
1580
+ response_dict = {} if not response.body else json.loads(response.body)
1581
+
1582
+ return_value = types.AgentEngineSandboxOperation._from_response(
1583
+ response=response_dict,
1584
+ kwargs=(
1585
+ {
1586
+ "config": {
1587
+ "response_schema": getattr(
1588
+ parameter_model.config, "response_schema", None
1589
+ ),
1590
+ "response_json_schema": getattr(
1591
+ parameter_model.config, "response_json_schema", None
1592
+ ),
1593
+ "include_all_fields": getattr(
1594
+ parameter_model.config, "include_all_fields", None
1595
+ ),
1596
+ }
1597
+ }
1598
+ if getattr(parameter_model, "config", None)
1599
+ else {}
1600
+ ),
1601
+ )
1602
+
1603
+ self._api_client._verify_response(return_value)
1604
+ return return_value