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,3931 @@
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 datetime
20
+ import importlib
21
+ import json
22
+ import logging
23
+ import typing
24
+ from typing import Any, AsyncIterator, Iterator, Optional, Sequence, Tuple, Union
25
+ from urllib.parse import urlencode
26
+ import warnings
27
+
28
+ from google.genai import _api_module
29
+ from google.genai import _common
30
+ from google.genai import types as genai_types
31
+ from google.genai._common import get_value_by_path as getv
32
+ from google.genai._common import set_value_by_path as setv
33
+ from google.genai.pagers import Pager
34
+
35
+ from . import _agent_engines_utils
36
+ from . import types
37
+
38
+ if typing.TYPE_CHECKING:
39
+ from . import sessions as sessions_module
40
+ from . import a2a_tasks as a2a_tasks_module
41
+ from . import runtimes as runtimes_module
42
+
43
+ _ = sessions_module
44
+ ___ = a2a_tasks_module
45
+ ____ = runtimes_module
46
+
47
+
48
+ logger = logging.getLogger("agentplatform_genai.agentengines")
49
+
50
+ logger.setLevel(logging.INFO)
51
+
52
+
53
+ def _AgentEngineOperation_from_vertex(
54
+ from_object: Union[dict[str, Any], object],
55
+ parent_object: Optional[dict[str, Any]] = None,
56
+ ) -> dict[str, Any]:
57
+ to_object: dict[str, Any] = {}
58
+ if getv(from_object, ["name"]) is not None:
59
+ setv(to_object, ["name"], getv(from_object, ["name"]))
60
+
61
+ if getv(from_object, ["metadata"]) is not None:
62
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
63
+
64
+ if getv(from_object, ["done"]) is not None:
65
+ setv(to_object, ["done"], getv(from_object, ["done"]))
66
+
67
+ if getv(from_object, ["error"]) is not None:
68
+ setv(to_object, ["error"], getv(from_object, ["error"]))
69
+
70
+ if getv(from_object, ["response"]) is not None:
71
+ setv(
72
+ to_object,
73
+ ["response"],
74
+ _ReasoningEngine_from_vertex(getv(from_object, ["response"]), to_object),
75
+ )
76
+
77
+ return to_object
78
+
79
+
80
+ def _CancelQueryJobAgentEngineConfig_to_vertex(
81
+ from_object: Union[dict[str, Any], object],
82
+ parent_object: Optional[dict[str, Any]] = None,
83
+ ) -> dict[str, Any]:
84
+ to_object: dict[str, Any] = {}
85
+
86
+ if getv(from_object, ["operation_name"]) is not None:
87
+ setv(parent_object, ["operationName"], getv(from_object, ["operation_name"]))
88
+
89
+ return to_object
90
+
91
+
92
+ def _CancelQueryJobAgentEngineRequestParameters_to_vertex(
93
+ from_object: Union[dict[str, Any], object],
94
+ parent_object: Optional[dict[str, Any]] = None,
95
+ ) -> dict[str, Any]:
96
+ to_object: dict[str, Any] = {}
97
+ if getv(from_object, ["name"]) is not None:
98
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
99
+
100
+ if getv(from_object, ["config"]) is not None:
101
+ setv(
102
+ to_object,
103
+ ["config"],
104
+ _CancelQueryJobAgentEngineConfig_to_vertex(
105
+ getv(from_object, ["config"]), to_object
106
+ ),
107
+ )
108
+
109
+ return to_object
110
+
111
+
112
+ def _CheckQueryJobAgentEngineConfig_to_vertex(
113
+ from_object: Union[dict[str, Any], object],
114
+ parent_object: Optional[dict[str, Any]] = None,
115
+ ) -> dict[str, Any]:
116
+ to_object: dict[str, Any] = {}
117
+
118
+ if getv(from_object, ["retrieve_result"]) is not None:
119
+ setv(parent_object, ["retrieveResult"], getv(from_object, ["retrieve_result"]))
120
+
121
+ return to_object
122
+
123
+
124
+ def _CheckQueryJobAgentEngineRequestParameters_to_vertex(
125
+ from_object: Union[dict[str, Any], object],
126
+ parent_object: Optional[dict[str, Any]] = None,
127
+ ) -> dict[str, Any]:
128
+ to_object: dict[str, Any] = {}
129
+ if getv(from_object, ["name"]) is not None:
130
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
131
+
132
+ if getv(from_object, ["config"]) is not None:
133
+ setv(
134
+ to_object,
135
+ ["config"],
136
+ _CheckQueryJobAgentEngineConfig_to_vertex(
137
+ getv(from_object, ["config"]), to_object
138
+ ),
139
+ )
140
+
141
+ return to_object
142
+
143
+
144
+ def _CheckQueryJobResult_from_vertex(
145
+ from_object: Union[dict[str, Any], object],
146
+ parent_object: Optional[dict[str, Any]] = None,
147
+ ) -> dict[str, Any]:
148
+ to_object: dict[str, Any] = {}
149
+
150
+ if getv(parent_object, ["operationName"]) is not None:
151
+ setv(to_object, ["operation_name"], getv(parent_object, ["operationName"]))
152
+
153
+ if getv(parent_object, ["outputGcsUri"]) is not None:
154
+ setv(to_object, ["output_gcs_uri"], getv(parent_object, ["outputGcsUri"]))
155
+
156
+ if getv(parent_object, ["status"]) is not None:
157
+ setv(to_object, ["status"], getv(parent_object, ["status"]))
158
+
159
+ if getv(parent_object, ["result"]) is not None:
160
+ setv(to_object, ["result"], getv(parent_object, ["result"]))
161
+
162
+ return to_object
163
+
164
+
165
+ def _CreateAgentEngineConfig_to_vertex(
166
+ from_object: Union[dict[str, Any], object],
167
+ parent_object: Optional[dict[str, Any]] = None,
168
+ ) -> dict[str, Any]:
169
+ to_object: dict[str, Any] = {}
170
+
171
+ if getv(from_object, ["display_name"]) is not None:
172
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
173
+
174
+ if getv(from_object, ["description"]) is not None:
175
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
176
+
177
+ if getv(from_object, ["spec"]) is not None:
178
+ setv(parent_object, ["spec"], getv(from_object, ["spec"]))
179
+
180
+ if getv(from_object, ["context_spec"]) is not None:
181
+ setv(
182
+ parent_object,
183
+ ["contextSpec"],
184
+ _ReasoningEngineContextSpec_to_vertex(
185
+ getv(from_object, ["context_spec"]), to_object
186
+ ),
187
+ )
188
+
189
+ if getv(from_object, ["psc_interface_config"]) is not None:
190
+ setv(
191
+ parent_object,
192
+ ["pscInterfaceConfig"],
193
+ getv(from_object, ["psc_interface_config"]),
194
+ )
195
+
196
+ if getv(from_object, ["encryption_spec"]) is not None:
197
+ setv(parent_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
198
+
199
+ if getv(from_object, ["labels"]) is not None:
200
+ setv(parent_object, ["labels"], getv(from_object, ["labels"]))
201
+
202
+ if getv(from_object, ["source_packages"]) is not None:
203
+ setv(parent_object, ["sourcePackages"], getv(from_object, ["source_packages"]))
204
+
205
+ if getv(from_object, ["entrypoint_module"]) is not None:
206
+ setv(
207
+ parent_object,
208
+ ["entrypointModule"],
209
+ getv(from_object, ["entrypoint_module"]),
210
+ )
211
+
212
+ if getv(from_object, ["entrypoint_object"]) is not None:
213
+ setv(
214
+ parent_object,
215
+ ["entrypointObject"],
216
+ getv(from_object, ["entrypoint_object"]),
217
+ )
218
+
219
+ if getv(from_object, ["requirements_file"]) is not None:
220
+ setv(
221
+ parent_object,
222
+ ["requirementsFile"],
223
+ getv(from_object, ["requirements_file"]),
224
+ )
225
+
226
+ if getv(from_object, ["agent_framework"]) is not None:
227
+ setv(parent_object, ["agentFramework"], getv(from_object, ["agent_framework"]))
228
+
229
+ if getv(from_object, ["python_version"]) is not None:
230
+ setv(parent_object, ["pythonVersion"], getv(from_object, ["python_version"]))
231
+
232
+ if getv(from_object, ["agent_gateway_config"]) is not None:
233
+ setv(
234
+ parent_object,
235
+ ["agentGatewayConfig"],
236
+ getv(from_object, ["agent_gateway_config"]),
237
+ )
238
+
239
+ return to_object
240
+
241
+
242
+ def _CreateAgentEngineRequestParameters_to_vertex(
243
+ from_object: Union[dict[str, Any], object],
244
+ parent_object: Optional[dict[str, Any]] = None,
245
+ ) -> dict[str, Any]:
246
+ to_object: dict[str, Any] = {}
247
+ if getv(from_object, ["config"]) is not None:
248
+ _CreateAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
249
+
250
+ return to_object
251
+
252
+
253
+ def _DeleteAgentEngineRequestParameters_to_vertex(
254
+ from_object: Union[dict[str, Any], object],
255
+ parent_object: Optional[dict[str, Any]] = None,
256
+ ) -> dict[str, Any]:
257
+ to_object: dict[str, Any] = {}
258
+ if getv(from_object, ["name"]) is not None:
259
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
260
+
261
+ if getv(from_object, ["force"]) is not None:
262
+ setv(to_object, ["force"], getv(from_object, ["force"]))
263
+
264
+ return to_object
265
+
266
+
267
+ def _GetAgentEngineOperationParameters_to_vertex(
268
+ from_object: Union[dict[str, Any], object],
269
+ parent_object: Optional[dict[str, Any]] = None,
270
+ ) -> dict[str, Any]:
271
+ to_object: dict[str, Any] = {}
272
+ if getv(from_object, ["operation_name"]) is not None:
273
+ setv(
274
+ to_object, ["_url", "operationName"], getv(from_object, ["operation_name"])
275
+ )
276
+
277
+ return to_object
278
+
279
+
280
+ def _GetAgentEngineRequestParameters_to_vertex(
281
+ from_object: Union[dict[str, Any], object],
282
+ parent_object: Optional[dict[str, Any]] = None,
283
+ ) -> dict[str, Any]:
284
+ to_object: dict[str, Any] = {}
285
+ if getv(from_object, ["name"]) is not None:
286
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
287
+
288
+ return to_object
289
+
290
+
291
+ def _ListAgentEngineConfig_to_vertex(
292
+ from_object: Union[dict[str, Any], object],
293
+ parent_object: Optional[dict[str, Any]] = None,
294
+ ) -> dict[str, Any]:
295
+ to_object: dict[str, Any] = {}
296
+
297
+ if getv(from_object, ["page_size"]) is not None:
298
+ setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))
299
+
300
+ if getv(from_object, ["page_token"]) is not None:
301
+ setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))
302
+
303
+ if getv(from_object, ["filter"]) is not None:
304
+ setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))
305
+
306
+ return to_object
307
+
308
+
309
+ def _ListAgentEngineRequestParameters_to_vertex(
310
+ from_object: Union[dict[str, Any], object],
311
+ parent_object: Optional[dict[str, Any]] = None,
312
+ ) -> dict[str, Any]:
313
+ to_object: dict[str, Any] = {}
314
+ if getv(from_object, ["config"]) is not None:
315
+ _ListAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
316
+
317
+ return to_object
318
+
319
+
320
+ def _ListReasoningEnginesResponse_from_vertex(
321
+ from_object: Union[dict[str, Any], object],
322
+ parent_object: Optional[dict[str, Any]] = None,
323
+ ) -> dict[str, Any]:
324
+ to_object: dict[str, Any] = {}
325
+ if getv(from_object, ["sdkHttpResponse"]) is not None:
326
+ setv(to_object, ["sdk_http_response"], getv(from_object, ["sdkHttpResponse"]))
327
+
328
+ if getv(from_object, ["nextPageToken"]) is not None:
329
+ setv(to_object, ["next_page_token"], getv(from_object, ["nextPageToken"]))
330
+
331
+ if getv(from_object, ["reasoningEngines"]) is not None:
332
+ setv(
333
+ to_object,
334
+ ["reasoning_engines"],
335
+ [
336
+ _ReasoningEngine_from_vertex(item, to_object)
337
+ for item in getv(from_object, ["reasoningEngines"])
338
+ ],
339
+ )
340
+
341
+ return to_object
342
+
343
+
344
+ def _QueryAgentEngineConfig_to_vertex(
345
+ from_object: Union[dict[str, Any], object],
346
+ parent_object: Optional[dict[str, Any]] = None,
347
+ ) -> dict[str, Any]:
348
+ to_object: dict[str, Any] = {}
349
+
350
+ if getv(from_object, ["class_method"]) is not None:
351
+ setv(parent_object, ["classMethod"], getv(from_object, ["class_method"]))
352
+
353
+ if getv(from_object, ["input"]) is not None:
354
+ setv(parent_object, ["input"], getv(from_object, ["input"]))
355
+
356
+ if getv(from_object, ["include_all_fields"]) is not None:
357
+ setv(to_object, ["includeAllFields"], getv(from_object, ["include_all_fields"]))
358
+
359
+ return to_object
360
+
361
+
362
+ def _QueryAgentEngineRequestParameters_to_vertex(
363
+ from_object: Union[dict[str, Any], object],
364
+ parent_object: Optional[dict[str, Any]] = None,
365
+ ) -> dict[str, Any]:
366
+ to_object: dict[str, Any] = {}
367
+ if getv(from_object, ["name"]) is not None:
368
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
369
+
370
+ if getv(from_object, ["config"]) is not None:
371
+ _QueryAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
372
+
373
+ return to_object
374
+
375
+
376
+ def _ReasoningEngineContextSpecMemoryBankConfig_from_vertex(
377
+ from_object: Union[dict[str, Any], object],
378
+ parent_object: Optional[dict[str, Any]] = None,
379
+ ) -> dict[str, Any]:
380
+ to_object: dict[str, Any] = {}
381
+ if getv(from_object, ["customizationConfigs"]) is not None:
382
+ setv(
383
+ to_object,
384
+ ["customization_configs"],
385
+ [item for item in getv(from_object, ["customizationConfigs"])],
386
+ )
387
+
388
+ if getv(from_object, ["disableMemoryRevisions"]) is not None:
389
+ setv(
390
+ to_object,
391
+ ["disable_memory_revisions"],
392
+ getv(from_object, ["disableMemoryRevisions"]),
393
+ )
394
+
395
+ if getv(from_object, ["generationConfig"]) is not None:
396
+ setv(to_object, ["generation_config"], getv(from_object, ["generationConfig"]))
397
+
398
+ if getv(from_object, ["similaritySearchConfig"]) is not None:
399
+ setv(
400
+ to_object,
401
+ ["similarity_search_config"],
402
+ getv(from_object, ["similaritySearchConfig"]),
403
+ )
404
+
405
+ if getv(from_object, ["ttlConfig"]) is not None:
406
+ setv(to_object, ["ttl_config"], getv(from_object, ["ttlConfig"]))
407
+
408
+ if getv(from_object, ["structuredMemoryConfigs"]) is not None:
409
+ setv(
410
+ to_object,
411
+ ["structured_memory_configs"],
412
+ [
413
+ _StructuredMemoryConfig_from_vertex(item, to_object)
414
+ for item in getv(from_object, ["structuredMemoryConfigs"])
415
+ ],
416
+ )
417
+
418
+ return to_object
419
+
420
+
421
+ def _ReasoningEngineContextSpecMemoryBankConfig_to_vertex(
422
+ from_object: Union[dict[str, Any], object],
423
+ parent_object: Optional[dict[str, Any]] = None,
424
+ ) -> dict[str, Any]:
425
+ to_object: dict[str, Any] = {}
426
+ if getv(from_object, ["customization_configs"]) is not None:
427
+ setv(
428
+ to_object,
429
+ ["customizationConfigs"],
430
+ [item for item in getv(from_object, ["customization_configs"])],
431
+ )
432
+
433
+ if getv(from_object, ["disable_memory_revisions"]) is not None:
434
+ setv(
435
+ to_object,
436
+ ["disableMemoryRevisions"],
437
+ getv(from_object, ["disable_memory_revisions"]),
438
+ )
439
+
440
+ if getv(from_object, ["generation_config"]) is not None:
441
+ setv(to_object, ["generationConfig"], getv(from_object, ["generation_config"]))
442
+
443
+ if getv(from_object, ["similarity_search_config"]) is not None:
444
+ setv(
445
+ to_object,
446
+ ["similaritySearchConfig"],
447
+ getv(from_object, ["similarity_search_config"]),
448
+ )
449
+
450
+ if getv(from_object, ["ttl_config"]) is not None:
451
+ setv(to_object, ["ttlConfig"], getv(from_object, ["ttl_config"]))
452
+
453
+ if getv(from_object, ["structured_memory_configs"]) is not None:
454
+ setv(
455
+ to_object,
456
+ ["structuredMemoryConfigs"],
457
+ [
458
+ _StructuredMemoryConfig_to_vertex(item, to_object)
459
+ for item in getv(from_object, ["structured_memory_configs"])
460
+ ],
461
+ )
462
+
463
+ return to_object
464
+
465
+
466
+ def _ReasoningEngineContextSpec_from_vertex(
467
+ from_object: Union[dict[str, Any], object],
468
+ parent_object: Optional[dict[str, Any]] = None,
469
+ ) -> dict[str, Any]:
470
+ to_object: dict[str, Any] = {}
471
+ if getv(from_object, ["memoryBankConfig"]) is not None:
472
+ setv(
473
+ to_object,
474
+ ["memory_bank_config"],
475
+ _ReasoningEngineContextSpecMemoryBankConfig_from_vertex(
476
+ getv(from_object, ["memoryBankConfig"]), to_object
477
+ ),
478
+ )
479
+
480
+ return to_object
481
+
482
+
483
+ def _ReasoningEngineContextSpec_to_vertex(
484
+ from_object: Union[dict[str, Any], object],
485
+ parent_object: Optional[dict[str, Any]] = None,
486
+ ) -> dict[str, Any]:
487
+ to_object: dict[str, Any] = {}
488
+ if getv(from_object, ["memory_bank_config"]) is not None:
489
+ setv(
490
+ to_object,
491
+ ["memoryBankConfig"],
492
+ _ReasoningEngineContextSpecMemoryBankConfig_to_vertex(
493
+ getv(from_object, ["memory_bank_config"]), to_object
494
+ ),
495
+ )
496
+
497
+ return to_object
498
+
499
+
500
+ def _ReasoningEngine_from_vertex(
501
+ from_object: Union[dict[str, Any], object],
502
+ parent_object: Optional[dict[str, Any]] = None,
503
+ ) -> dict[str, Any]:
504
+ to_object: dict[str, Any] = {}
505
+ if getv(from_object, ["encryptionSpec"]) is not None:
506
+ setv(to_object, ["encryption_spec"], getv(from_object, ["encryptionSpec"]))
507
+
508
+ if getv(from_object, ["contextSpec"]) is not None:
509
+ setv(
510
+ to_object,
511
+ ["context_spec"],
512
+ _ReasoningEngineContextSpec_from_vertex(
513
+ getv(from_object, ["contextSpec"]), to_object
514
+ ),
515
+ )
516
+
517
+ if getv(from_object, ["createTime"]) is not None:
518
+ setv(to_object, ["create_time"], getv(from_object, ["createTime"]))
519
+
520
+ if getv(from_object, ["description"]) is not None:
521
+ setv(to_object, ["description"], getv(from_object, ["description"]))
522
+
523
+ if getv(from_object, ["displayName"]) is not None:
524
+ setv(to_object, ["display_name"], getv(from_object, ["displayName"]))
525
+
526
+ if getv(from_object, ["etag"]) is not None:
527
+ setv(to_object, ["etag"], getv(from_object, ["etag"]))
528
+
529
+ if getv(from_object, ["labels"]) is not None:
530
+ setv(to_object, ["labels"], getv(from_object, ["labels"]))
531
+
532
+ if getv(from_object, ["name"]) is not None:
533
+ setv(to_object, ["name"], getv(from_object, ["name"]))
534
+
535
+ if getv(from_object, ["spec"]) is not None:
536
+ setv(to_object, ["spec"], getv(from_object, ["spec"]))
537
+
538
+ if getv(from_object, ["updateTime"]) is not None:
539
+ setv(to_object, ["update_time"], getv(from_object, ["updateTime"]))
540
+
541
+ if getv(from_object, ["trafficConfig"]) is not None:
542
+ setv(to_object, ["traffic_config"], getv(from_object, ["trafficConfig"]))
543
+
544
+ return to_object
545
+
546
+
547
+ def _RunQueryJobAgentEngineConfig_to_vertex(
548
+ from_object: Union[dict[str, Any], object],
549
+ parent_object: Optional[dict[str, Any]] = None,
550
+ ) -> dict[str, Any]:
551
+ to_object: dict[str, Any] = {}
552
+
553
+ if getv(from_object, ["input_gcs_uri"]) is not None:
554
+ setv(parent_object, ["inputGcsUri"], getv(from_object, ["input_gcs_uri"]))
555
+
556
+ if getv(from_object, ["output_gcs_uri"]) is not None:
557
+ setv(parent_object, ["outputGcsUri"], getv(from_object, ["output_gcs_uri"]))
558
+
559
+ return to_object
560
+
561
+
562
+ def _RunQueryJobAgentEngineRequestParameters_to_vertex(
563
+ from_object: Union[dict[str, Any], object],
564
+ parent_object: Optional[dict[str, Any]] = None,
565
+ ) -> dict[str, Any]:
566
+ to_object: dict[str, Any] = {}
567
+ if getv(from_object, ["name"]) is not None:
568
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
569
+
570
+ if getv(from_object, ["config"]) is not None:
571
+ setv(
572
+ to_object,
573
+ ["config"],
574
+ _RunQueryJobAgentEngineConfig_to_vertex(
575
+ getv(from_object, ["config"]), to_object
576
+ ),
577
+ )
578
+
579
+ return to_object
580
+
581
+
582
+ def _StructuredMemoryConfig_from_vertex(
583
+ from_object: Union[dict[str, Any], object],
584
+ parent_object: Optional[dict[str, Any]] = None,
585
+ ) -> dict[str, Any]:
586
+ to_object: dict[str, Any] = {}
587
+ if getv(from_object, ["schemaConfigs"]) is not None:
588
+ setv(
589
+ to_object,
590
+ ["schema_configs"],
591
+ [
592
+ _StructuredMemorySchemaConfig_from_vertex(item, to_object)
593
+ for item in getv(from_object, ["schemaConfigs"])
594
+ ],
595
+ )
596
+
597
+ if getv(from_object, ["scopeKeys"]) is not None:
598
+ setv(to_object, ["scope_keys"], getv(from_object, ["scopeKeys"]))
599
+
600
+ return to_object
601
+
602
+
603
+ def _StructuredMemoryConfig_to_vertex(
604
+ from_object: Union[dict[str, Any], object],
605
+ parent_object: Optional[dict[str, Any]] = None,
606
+ ) -> dict[str, Any]:
607
+ to_object: dict[str, Any] = {}
608
+ if getv(from_object, ["schema_configs"]) is not None:
609
+ setv(
610
+ to_object,
611
+ ["schemaConfigs"],
612
+ [
613
+ _StructuredMemorySchemaConfig_to_vertex(item, to_object)
614
+ for item in getv(from_object, ["schema_configs"])
615
+ ],
616
+ )
617
+
618
+ if getv(from_object, ["scope_keys"]) is not None:
619
+ setv(to_object, ["scopeKeys"], getv(from_object, ["scope_keys"]))
620
+
621
+ return to_object
622
+
623
+
624
+ def _StructuredMemorySchemaConfig_from_vertex(
625
+ from_object: Union[dict[str, Any], object],
626
+ parent_object: Optional[dict[str, Any]] = None,
627
+ ) -> dict[str, Any]:
628
+ to_object: dict[str, Any] = {}
629
+ if getv(from_object, ["schema"]) is not None:
630
+ setv(to_object, ["memory_schema"], getv(from_object, ["schema"]))
631
+
632
+ if getv(from_object, ["id"]) is not None:
633
+ setv(to_object, ["id"], getv(from_object, ["id"]))
634
+
635
+ if getv(from_object, ["memoryType"]) is not None:
636
+ setv(to_object, ["memory_type"], getv(from_object, ["memoryType"]))
637
+
638
+ return to_object
639
+
640
+
641
+ def _StructuredMemorySchemaConfig_to_vertex(
642
+ from_object: Union[dict[str, Any], object],
643
+ parent_object: Optional[dict[str, Any]] = None,
644
+ ) -> dict[str, Any]:
645
+ to_object: dict[str, Any] = {}
646
+ if getv(from_object, ["memory_schema"]) is not None:
647
+ setv(to_object, ["schema"], getv(from_object, ["memory_schema"]))
648
+
649
+ if getv(from_object, ["id"]) is not None:
650
+ setv(to_object, ["id"], getv(from_object, ["id"]))
651
+
652
+ if getv(from_object, ["memory_type"]) is not None:
653
+ setv(to_object, ["memoryType"], getv(from_object, ["memory_type"]))
654
+
655
+ return to_object
656
+
657
+
658
+ def _UpdateAgentEngineConfig_to_vertex(
659
+ from_object: Union[dict[str, Any], object],
660
+ parent_object: Optional[dict[str, Any]] = None,
661
+ ) -> dict[str, Any]:
662
+ to_object: dict[str, Any] = {}
663
+
664
+ if getv(from_object, ["display_name"]) is not None:
665
+ setv(parent_object, ["displayName"], getv(from_object, ["display_name"]))
666
+
667
+ if getv(from_object, ["description"]) is not None:
668
+ setv(parent_object, ["description"], getv(from_object, ["description"]))
669
+
670
+ if getv(from_object, ["spec"]) is not None:
671
+ setv(parent_object, ["spec"], getv(from_object, ["spec"]))
672
+
673
+ if getv(from_object, ["context_spec"]) is not None:
674
+ setv(
675
+ parent_object,
676
+ ["contextSpec"],
677
+ _ReasoningEngineContextSpec_to_vertex(
678
+ getv(from_object, ["context_spec"]), to_object
679
+ ),
680
+ )
681
+
682
+ if getv(from_object, ["psc_interface_config"]) is not None:
683
+ setv(
684
+ parent_object,
685
+ ["pscInterfaceConfig"],
686
+ getv(from_object, ["psc_interface_config"]),
687
+ )
688
+
689
+ if getv(from_object, ["encryption_spec"]) is not None:
690
+ setv(parent_object, ["encryptionSpec"], getv(from_object, ["encryption_spec"]))
691
+
692
+ if getv(from_object, ["labels"]) is not None:
693
+ setv(parent_object, ["labels"], getv(from_object, ["labels"]))
694
+
695
+ if getv(from_object, ["source_packages"]) is not None:
696
+ setv(parent_object, ["sourcePackages"], getv(from_object, ["source_packages"]))
697
+
698
+ if getv(from_object, ["entrypoint_module"]) is not None:
699
+ setv(
700
+ parent_object,
701
+ ["entrypointModule"],
702
+ getv(from_object, ["entrypoint_module"]),
703
+ )
704
+
705
+ if getv(from_object, ["entrypoint_object"]) is not None:
706
+ setv(
707
+ parent_object,
708
+ ["entrypointObject"],
709
+ getv(from_object, ["entrypoint_object"]),
710
+ )
711
+
712
+ if getv(from_object, ["requirements_file"]) is not None:
713
+ setv(
714
+ parent_object,
715
+ ["requirementsFile"],
716
+ getv(from_object, ["requirements_file"]),
717
+ )
718
+
719
+ if getv(from_object, ["agent_framework"]) is not None:
720
+ setv(parent_object, ["agentFramework"], getv(from_object, ["agent_framework"]))
721
+
722
+ if getv(from_object, ["python_version"]) is not None:
723
+ setv(parent_object, ["pythonVersion"], getv(from_object, ["python_version"]))
724
+
725
+ if getv(from_object, ["agent_gateway_config"]) is not None:
726
+ setv(
727
+ parent_object,
728
+ ["agentGatewayConfig"],
729
+ getv(from_object, ["agent_gateway_config"]),
730
+ )
731
+
732
+ if getv(from_object, ["update_mask"]) is not None:
733
+ setv(
734
+ parent_object, ["_query", "updateMask"], getv(from_object, ["update_mask"])
735
+ )
736
+
737
+ if getv(from_object, ["traffic_config"]) is not None:
738
+ setv(parent_object, ["trafficConfig"], getv(from_object, ["traffic_config"]))
739
+
740
+ return to_object
741
+
742
+
743
+ def _UpdateAgentEngineRequestParameters_to_vertex(
744
+ from_object: Union[dict[str, Any], object],
745
+ parent_object: Optional[dict[str, Any]] = None,
746
+ ) -> dict[str, Any]:
747
+ to_object: dict[str, Any] = {}
748
+ if getv(from_object, ["name"]) is not None:
749
+ setv(to_object, ["_url", "name"], getv(from_object, ["name"]))
750
+
751
+ if getv(from_object, ["config"]) is not None:
752
+ _UpdateAgentEngineConfig_to_vertex(getv(from_object, ["config"]), to_object)
753
+
754
+ return to_object
755
+
756
+
757
+ class AgentEngines(_api_module.BaseModule):
758
+
759
+ def cancel_query_job(
760
+ self,
761
+ *,
762
+ name: str,
763
+ config: Optional[types.CancelQueryJobAgentEngineConfigOrDict] = None,
764
+ ) -> types.CancelQueryJobResult:
765
+ """
766
+ Cancels a long-running query job on an Agent Engine.
767
+
768
+ Args:
769
+ name (str):
770
+ Required. The reasoning engine resource name.
771
+ config (CancelQueryJobAgentEngineConfigOrDict):
772
+ Optional. The configuration for the cancel_query_job.
773
+
774
+ """
775
+
776
+ parameter_model = types._CancelQueryJobAgentEngineRequestParameters(
777
+ name=name,
778
+ config=config,
779
+ )
780
+
781
+ request_url_dict: Optional[dict[str, str]]
782
+ if not self._api_client.vertexai:
783
+ raise ValueError(
784
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
785
+ )
786
+ else:
787
+ request_dict = _CancelQueryJobAgentEngineRequestParameters_to_vertex(
788
+ parameter_model
789
+ )
790
+ request_url_dict = request_dict.get("_url")
791
+ if request_url_dict:
792
+ path = "{name}:cancelAsyncQuery".format_map(request_url_dict)
793
+ else:
794
+ path = "{name}:cancelAsyncQuery"
795
+
796
+ query_params = request_dict.get("_query")
797
+ if query_params:
798
+ path = f"{path}?{urlencode(query_params)}"
799
+ # TODO: remove the hack that pops config.
800
+ request_dict.pop("config", None)
801
+
802
+ http_options: Optional[types.HttpOptions] = None
803
+ if (
804
+ parameter_model.config is not None
805
+ and parameter_model.config.http_options is not None
806
+ ):
807
+ http_options = parameter_model.config.http_options
808
+
809
+ request_dict = _common.convert_to_dict(request_dict)
810
+ request_dict = _common.encode_unserializable_types(request_dict)
811
+
812
+ response = self._api_client.request("post", path, request_dict, http_options)
813
+
814
+ response_dict = {} if not response.body else json.loads(response.body)
815
+
816
+ return_value = types.CancelQueryJobResult._from_response(
817
+ response=response_dict,
818
+ kwargs=(
819
+ {
820
+ "config": {
821
+ "response_schema": getattr(
822
+ parameter_model.config, "response_schema", None
823
+ ),
824
+ "response_json_schema": getattr(
825
+ parameter_model.config, "response_json_schema", None
826
+ ),
827
+ "include_all_fields": getattr(
828
+ parameter_model.config, "include_all_fields", None
829
+ ),
830
+ }
831
+ }
832
+ if getattr(parameter_model, "config", None)
833
+ else {}
834
+ ),
835
+ )
836
+
837
+ self._api_client._verify_response(return_value)
838
+ return return_value
839
+
840
+ def _check_query_job(
841
+ self,
842
+ *,
843
+ name: str,
844
+ config: Optional[types.CheckQueryJobAgentEngineConfigOrDict] = None,
845
+ ) -> types.CheckQueryJobResult:
846
+ """
847
+ Query an Agent Engine asynchronously.
848
+ """
849
+
850
+ parameter_model = types._CheckQueryJobAgentEngineRequestParameters(
851
+ name=name,
852
+ config=config,
853
+ )
854
+
855
+ request_url_dict: Optional[dict[str, str]]
856
+ if not self._api_client.vertexai:
857
+ raise ValueError(
858
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
859
+ )
860
+ else:
861
+ request_dict = _CheckQueryJobAgentEngineRequestParameters_to_vertex(
862
+ parameter_model
863
+ )
864
+ request_url_dict = request_dict.get("_url")
865
+ if request_url_dict:
866
+ path = "{name}:checkQueryJob".format_map(request_url_dict)
867
+ else:
868
+ path = "{name}:checkQueryJob"
869
+
870
+ query_params = request_dict.get("_query")
871
+ if query_params:
872
+ path = f"{path}?{urlencode(query_params)}"
873
+ # TODO: remove the hack that pops config.
874
+ request_dict.pop("config", None)
875
+
876
+ http_options: Optional[types.HttpOptions] = None
877
+ if (
878
+ parameter_model.config is not None
879
+ and parameter_model.config.http_options is not None
880
+ ):
881
+ http_options = parameter_model.config.http_options
882
+
883
+ request_dict = _common.convert_to_dict(request_dict)
884
+ request_dict = _common.encode_unserializable_types(request_dict)
885
+
886
+ response = self._api_client.request("post", path, request_dict, http_options)
887
+
888
+ response_dict = {} if not response.body else json.loads(response.body)
889
+
890
+ if self._api_client.vertexai:
891
+ response_dict = _CheckQueryJobResult_from_vertex(response_dict)
892
+
893
+ return_value = types.CheckQueryJobResult._from_response(
894
+ response=response_dict,
895
+ kwargs=(
896
+ {
897
+ "config": {
898
+ "response_schema": getattr(
899
+ parameter_model.config, "response_schema", None
900
+ ),
901
+ "response_json_schema": getattr(
902
+ parameter_model.config, "response_json_schema", None
903
+ ),
904
+ "include_all_fields": getattr(
905
+ parameter_model.config, "include_all_fields", None
906
+ ),
907
+ }
908
+ }
909
+ if getattr(parameter_model, "config", None)
910
+ else {}
911
+ ),
912
+ )
913
+
914
+ self._api_client._verify_response(return_value)
915
+ return return_value
916
+
917
+ def _run_query_job(
918
+ self,
919
+ *,
920
+ name: str,
921
+ config: Optional[types._RunQueryJobAgentEngineConfigOrDict] = None,
922
+ ) -> types.AgentEngineOperation:
923
+ """
924
+ Run a query job on an agent engine.
925
+ """
926
+
927
+ parameter_model = types._RunQueryJobAgentEngineRequestParameters(
928
+ name=name,
929
+ config=config,
930
+ )
931
+
932
+ request_url_dict: Optional[dict[str, str]]
933
+ if not self._api_client.vertexai:
934
+ raise ValueError(
935
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
936
+ )
937
+ else:
938
+ request_dict = _RunQueryJobAgentEngineRequestParameters_to_vertex(
939
+ parameter_model
940
+ )
941
+ request_url_dict = request_dict.get("_url")
942
+ if request_url_dict:
943
+ path = "{name}:asyncQuery".format_map(request_url_dict)
944
+ else:
945
+ path = "{name}:asyncQuery"
946
+
947
+ query_params = request_dict.get("_query")
948
+ if query_params:
949
+ path = f"{path}?{urlencode(query_params)}"
950
+ # TODO: remove the hack that pops config.
951
+ request_dict.pop("config", None)
952
+
953
+ http_options: Optional[types.HttpOptions] = None
954
+ if (
955
+ parameter_model.config is not None
956
+ and parameter_model.config.http_options is not None
957
+ ):
958
+ http_options = parameter_model.config.http_options
959
+
960
+ request_dict = _common.convert_to_dict(request_dict)
961
+ request_dict = _common.encode_unserializable_types(request_dict)
962
+
963
+ response = self._api_client.request("post", path, request_dict, http_options)
964
+
965
+ response_dict = {} if not response.body else json.loads(response.body)
966
+
967
+ if self._api_client.vertexai:
968
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
969
+
970
+ return_value = types.AgentEngineOperation._from_response(
971
+ response=response_dict,
972
+ kwargs=(
973
+ {
974
+ "config": {
975
+ "response_schema": getattr(
976
+ parameter_model.config, "response_schema", None
977
+ ),
978
+ "response_json_schema": getattr(
979
+ parameter_model.config, "response_json_schema", None
980
+ ),
981
+ "include_all_fields": getattr(
982
+ parameter_model.config, "include_all_fields", None
983
+ ),
984
+ }
985
+ }
986
+ if getattr(parameter_model, "config", None)
987
+ else {}
988
+ ),
989
+ )
990
+
991
+ self._api_client._verify_response(return_value)
992
+ return return_value
993
+
994
+ def _create(
995
+ self, *, config: Optional[types.CreateAgentEngineConfigOrDict] = None
996
+ ) -> types.AgentEngineOperation:
997
+ """
998
+ Creates a new Agent Engine.
999
+ """
1000
+
1001
+ parameter_model = types._CreateAgentEngineRequestParameters(
1002
+ config=config,
1003
+ )
1004
+
1005
+ request_url_dict: Optional[dict[str, str]]
1006
+ if not self._api_client.vertexai:
1007
+ raise ValueError(
1008
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1009
+ )
1010
+ else:
1011
+ request_dict = _CreateAgentEngineRequestParameters_to_vertex(
1012
+ parameter_model
1013
+ )
1014
+ request_url_dict = request_dict.get("_url")
1015
+ if request_url_dict:
1016
+ path = "reasoningEngines".format_map(request_url_dict)
1017
+ else:
1018
+ path = "reasoningEngines"
1019
+
1020
+ query_params = request_dict.get("_query")
1021
+ if query_params:
1022
+ path = f"{path}?{urlencode(query_params)}"
1023
+ # TODO: remove the hack that pops config.
1024
+ request_dict.pop("config", None)
1025
+
1026
+ http_options: Optional[types.HttpOptions] = None
1027
+ if (
1028
+ parameter_model.config is not None
1029
+ and parameter_model.config.http_options is not None
1030
+ ):
1031
+ http_options = parameter_model.config.http_options
1032
+
1033
+ request_dict = _common.convert_to_dict(request_dict)
1034
+ request_dict = _common.encode_unserializable_types(request_dict)
1035
+
1036
+ response = self._api_client.request("post", path, request_dict, http_options)
1037
+
1038
+ response_dict = {} if not response.body else json.loads(response.body)
1039
+
1040
+ if self._api_client.vertexai:
1041
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
1042
+
1043
+ return_value = types.AgentEngineOperation._from_response(
1044
+ response=response_dict,
1045
+ kwargs=(
1046
+ {
1047
+ "config": {
1048
+ "response_schema": getattr(
1049
+ parameter_model.config, "response_schema", None
1050
+ ),
1051
+ "response_json_schema": getattr(
1052
+ parameter_model.config, "response_json_schema", None
1053
+ ),
1054
+ "include_all_fields": getattr(
1055
+ parameter_model.config, "include_all_fields", None
1056
+ ),
1057
+ }
1058
+ }
1059
+ if getattr(parameter_model, "config", None)
1060
+ else {}
1061
+ ),
1062
+ )
1063
+
1064
+ self._api_client._verify_response(return_value)
1065
+ return return_value
1066
+
1067
+ def _delete(
1068
+ self,
1069
+ *,
1070
+ name: str,
1071
+ force: Optional[bool] = None,
1072
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
1073
+ ) -> types.DeleteAgentEngineOperation:
1074
+ """
1075
+ Delete an Agent Engine resource.
1076
+
1077
+ Args:
1078
+ name (str):
1079
+ Required. The name of the Agent Engine to be deleted. Format:
1080
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
1081
+ or `reasoningEngines/{resource_id}`.
1082
+ force (bool):
1083
+ Optional. If set to True, child resources will also be deleted.
1084
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
1085
+ the Agent Engine has undeleted child resources. Defaults to False.
1086
+ config (DeleteAgentEngineConfig):
1087
+ Optional. Additional configurations for deleting the Agent Engine.
1088
+
1089
+ """
1090
+
1091
+ parameter_model = types._DeleteAgentEngineRequestParameters(
1092
+ name=name,
1093
+ force=force,
1094
+ config=config,
1095
+ )
1096
+
1097
+ request_url_dict: Optional[dict[str, str]]
1098
+ if not self._api_client.vertexai:
1099
+ raise ValueError(
1100
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1101
+ )
1102
+ else:
1103
+ request_dict = _DeleteAgentEngineRequestParameters_to_vertex(
1104
+ parameter_model
1105
+ )
1106
+ request_url_dict = request_dict.get("_url")
1107
+ if request_url_dict:
1108
+ path = "{name}".format_map(request_url_dict)
1109
+ else:
1110
+ path = "{name}"
1111
+
1112
+ query_params = request_dict.get("_query")
1113
+ if query_params:
1114
+ path = f"{path}?{urlencode(query_params)}"
1115
+ # TODO: remove the hack that pops config.
1116
+ request_dict.pop("config", None)
1117
+
1118
+ http_options: Optional[types.HttpOptions] = None
1119
+ if (
1120
+ parameter_model.config is not None
1121
+ and parameter_model.config.http_options is not None
1122
+ ):
1123
+ http_options = parameter_model.config.http_options
1124
+
1125
+ request_dict = _common.convert_to_dict(request_dict)
1126
+ request_dict = _common.encode_unserializable_types(request_dict)
1127
+
1128
+ response = self._api_client.request("delete", path, request_dict, http_options)
1129
+
1130
+ response_dict = {} if not response.body else json.loads(response.body)
1131
+
1132
+ return_value = types.DeleteAgentEngineOperation._from_response(
1133
+ response=response_dict,
1134
+ kwargs=(
1135
+ {
1136
+ "config": {
1137
+ "response_schema": getattr(
1138
+ parameter_model.config, "response_schema", None
1139
+ ),
1140
+ "response_json_schema": getattr(
1141
+ parameter_model.config, "response_json_schema", None
1142
+ ),
1143
+ "include_all_fields": getattr(
1144
+ parameter_model.config, "include_all_fields", None
1145
+ ),
1146
+ }
1147
+ }
1148
+ if getattr(parameter_model, "config", None)
1149
+ else {}
1150
+ ),
1151
+ )
1152
+
1153
+ self._api_client._verify_response(return_value)
1154
+ return return_value
1155
+
1156
+ def _get(
1157
+ self, *, name: str, config: Optional[types.GetAgentEngineConfigOrDict] = None
1158
+ ) -> types.ReasoningEngine:
1159
+ """
1160
+ Get an Agent Engine instance.
1161
+ """
1162
+
1163
+ parameter_model = types._GetAgentEngineRequestParameters(
1164
+ name=name,
1165
+ config=config,
1166
+ )
1167
+
1168
+ request_url_dict: Optional[dict[str, str]]
1169
+ if not self._api_client.vertexai:
1170
+ raise ValueError(
1171
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1172
+ )
1173
+ else:
1174
+ request_dict = _GetAgentEngineRequestParameters_to_vertex(parameter_model)
1175
+ request_url_dict = request_dict.get("_url")
1176
+ if request_url_dict:
1177
+ path = "{name}".format_map(request_url_dict)
1178
+ else:
1179
+ path = "{name}"
1180
+
1181
+ query_params = request_dict.get("_query")
1182
+ if query_params:
1183
+ path = f"{path}?{urlencode(query_params)}"
1184
+ # TODO: remove the hack that pops config.
1185
+ request_dict.pop("config", None)
1186
+
1187
+ http_options: Optional[types.HttpOptions] = None
1188
+ if (
1189
+ parameter_model.config is not None
1190
+ and parameter_model.config.http_options is not None
1191
+ ):
1192
+ http_options = parameter_model.config.http_options
1193
+
1194
+ request_dict = _common.convert_to_dict(request_dict)
1195
+ request_dict = _common.encode_unserializable_types(request_dict)
1196
+
1197
+ response = self._api_client.request("get", path, request_dict, http_options)
1198
+
1199
+ response_dict = {} if not response.body else json.loads(response.body)
1200
+
1201
+ if self._api_client.vertexai:
1202
+ response_dict = _ReasoningEngine_from_vertex(response_dict)
1203
+
1204
+ return_value = types.ReasoningEngine._from_response(
1205
+ response=response_dict,
1206
+ kwargs=(
1207
+ {
1208
+ "config": {
1209
+ "response_schema": getattr(
1210
+ parameter_model.config, "response_schema", None
1211
+ ),
1212
+ "response_json_schema": getattr(
1213
+ parameter_model.config, "response_json_schema", None
1214
+ ),
1215
+ "include_all_fields": getattr(
1216
+ parameter_model.config, "include_all_fields", None
1217
+ ),
1218
+ }
1219
+ }
1220
+ if getattr(parameter_model, "config", None)
1221
+ else {}
1222
+ ),
1223
+ )
1224
+
1225
+ self._api_client._verify_response(return_value)
1226
+ return return_value
1227
+
1228
+ def _list(
1229
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
1230
+ ) -> types.ListReasoningEnginesResponse:
1231
+ """
1232
+ Lists Agent Engines.
1233
+ """
1234
+
1235
+ parameter_model = types._ListAgentEngineRequestParameters(
1236
+ config=config,
1237
+ )
1238
+
1239
+ request_url_dict: Optional[dict[str, str]]
1240
+ if not self._api_client.vertexai:
1241
+ raise ValueError(
1242
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1243
+ )
1244
+ else:
1245
+ request_dict = _ListAgentEngineRequestParameters_to_vertex(parameter_model)
1246
+ request_url_dict = request_dict.get("_url")
1247
+ if request_url_dict:
1248
+ path = "reasoningEngines".format_map(request_url_dict)
1249
+ else:
1250
+ path = "reasoningEngines"
1251
+
1252
+ query_params = request_dict.get("_query")
1253
+ if query_params:
1254
+ path = f"{path}?{urlencode(query_params)}"
1255
+ # TODO: remove the hack that pops config.
1256
+ request_dict.pop("config", None)
1257
+
1258
+ http_options: Optional[types.HttpOptions] = None
1259
+ if (
1260
+ parameter_model.config is not None
1261
+ and parameter_model.config.http_options is not None
1262
+ ):
1263
+ http_options = parameter_model.config.http_options
1264
+
1265
+ request_dict = _common.convert_to_dict(request_dict)
1266
+ request_dict = _common.encode_unserializable_types(request_dict)
1267
+
1268
+ response = self._api_client.request("get", path, request_dict, http_options)
1269
+
1270
+ response_dict = {} if not response.body else json.loads(response.body)
1271
+
1272
+ if self._api_client.vertexai:
1273
+ response_dict = _ListReasoningEnginesResponse_from_vertex(response_dict)
1274
+
1275
+ return_value = types.ListReasoningEnginesResponse._from_response(
1276
+ response=response_dict,
1277
+ kwargs=(
1278
+ {
1279
+ "config": {
1280
+ "response_schema": getattr(
1281
+ parameter_model.config, "response_schema", None
1282
+ ),
1283
+ "response_json_schema": getattr(
1284
+ parameter_model.config, "response_json_schema", None
1285
+ ),
1286
+ "include_all_fields": getattr(
1287
+ parameter_model.config, "include_all_fields", None
1288
+ ),
1289
+ }
1290
+ }
1291
+ if getattr(parameter_model, "config", None)
1292
+ else {}
1293
+ ),
1294
+ )
1295
+
1296
+ self._api_client._verify_response(return_value)
1297
+ return return_value
1298
+
1299
+ def _get_agent_operation(
1300
+ self,
1301
+ *,
1302
+ operation_name: str,
1303
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
1304
+ ) -> types.AgentEngineOperation:
1305
+ parameter_model = types._GetAgentEngineOperationParameters(
1306
+ operation_name=operation_name,
1307
+ config=config,
1308
+ )
1309
+
1310
+ request_url_dict: Optional[dict[str, str]]
1311
+ if not self._api_client.vertexai:
1312
+ raise ValueError(
1313
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1314
+ )
1315
+ else:
1316
+ request_dict = _GetAgentEngineOperationParameters_to_vertex(parameter_model)
1317
+ request_url_dict = request_dict.get("_url")
1318
+ if request_url_dict:
1319
+ path = "{operationName}".format_map(request_url_dict)
1320
+ else:
1321
+ path = "{operationName}"
1322
+
1323
+ query_params = request_dict.get("_query")
1324
+ if query_params:
1325
+ path = f"{path}?{urlencode(query_params)}"
1326
+ # TODO: remove the hack that pops config.
1327
+ request_dict.pop("config", None)
1328
+
1329
+ http_options: Optional[types.HttpOptions] = None
1330
+ if (
1331
+ parameter_model.config is not None
1332
+ and parameter_model.config.http_options is not None
1333
+ ):
1334
+ http_options = parameter_model.config.http_options
1335
+
1336
+ request_dict = _common.convert_to_dict(request_dict)
1337
+ request_dict = _common.encode_unserializable_types(request_dict)
1338
+
1339
+ response = self._api_client.request("get", path, request_dict, http_options)
1340
+
1341
+ response_dict = {} if not response.body else json.loads(response.body)
1342
+
1343
+ if self._api_client.vertexai:
1344
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
1345
+
1346
+ return_value = types.AgentEngineOperation._from_response(
1347
+ response=response_dict,
1348
+ kwargs=(
1349
+ {
1350
+ "config": {
1351
+ "response_schema": getattr(
1352
+ parameter_model.config, "response_schema", None
1353
+ ),
1354
+ "response_json_schema": getattr(
1355
+ parameter_model.config, "response_json_schema", None
1356
+ ),
1357
+ "include_all_fields": getattr(
1358
+ parameter_model.config, "include_all_fields", None
1359
+ ),
1360
+ }
1361
+ }
1362
+ if getattr(parameter_model, "config", None)
1363
+ else {}
1364
+ ),
1365
+ )
1366
+
1367
+ self._api_client._verify_response(return_value)
1368
+ return return_value
1369
+
1370
+ def _query(
1371
+ self, *, name: str, config: Optional[types.QueryAgentEngineConfigOrDict] = None
1372
+ ) -> types.QueryReasoningEngineResponse:
1373
+ """
1374
+ Query an Agent Engine.
1375
+ """
1376
+
1377
+ parameter_model = types._QueryAgentEngineRequestParameters(
1378
+ name=name,
1379
+ config=config,
1380
+ )
1381
+
1382
+ request_url_dict: Optional[dict[str, str]]
1383
+ if not self._api_client.vertexai:
1384
+ raise ValueError(
1385
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1386
+ )
1387
+ else:
1388
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
1389
+ request_url_dict = request_dict.get("_url")
1390
+ if request_url_dict:
1391
+ path = "{name}:query".format_map(request_url_dict)
1392
+ else:
1393
+ path = "{name}:query"
1394
+
1395
+ query_params = request_dict.get("_query")
1396
+ if query_params:
1397
+ path = f"{path}?{urlencode(query_params)}"
1398
+ # TODO: remove the hack that pops config.
1399
+ request_dict.pop("config", None)
1400
+
1401
+ http_options: Optional[types.HttpOptions] = None
1402
+ if (
1403
+ parameter_model.config is not None
1404
+ and parameter_model.config.http_options is not None
1405
+ ):
1406
+ http_options = parameter_model.config.http_options
1407
+
1408
+ request_dict = _common.convert_to_dict(request_dict)
1409
+ request_dict = _common.encode_unserializable_types(request_dict)
1410
+
1411
+ response = self._api_client.request("post", path, request_dict, http_options)
1412
+
1413
+ response_dict = {} if not response.body else json.loads(response.body)
1414
+
1415
+ return_value = types.QueryReasoningEngineResponse._from_response(
1416
+ response=response_dict,
1417
+ kwargs=(
1418
+ {
1419
+ "config": {
1420
+ "response_schema": getattr(
1421
+ parameter_model.config, "response_schema", None
1422
+ ),
1423
+ "response_json_schema": getattr(
1424
+ parameter_model.config, "response_json_schema", None
1425
+ ),
1426
+ "include_all_fields": getattr(
1427
+ parameter_model.config, "include_all_fields", None
1428
+ ),
1429
+ }
1430
+ }
1431
+ if getattr(parameter_model, "config", None)
1432
+ else {}
1433
+ ),
1434
+ )
1435
+
1436
+ self._api_client._verify_response(return_value)
1437
+ return return_value
1438
+
1439
+ def _update(
1440
+ self, *, name: str, config: Optional[types.UpdateAgentEngineConfigOrDict] = None
1441
+ ) -> types.AgentEngineOperation:
1442
+ """
1443
+ Updates an Agent Engine.
1444
+ """
1445
+
1446
+ parameter_model = types._UpdateAgentEngineRequestParameters(
1447
+ name=name,
1448
+ config=config,
1449
+ )
1450
+
1451
+ request_url_dict: Optional[dict[str, str]]
1452
+ if not self._api_client.vertexai:
1453
+ raise ValueError(
1454
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
1455
+ )
1456
+ else:
1457
+ request_dict = _UpdateAgentEngineRequestParameters_to_vertex(
1458
+ parameter_model
1459
+ )
1460
+ request_url_dict = request_dict.get("_url")
1461
+ if request_url_dict:
1462
+ path = "{name}".format_map(request_url_dict)
1463
+ else:
1464
+ path = "{name}"
1465
+
1466
+ query_params = request_dict.get("_query")
1467
+ if query_params:
1468
+ path = f"{path}?{urlencode(query_params)}"
1469
+ # TODO: remove the hack that pops config.
1470
+ request_dict.pop("config", None)
1471
+
1472
+ http_options: Optional[types.HttpOptions] = None
1473
+ if (
1474
+ parameter_model.config is not None
1475
+ and parameter_model.config.http_options is not None
1476
+ ):
1477
+ http_options = parameter_model.config.http_options
1478
+
1479
+ request_dict = _common.convert_to_dict(request_dict)
1480
+ request_dict = _common.encode_unserializable_types(request_dict)
1481
+
1482
+ response = self._api_client.request("patch", path, request_dict, http_options)
1483
+
1484
+ response_dict = {} if not response.body else json.loads(response.body)
1485
+
1486
+ if self._api_client.vertexai:
1487
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
1488
+
1489
+ return_value = types.AgentEngineOperation._from_response(
1490
+ response=response_dict,
1491
+ kwargs=(
1492
+ {
1493
+ "config": {
1494
+ "response_schema": getattr(
1495
+ parameter_model.config, "response_schema", None
1496
+ ),
1497
+ "response_json_schema": getattr(
1498
+ parameter_model.config, "response_json_schema", None
1499
+ ),
1500
+ "include_all_fields": getattr(
1501
+ parameter_model.config, "include_all_fields", None
1502
+ ),
1503
+ }
1504
+ }
1505
+ if getattr(parameter_model, "config", None)
1506
+ else {}
1507
+ ),
1508
+ )
1509
+
1510
+ self._api_client._verify_response(return_value)
1511
+ return return_value
1512
+
1513
+ _a2a_tasks = None
1514
+ _sandboxes = None
1515
+ _sessions = None
1516
+ _runtimes = None
1517
+
1518
+ @property
1519
+ def runtimes(self) -> "runtimes_module.Runtimes":
1520
+ if self._runtimes is None:
1521
+ try:
1522
+ # We need to lazy load the runtimes module to handle the
1523
+ # possibility of ImportError when dependencies are not installed.
1524
+ self._runtimes = importlib.import_module(".runtimes", __package__)
1525
+ except ImportError as e:
1526
+ raise ImportError(
1527
+ "The 'agent_engines.runtimes' module requires additional "
1528
+ "packages. Please install them using pip install "
1529
+ "google-cloud-aiplatform[agent_engines]"
1530
+ ) from e
1531
+ return self._runtimes.Runtimes(self._api_client) # type: ignore[no-any-return]
1532
+
1533
+ @property
1534
+ def a2a_tasks(self) -> "a2a_tasks_module.A2aTasks":
1535
+ if self._a2a_tasks is None:
1536
+ try:
1537
+ # We need to lazy load the a2a_tasks module to handle the
1538
+ # possibility of ImportError when dependencies are not installed.
1539
+ self._a2a_tasks = importlib.import_module(".a2a_tasks", __package__)
1540
+ except ImportError as e:
1541
+ raise ImportError(
1542
+ "The 'agent_engines.a2a_tasks' module requires additional "
1543
+ "packages. Please install them using pip install "
1544
+ "google-cloud-aiplatform[agent_engines]"
1545
+ ) from e
1546
+ return self._a2a_tasks.A2aTasks(self._api_client) # type: ignore[no-any-return]
1547
+
1548
+ @property
1549
+ def sandboxes(self) -> Any:
1550
+ if self._sandboxes is None:
1551
+ try:
1552
+ # We need to lazy load the sandboxes module to handle the
1553
+ # possibility of ImportError when dependencies are not installed.
1554
+ self._sandboxes = importlib.import_module(".sandboxes", __package__)
1555
+ except ImportError as e:
1556
+ raise ImportError(
1557
+ "The agent_engines.sandboxes module requires additional packages. "
1558
+ "Please install them using pip install "
1559
+ "google-cloud-aiplatform[agent_engines]"
1560
+ ) from e
1561
+ return self._sandboxes.Sandboxes(self._api_client)
1562
+
1563
+ @property
1564
+ def sessions(self) -> "sessions_module.Sessions":
1565
+ if self._sessions is None:
1566
+ try:
1567
+ # We need to lazy load the sessions module to handle the
1568
+ # possibility of ImportError when dependencies are not installed.
1569
+ self._sessions = importlib.import_module(".sessions", __package__)
1570
+ except ImportError as e:
1571
+ raise ImportError(
1572
+ "The agent_engines.sessions module requires additional packages. "
1573
+ "Please install them using pip install "
1574
+ "google-cloud-aiplatform[agent_engines]"
1575
+ ) from e
1576
+ return self._sessions.Sessions(self._api_client) # type: ignore[no-any-return]
1577
+
1578
+ def _list_pager(
1579
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
1580
+ ) -> Pager[types.ReasoningEngine]:
1581
+ return Pager(
1582
+ "reasoning_engines",
1583
+ self._list,
1584
+ self._list(config=config),
1585
+ config,
1586
+ )
1587
+
1588
+ def check_query_job(
1589
+ self,
1590
+ *,
1591
+ name: str,
1592
+ config: Optional[types.CheckQueryJobAgentEngineConfigOrDict] = None,
1593
+ ) -> types.CheckQueryJobResult:
1594
+ """Checks a query job on an agent engine and optionally returns the results.
1595
+
1596
+ Args:
1597
+ name (str):
1598
+ Required. A fully-qualified resource name or ID.
1599
+ config (CheckQueryJobAgentEngineConfigOrDict):
1600
+ Optional. The configuration for the check_query_job. If not provided,
1601
+ the default configuration will be used. This can be used to specify
1602
+ the following fields:
1603
+ - retrieve_result: Whether to retrieve the results of the query job.
1604
+ """
1605
+ from google.cloud import storage # type: ignore[attr-defined]
1606
+ import json
1607
+
1608
+ if config is None:
1609
+ config = types.CheckQueryJobAgentEngineConfig()
1610
+ elif isinstance(config, dict):
1611
+ config = types.CheckQueryJobAgentEngineConfig(**config)
1612
+
1613
+ raw_response = self._api_client.request("get", name, {})
1614
+ if hasattr(raw_response, "body"):
1615
+ operation = (
1616
+ json.loads(raw_response.body)
1617
+ if isinstance(raw_response.body, str)
1618
+ else raw_response.body
1619
+ )
1620
+ else:
1621
+ operation = raw_response
1622
+
1623
+ status = "RUNNING"
1624
+ if isinstance(operation, dict):
1625
+ if operation.get("done"):
1626
+ status = "FAILED" if operation.get("error") else "SUCCESS"
1627
+
1628
+ response_dict = operation.get("response", {})
1629
+ output_gcs_uri = response_dict.get("outputGcsUri") or response_dict.get(
1630
+ "output_gcs_uri"
1631
+ )
1632
+ error = operation.get("error")
1633
+ else:
1634
+ if getattr(operation, "done", False):
1635
+ status = "FAILED" if getattr(operation, "error", None) else "SUCCESS"
1636
+
1637
+ response_obj = getattr(operation, "response", None)
1638
+ if isinstance(response_obj, dict):
1639
+ output_gcs_uri = response_obj.get("outputGcsUri") or response_obj.get(
1640
+ "output_gcs_uri"
1641
+ )
1642
+ else:
1643
+ output_gcs_uri = (
1644
+ getattr(
1645
+ response_obj,
1646
+ "output_gcs_uri",
1647
+ getattr(response_obj, "outputGcsUri", None),
1648
+ )
1649
+ if response_obj
1650
+ else None
1651
+ )
1652
+ error = getattr(operation, "error", None)
1653
+
1654
+ result_str = None
1655
+ if status == "SUCCESS" and config.retrieve_result and output_gcs_uri:
1656
+ storage_client = storage.Client(
1657
+ project=self._api_client.project,
1658
+ credentials=self._api_client._credentials,
1659
+ )
1660
+ bucket_name = output_gcs_uri.replace("gs://", "").split("/")[0]
1661
+ blob_name = output_gcs_uri.replace(f"gs://{bucket_name}/", "")
1662
+ bucket = storage_client.bucket(bucket_name)
1663
+ blob = bucket.blob(blob_name)
1664
+ if blob.exists():
1665
+ result_str = blob.download_as_string().decode("utf-8")
1666
+ else:
1667
+ raise ValueError(
1668
+ f"Failed to retrieve blob results for {output_gcs_uri}"
1669
+ )
1670
+
1671
+ elif status == "FAILED" and error:
1672
+ result_str = str(error)
1673
+
1674
+ return types.CheckQueryJobResult(
1675
+ operation_name=name,
1676
+ output_gcs_uri=output_gcs_uri,
1677
+ status=status,
1678
+ result=result_str,
1679
+ )
1680
+
1681
+ def _is_lightweight_creation(
1682
+ self, agent: Any, config: types.AgentEngineConfig
1683
+ ) -> bool:
1684
+ if (
1685
+ agent
1686
+ or config.source_packages
1687
+ or config.developer_connect_source
1688
+ or config.agent_config_source
1689
+ or config.container_spec
1690
+ ):
1691
+ return False
1692
+ return True
1693
+
1694
+ def run_query_job(
1695
+ self,
1696
+ *,
1697
+ name: str,
1698
+ config: Optional[types.RunQueryJobAgentEngineConfigOrDict] = None,
1699
+ ) -> types.RunQueryJobResult:
1700
+ """Launches a long-running query job on an Agent Engine
1701
+
1702
+ Args:
1703
+ name (str):
1704
+ Required. A fully-qualified resource name or ID.
1705
+ config (RunQueryJobAgentEngineConfigOrDict):
1706
+ Optional. The configuration for the async query. If not provided,
1707
+ the default configuration will be used. This can be used to specify
1708
+ the following fields:
1709
+ - query: The query to send to the agent engine.
1710
+ - output_gcs_uri: The GCS URI to use for the output.
1711
+ """
1712
+ from google.cloud import storage # type: ignore[attr-defined]
1713
+ from google.api_core import exceptions
1714
+ import uuid
1715
+
1716
+ if config is None:
1717
+ config = types.RunQueryJobAgentEngineConfig()
1718
+ elif isinstance(config, dict):
1719
+ config = types.RunQueryJobAgentEngineConfig(**config)
1720
+
1721
+ if not config.query:
1722
+ raise ValueError("`query` is required in the config object.")
1723
+ if not config.output_gcs_uri:
1724
+ raise ValueError("`output_gcs_uri` is required in the config object.")
1725
+
1726
+ output_gcs_uri = config.output_gcs_uri
1727
+ is_file = False
1728
+ last_part = ""
1729
+ if not output_gcs_uri.endswith("/"):
1730
+ last_part = output_gcs_uri.split("/")[-1]
1731
+ if "." in last_part:
1732
+ is_file = True
1733
+
1734
+ if is_file:
1735
+ path_parts = output_gcs_uri.split("/")
1736
+ file_name = path_parts[-1]
1737
+ base_uri = "/".join(path_parts[:-1])
1738
+ name_parts = file_name.rsplit(".", 1)
1739
+ if len(name_parts) == 2:
1740
+ name_part, ext = name_parts[0], "." + name_parts[1]
1741
+ else:
1742
+ name_part = name_parts[0]
1743
+ ext = ""
1744
+ input_gcs_uri = f"{base_uri}/{name_part}_input{ext}"
1745
+ else:
1746
+ job_uuid = uuid.uuid4().hex
1747
+ gcs_path = output_gcs_uri.rstrip("/")
1748
+ input_gcs_uri = f"{gcs_path}/{job_uuid}_input.json"
1749
+ output_gcs_uri = f"{gcs_path}/{job_uuid}_output.json"
1750
+
1751
+ storage_client = storage.Client(
1752
+ project=self._api_client.project, credentials=self._api_client._credentials
1753
+ )
1754
+
1755
+ # Handle creating the bucket if it does not exist
1756
+ bucket_name = config.output_gcs_uri.replace("gs://", "").split("/")[0]
1757
+ bucket = storage_client.bucket(bucket_name)
1758
+
1759
+ try:
1760
+ bucket_exists = bucket.exists()
1761
+ except exceptions.Forbidden as e:
1762
+ raise ValueError(
1763
+ f"Permission denied to check existence of bucket '{bucket_name}'. "
1764
+ "The service account may lack 'storage.buckets.get' permission."
1765
+ ) from e
1766
+
1767
+ if not bucket_exists:
1768
+ try:
1769
+ bucket.create()
1770
+ except exceptions.Forbidden as e:
1771
+ raise ValueError(
1772
+ f"Permission denied to create bucket '{bucket_name}'. "
1773
+ "The service account may lack 'storage.buckets.create' permission."
1774
+ ) from e
1775
+
1776
+ input_blob_name = input_gcs_uri.replace(f"gs://{bucket_name}/", "")
1777
+ blob = bucket.blob(input_blob_name)
1778
+ blob.upload_from_string(config.query)
1779
+
1780
+ new_config = types._RunQueryJobAgentEngineConfig(
1781
+ input_gcs_uri=input_gcs_uri,
1782
+ output_gcs_uri=output_gcs_uri,
1783
+ )
1784
+
1785
+ # Proceed with sending the async query via the auto-generated method
1786
+ operation = self._run_query_job(name=name, config=new_config)
1787
+
1788
+ return types.RunQueryJobResult(
1789
+ job_name=operation.name,
1790
+ input_gcs_uri=input_gcs_uri,
1791
+ output_gcs_uri=output_gcs_uri,
1792
+ )
1793
+
1794
+ def get(
1795
+ self,
1796
+ *,
1797
+ name: str,
1798
+ config: Optional[types.GetAgentEngineConfigOrDict] = None,
1799
+ ) -> types.AgentEngine:
1800
+ """Gets an agent engine.
1801
+
1802
+ Args:
1803
+ name (str):
1804
+ Required. A fully-qualified resource name or ID such as
1805
+ "projects/123/locations/us-central1/reasoningEngines/456" or
1806
+ a shortened name such as "reasoningEngines/456".
1807
+ """
1808
+ api_resource = self._get(name=name, config=config)
1809
+ agent_engine = types.AgentEngine(
1810
+ api_client=self,
1811
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
1812
+ api_resource=api_resource,
1813
+ )
1814
+ if api_resource.spec:
1815
+ self._register_api_methods(agent_engine=agent_engine)
1816
+ return agent_engine
1817
+
1818
+ def delete(
1819
+ self,
1820
+ *,
1821
+ name: str,
1822
+ force: Optional[bool] = None,
1823
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
1824
+ ) -> types.DeleteAgentEngineOperation:
1825
+ """
1826
+ Delete an Agent Engine resource.
1827
+
1828
+ Args:
1829
+ name (str):
1830
+ Required. The name of the Agent Engine to be deleted. Format:
1831
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
1832
+ or `reasoningEngines/{resource_id}`.
1833
+ force (bool):
1834
+ Optional. If set to True, child resources will also be deleted.
1835
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
1836
+ the Agent Engine has undeleted child resources. Defaults to False.
1837
+ config (DeleteAgentEngineConfig):
1838
+ Optional. Additional configurations for deleting the Agent Engine.
1839
+
1840
+ """
1841
+ logger.info(f"Deleting AgentEngine resource: {name}")
1842
+ operation = self._delete(name=name, force=force, config=config)
1843
+ logger.info(f"Started AgentEngine delete operation: {operation.name}")
1844
+ return operation
1845
+
1846
+ def create(
1847
+ self,
1848
+ *,
1849
+ agent_engine: Any = None,
1850
+ agent: Any = None,
1851
+ config: Optional[types.AgentEngineConfigOrDict] = None,
1852
+ ) -> types.AgentEngine:
1853
+ """Creates an agent engine.
1854
+
1855
+ The Agent Engine will be an instance of the `agent_engine` that
1856
+ was passed in, running remotely on Vertex AI.
1857
+
1858
+ Sample ``src_dir`` contents (e.g. ``./user_src_dir``):
1859
+
1860
+ .. code-block:: python
1861
+
1862
+ user_src_dir/
1863
+ |-- main.py
1864
+ |-- requirements.txt
1865
+ |-- user_code/
1866
+ | |-- utils.py
1867
+ | |-- ...
1868
+ |-- ...
1869
+
1870
+ To build an Agent Engine with the above files, run:
1871
+
1872
+ .. code-block:: python
1873
+
1874
+ client = agentplatform.Client(
1875
+ project="your-project",
1876
+ location="us-central1",
1877
+ )
1878
+ remote_agent = client.agent_engines.create(
1879
+ agent=local_agent,
1880
+ config=dict(
1881
+ requirements=[
1882
+ # I.e. the PyPI dependencies listed in requirements.txt
1883
+ "google-cloud-aiplatform[agent_engines,adk]",
1884
+ ...
1885
+ ],
1886
+ extra_packages=[
1887
+ "./user_src_dir/main.py", # a single file
1888
+ "./user_src_dir/user_code", # a directory
1889
+ ...
1890
+ ],
1891
+ ),
1892
+ )
1893
+
1894
+ Args:
1895
+ agent (Any):
1896
+ Optional. The Agent to be created. If not specified, this will
1897
+ correspond to a lightweight instance that cannot be queried
1898
+ (but can be updated to future instances that can be queried).
1899
+ agent_engine (Any):
1900
+ Optional. This is deprecated. Please use `agent` instead.
1901
+ config (AgentEngineConfig):
1902
+ Optional. The configurations to use for creating the Agent Engine.
1903
+
1904
+ Returns:
1905
+ AgentEngine: The created Agent Engine instance.
1906
+
1907
+ Raises:
1908
+ ValueError: If the `project` was not set using `client.Client`.
1909
+ ValueError: If the `location` was not set using `client.Client`.
1910
+ ValueError: If `config.staging_bucket` was not set when `agent`
1911
+ is specified.
1912
+ ValueError: If `config.staging_bucket` does not start with "gs://".
1913
+ ValueError: If `config.extra_packages` is specified but `agent`
1914
+ is None.
1915
+ ValueError: If `config.requirements` is specified but `agent` is None.
1916
+ ValueError: If `config.env_vars` has a dictionary entry that does not
1917
+ correspond to an environment variable value or a SecretRef.
1918
+ TypeError: If `config.env_vars` is not a dictionary.
1919
+ FileNotFoundError: If `config.extra_packages` includes a file or
1920
+ directory that does not exist.
1921
+ IOError: If ``config.requirements` is a string that corresponds to a
1922
+ nonexistent file.
1923
+ """
1924
+ if config is None:
1925
+ config = {}
1926
+ if isinstance(config, dict):
1927
+ config = types.AgentEngineConfig.model_validate(config)
1928
+ elif not isinstance(config, types.AgentEngineConfig):
1929
+ raise TypeError(
1930
+ f"config must be a dict or AgentEngineConfig, but got {type(config)}."
1931
+ )
1932
+ context_spec = config.context_spec
1933
+ if context_spec is not None:
1934
+ # Conversion to a dict for _create_config
1935
+ context_spec = json.loads(context_spec.model_dump_json())
1936
+ developer_connect_source = config.developer_connect_source
1937
+ if developer_connect_source is not None:
1938
+ developer_connect_source = json.loads(
1939
+ developer_connect_source.model_dump_json()
1940
+ )
1941
+ agent_config_source = config.agent_config_source
1942
+ if agent_config_source is not None:
1943
+ agent_config_source = json.loads(agent_config_source.model_dump_json())
1944
+ keep_alive_probe = config.keep_alive_probe
1945
+ if keep_alive_probe is not None:
1946
+ keep_alive_probe = json.loads(
1947
+ keep_alive_probe.model_dump_json(exclude_none=True)
1948
+ )
1949
+ if agent and agent_engine:
1950
+ raise ValueError("Please specify only one of `agent` or `agent_engine`.")
1951
+ elif agent_engine:
1952
+ raise DeprecationWarning(
1953
+ "The `agent_engine` argument is deprecated. Please use `agent` instead."
1954
+ )
1955
+ agent = agent or agent_engine
1956
+ api_config = self._create_config(
1957
+ mode="create",
1958
+ agent=agent,
1959
+ identity_type=config.identity_type,
1960
+ staging_bucket=config.staging_bucket,
1961
+ requirements=config.requirements,
1962
+ display_name=config.display_name,
1963
+ description=config.description,
1964
+ gcs_dir_name=config.gcs_dir_name,
1965
+ extra_packages=config.extra_packages,
1966
+ env_vars=config.env_vars,
1967
+ service_account=config.service_account,
1968
+ context_spec=context_spec,
1969
+ psc_interface_config=config.psc_interface_config,
1970
+ agent_gateway_config=config.agent_gateway_config,
1971
+ min_instances=config.min_instances,
1972
+ max_instances=config.max_instances,
1973
+ resource_limits=config.resource_limits,
1974
+ container_concurrency=config.container_concurrency,
1975
+ encryption_spec=config.encryption_spec,
1976
+ agent_server_mode=config.agent_server_mode,
1977
+ labels=config.labels,
1978
+ class_methods=config.class_methods,
1979
+ source_packages=config.source_packages,
1980
+ developer_connect_source=developer_connect_source,
1981
+ entrypoint_module=config.entrypoint_module,
1982
+ entrypoint_object=config.entrypoint_object,
1983
+ requirements_file=config.requirements_file,
1984
+ agent_framework=config.agent_framework,
1985
+ python_version=config.python_version,
1986
+ build_options=config.build_options,
1987
+ image_spec=config.image_spec,
1988
+ agent_config_source=agent_config_source,
1989
+ container_spec=config.container_spec,
1990
+ keep_alive_probe=keep_alive_probe,
1991
+ build_config=config.build_config,
1992
+ )
1993
+ operation = self._create(config=api_config)
1994
+ reasoning_engine_id = _agent_engines_utils._get_reasoning_engine_id(
1995
+ operation_name=operation.name
1996
+ )
1997
+ logger.info(
1998
+ "View progress and logs at https://console.cloud.google.com/logs/query?"
1999
+ f"project={self._api_client.project}"
2000
+ "&query=resource.type%3D%22aiplatform.googleapis.com%2FReasoningEngine%22%0A"
2001
+ f"resource.labels.reasoning_engine_id%3D%22{reasoning_engine_id}%22."
2002
+ )
2003
+ if not self._is_lightweight_creation(agent, config):
2004
+ poll_interval_seconds = 10
2005
+ else:
2006
+ poll_interval_seconds = 1 # Lightweight agent engine resource creation.
2007
+ operation = _agent_engines_utils._await_operation(
2008
+ operation_name=operation.name,
2009
+ get_operation_fn=self._get_agent_operation,
2010
+ poll_interval_seconds=poll_interval_seconds,
2011
+ )
2012
+
2013
+ agent_engine = types.AgentEngine(
2014
+ api_client=self,
2015
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
2016
+ api_resource=operation.response,
2017
+ )
2018
+ if agent_engine.api_resource:
2019
+ logger.info("Agent Engine created. To use it in another session:")
2020
+ logger.info(
2021
+ f"agent_engine=client.agent_engines.get(name='{agent_engine.api_resource.name}')"
2022
+ )
2023
+ elif operation.error:
2024
+ raise RuntimeError(f"Failed to create Agent Engine: {operation.error}")
2025
+ else:
2026
+ logger.warning("The operation returned an empty response.")
2027
+ if not self._is_lightweight_creation(agent, config):
2028
+ # If the user did not provide an agent_engine (e.g. lightweight
2029
+ # provisioning), it will not have any API methods registered.
2030
+ agent_engine = self._register_api_methods(agent_engine=agent_engine)
2031
+ return agent_engine # type: ignore[no-any-return]
2032
+
2033
+ def _set_source_code_spec(
2034
+ self,
2035
+ *,
2036
+ spec: types.ReasoningEngineSpecDict,
2037
+ update_masks: builtins.list[str],
2038
+ source_packages: Optional[Sequence[str]] = None,
2039
+ developer_connect_source: Optional[
2040
+ types.ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
2041
+ ] = None,
2042
+ class_methods: Optional[Sequence[dict[str, Any]]] = None,
2043
+ entrypoint_module: Optional[str] = None,
2044
+ entrypoint_object: Optional[str] = None,
2045
+ requirements_file: Optional[str] = None,
2046
+ sys_version: str,
2047
+ build_options: Optional[dict[str, builtins.list[str]]] = None,
2048
+ image_spec: Optional[
2049
+ types.ReasoningEngineSpecSourceCodeSpecImageSpecDict
2050
+ ] = None,
2051
+ agent_config_source: Optional[
2052
+ types.ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict
2053
+ ] = None,
2054
+ ) -> None:
2055
+ """Sets source_code_spec for agent engine inside the `spec`."""
2056
+ source_code_spec = types.ReasoningEngineSpecSourceCodeSpecDict()
2057
+ if source_packages and not agent_config_source:
2058
+ source_packages = _agent_engines_utils._validate_packages_or_raise(
2059
+ packages=source_packages,
2060
+ build_options=build_options,
2061
+ )
2062
+ update_masks.append("spec.source_code_spec.inline_source.source_archive")
2063
+ source_code_spec["inline_source"] = { # type: ignore[typeddict-item]
2064
+ "source_archive": _agent_engines_utils._create_base64_encoded_tarball(
2065
+ source_packages=source_packages
2066
+ )
2067
+ }
2068
+ elif developer_connect_source:
2069
+ update_masks.append("spec.source_code_spec.developer_connect_source")
2070
+ source_code_spec["developer_connect_source"] = {
2071
+ "config": developer_connect_source
2072
+ }
2073
+ elif not agent_config_source:
2074
+ raise ValueError(
2075
+ "Please specify one of `source_packages`, `developer_connect_source`, "
2076
+ "or `agent_config_source`."
2077
+ )
2078
+ if class_methods is not None:
2079
+ update_masks.append("spec.class_methods")
2080
+ class_methods_spec_list = (
2081
+ _agent_engines_utils._class_methods_to_class_methods_spec(
2082
+ class_methods=class_methods
2083
+ )
2084
+ )
2085
+ spec["class_methods"] = [
2086
+ _agent_engines_utils._to_dict(class_method_spec)
2087
+ for class_method_spec in class_methods_spec_list
2088
+ ]
2089
+ elif image_spec is None:
2090
+ raise ValueError(
2091
+ "`class_methods` must be specified if `source_packages`, "
2092
+ "`developer_connect_source`, or `agent_config_source` is "
2093
+ "specified without a Dockerfile or `image_spec`."
2094
+ )
2095
+ if image_spec is not None:
2096
+ if entrypoint_module or entrypoint_object or requirements_file:
2097
+ raise ValueError(
2098
+ "`image_spec` cannot be specified alongside `entrypoint_module`, "
2099
+ "`entrypoint_object`, or `requirements_file`, as they are "
2100
+ "mutually exclusive."
2101
+ )
2102
+ if agent_config_source:
2103
+ raise ValueError(
2104
+ "`image_spec` cannot be specified alongside `agent_config_source`, "
2105
+ "as they are mutually exclusive."
2106
+ )
2107
+ update_masks.append("spec.source_code_spec.image_spec")
2108
+ source_code_spec["image_spec"] = image_spec
2109
+ spec["source_code_spec"] = source_code_spec
2110
+ return
2111
+
2112
+ update_masks.append("spec.source_code_spec.python_spec.version")
2113
+ python_spec: types.ReasoningEngineSpecSourceCodeSpecPythonSpecDict = {
2114
+ "version": sys_version,
2115
+ }
2116
+ if agent_config_source is not None:
2117
+ if entrypoint_module or entrypoint_object:
2118
+ logger.warning(
2119
+ "`entrypoint_module` and `entrypoint_object` are ignored when "
2120
+ "`agent_config_source` is specified, as they are pre-defined."
2121
+ )
2122
+ if source_packages:
2123
+ source_packages = _agent_engines_utils._validate_packages_or_raise(
2124
+ packages=source_packages,
2125
+ build_options=build_options,
2126
+ )
2127
+ update_masks.append(
2128
+ "spec.source_code_spec.agent_config_source.inline_source.source_archive"
2129
+ )
2130
+ agent_config_source["inline_source"] = { # type: ignore[typeddict-item]
2131
+ "source_archive": _agent_engines_utils._create_base64_encoded_tarball(
2132
+ source_packages=source_packages
2133
+ )
2134
+ }
2135
+ update_masks.append("spec.source_code_spec.agent_config_source")
2136
+ source_code_spec["agent_config_source"] = agent_config_source
2137
+
2138
+ if requirements_file is not None:
2139
+ update_masks.append(
2140
+ "spec.source_code_spec.python_spec.requirements_file"
2141
+ )
2142
+ python_spec["requirements_file"] = requirements_file
2143
+ source_code_spec["python_spec"] = python_spec
2144
+
2145
+ spec["source_code_spec"] = source_code_spec
2146
+ return
2147
+
2148
+ if not entrypoint_module:
2149
+ raise ValueError(
2150
+ "`entrypoint_module` must be specified if `source_packages` or `developer_connect_source` is specified."
2151
+ )
2152
+ update_masks.append("spec.source_code_spec.python_spec.entrypoint_module")
2153
+ python_spec["entrypoint_module"] = entrypoint_module
2154
+ if not entrypoint_object:
2155
+ raise ValueError(
2156
+ "`entrypoint_object` must be specified if `source_packages` or `developer_connect_source` is specified."
2157
+ )
2158
+ update_masks.append("spec.source_code_spec.python_spec.entrypoint_object")
2159
+ python_spec["entrypoint_object"] = entrypoint_object
2160
+ if requirements_file is not None:
2161
+ update_masks.append("spec.source_code_spec.python_spec.requirements_file")
2162
+ python_spec["requirements_file"] = requirements_file
2163
+ source_code_spec["python_spec"] = python_spec
2164
+ spec["source_code_spec"] = source_code_spec
2165
+
2166
+ def _set_package_spec(
2167
+ self,
2168
+ *,
2169
+ spec: types.ReasoningEngineSpecDict,
2170
+ update_masks: builtins.list[str],
2171
+ agent: Any,
2172
+ staging_bucket: Optional[str] = None,
2173
+ requirements: Optional[Union[str, Sequence[str]]] = None,
2174
+ gcs_dir_name: Optional[str] = None,
2175
+ extra_packages: Optional[Sequence[str]] = None,
2176
+ class_methods: Optional[Sequence[dict[str, Any]]] = None,
2177
+ sys_version: str,
2178
+ build_options: Optional[dict[str, builtins.list[str]]] = None,
2179
+ ) -> None:
2180
+ """Sets package spec for agent engine."""
2181
+ project = self._api_client.project
2182
+ if project is None:
2183
+ raise ValueError("project must be set using `agentplatform.Client`.")
2184
+ location = self._api_client.location
2185
+ if location is None:
2186
+ raise ValueError("location must be set using `agentplatform.Client`.")
2187
+ gcs_dir_name = gcs_dir_name or _agent_engines_utils._DEFAULT_GCS_DIR_NAME
2188
+ staging_bucket = _agent_engines_utils._validate_staging_bucket_or_raise(
2189
+ staging_bucket=staging_bucket,
2190
+ )
2191
+ requirements = _agent_engines_utils._validate_requirements_or_raise(
2192
+ agent=agent,
2193
+ requirements=requirements,
2194
+ )
2195
+ extra_packages = _agent_engines_utils._validate_packages_or_raise(
2196
+ packages=extra_packages,
2197
+ build_options=build_options,
2198
+ )
2199
+ # Prepares the Agent Engine for creation/update in Vertex AI. This
2200
+ # involves packaging and uploading the artifacts for agent_engine,
2201
+ # requirements and extra_packages to `staging_bucket/gcs_dir_name`.
2202
+ _agent_engines_utils._prepare(
2203
+ agent=agent,
2204
+ requirements=requirements,
2205
+ project=project,
2206
+ location=location,
2207
+ staging_bucket=staging_bucket,
2208
+ gcs_dir_name=gcs_dir_name,
2209
+ extra_packages=extra_packages,
2210
+ credentials=self._api_client._credentials,
2211
+ )
2212
+ # Update the package spec.
2213
+ update_masks.append("spec.package_spec.pickle_object_gcs_uri")
2214
+ package_spec: types.ReasoningEngineSpecPackageSpecDict = {
2215
+ "python_version": sys_version,
2216
+ "pickle_object_gcs_uri": "{}/{}/{}".format(
2217
+ staging_bucket,
2218
+ gcs_dir_name,
2219
+ _agent_engines_utils._BLOB_FILENAME,
2220
+ ),
2221
+ }
2222
+ if extra_packages:
2223
+ update_masks.append("spec.package_spec.dependency_files_gcs_uri")
2224
+ package_spec["dependency_files_gcs_uri"] = "{}/{}/{}".format(
2225
+ staging_bucket,
2226
+ gcs_dir_name,
2227
+ _agent_engines_utils._EXTRA_PACKAGES_FILE,
2228
+ )
2229
+ if requirements:
2230
+ update_masks.append("spec.package_spec.requirements_gcs_uri")
2231
+ package_spec["requirements_gcs_uri"] = "{}/{}/{}".format(
2232
+ staging_bucket,
2233
+ gcs_dir_name,
2234
+ _agent_engines_utils._REQUIREMENTS_FILE,
2235
+ )
2236
+ spec["package_spec"] = package_spec
2237
+
2238
+ update_masks.append("spec.class_methods")
2239
+ if class_methods is not None:
2240
+ class_methods_spec_list = (
2241
+ _agent_engines_utils._class_methods_to_class_methods_spec(
2242
+ class_methods=class_methods
2243
+ )
2244
+ )
2245
+ else:
2246
+ class_methods_spec_list = (
2247
+ _agent_engines_utils._generate_class_methods_spec_or_raise(
2248
+ agent=agent,
2249
+ operations=_agent_engines_utils._get_registered_operations(
2250
+ agent=agent
2251
+ ),
2252
+ )
2253
+ )
2254
+ spec["class_methods"] = [
2255
+ _agent_engines_utils._to_dict(class_method_spec)
2256
+ for class_method_spec in class_methods_spec_list
2257
+ ]
2258
+
2259
+ def _create_config(
2260
+ self,
2261
+ *,
2262
+ mode: str,
2263
+ agent: Any = None,
2264
+ identity_type: Optional[types.IdentityType] = None,
2265
+ staging_bucket: Optional[str] = None,
2266
+ requirements: Optional[Union[str, Sequence[str]]] = None,
2267
+ display_name: Optional[str] = None,
2268
+ description: Optional[str] = None,
2269
+ gcs_dir_name: Optional[str] = None,
2270
+ extra_packages: Optional[Sequence[str]] = None,
2271
+ env_vars: Optional[dict[str, Union[str, Any]]] = None,
2272
+ service_account: Optional[str] = None,
2273
+ context_spec: Optional[types.ReasoningEngineContextSpecDict] = None,
2274
+ psc_interface_config: Optional[types.PscInterfaceConfigDict] = None,
2275
+ agent_gateway_config: Optional[
2276
+ types.ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
2277
+ ] = None,
2278
+ min_instances: Optional[int] = None,
2279
+ max_instances: Optional[int] = None,
2280
+ resource_limits: Optional[dict[str, str]] = None,
2281
+ container_concurrency: Optional[int] = None,
2282
+ encryption_spec: Optional[genai_types.EncryptionSpecDict] = None,
2283
+ labels: Optional[dict[str, str]] = None,
2284
+ agent_server_mode: Optional[types.AgentServerMode] = None,
2285
+ class_methods: Optional[Sequence[dict[str, Any]]] = None,
2286
+ source_packages: Optional[Sequence[str]] = None,
2287
+ developer_connect_source: Optional[
2288
+ types.ReasoningEngineSpecSourceCodeSpecDeveloperConnectConfigDict
2289
+ ] = None,
2290
+ entrypoint_module: Optional[str] = None,
2291
+ entrypoint_object: Optional[str] = None,
2292
+ requirements_file: Optional[str] = None,
2293
+ agent_framework: Optional[str] = None,
2294
+ python_version: Optional[str] = None,
2295
+ build_options: Optional[dict[str, builtins.list[str]]] = None,
2296
+ image_spec: Optional[
2297
+ types.ReasoningEngineSpecSourceCodeSpecImageSpecDict
2298
+ ] = None,
2299
+ agent_config_source: Optional[
2300
+ types.ReasoningEngineSpecSourceCodeSpecAgentConfigSourceDict
2301
+ ] = None,
2302
+ container_spec: Optional[types.ReasoningEngineSpecContainerSpecDict] = None,
2303
+ keep_alive_probe: Optional[dict[str, Any]] = None,
2304
+ traffic_config: Optional[types.ReasoningEngineTrafficConfigDict] = None,
2305
+ build_config: Optional[types.ReasoningEngineSpecBuildSpecDict] = None,
2306
+ ) -> types.UpdateAgentEngineConfigDict:
2307
+ import sys
2308
+
2309
+ config: types.UpdateAgentEngineConfigDict = {}
2310
+ update_masks = []
2311
+ if mode not in ["create", "update"]:
2312
+ raise ValueError(f"Unsupported mode: {mode}")
2313
+ if agent is None:
2314
+ if requirements is not None:
2315
+ raise ValueError("requirements must be None if agent is None.")
2316
+ if extra_packages is not None:
2317
+ raise ValueError("extra_packages must be None if agent is None.")
2318
+ if display_name is not None:
2319
+ update_masks.append("display_name")
2320
+ config["display_name"] = display_name
2321
+ if description is not None:
2322
+ update_masks.append("description")
2323
+ config["description"] = description
2324
+ if context_spec is not None:
2325
+ update_masks.append("context_spec")
2326
+ config["context_spec"] = context_spec
2327
+ if encryption_spec is not None:
2328
+ update_masks.append("encryption_spec")
2329
+ config["encryption_spec"] = encryption_spec
2330
+ if labels is not None:
2331
+ update_masks.append("labels")
2332
+ config["labels"] = labels
2333
+ if traffic_config is not None:
2334
+ update_masks.append("traffic_config")
2335
+ config["traffic_config"] = traffic_config
2336
+
2337
+ if agent_framework == "google-adk":
2338
+ env_vars = _agent_engines_utils._add_telemetry_enablement_env(env_vars)
2339
+
2340
+ if python_version:
2341
+ sys_version = python_version
2342
+ else:
2343
+ sys_version = f"{sys.version_info.major}.{sys.version_info.minor}"
2344
+
2345
+ if agent:
2346
+ if source_packages:
2347
+ raise ValueError(
2348
+ "If you have provided `source_packages` in `config`, please "
2349
+ "do not specify `agent` in `agent_engines.create()` or "
2350
+ "`agent_engines.update()`."
2351
+ )
2352
+ if developer_connect_source:
2353
+ raise ValueError(
2354
+ "If you have provided `developer_connect_source` in `config`, please "
2355
+ "do not specify `agent` in `agent_engines.create()` or "
2356
+ "`agent_engines.update()`."
2357
+ )
2358
+ elif source_packages and developer_connect_source:
2359
+ raise ValueError(
2360
+ "Please specify only one of `source_packages` or `developer_connect_source` in `config`."
2361
+ )
2362
+
2363
+ if container_spec:
2364
+ if agent:
2365
+ raise ValueError(
2366
+ "If you have provided `container_spec` in `config`, please "
2367
+ "do not specify `agent` in `agent_engines.create()` or "
2368
+ "`agent_engines.update()`."
2369
+ )
2370
+ if source_packages or developer_connect_source:
2371
+ raise ValueError(
2372
+ "If you have provided `container_spec` in `config`, please "
2373
+ "do not specify `source_packages` or `developer_connect_source` in `config`."
2374
+ )
2375
+
2376
+ agent_engine_spec: Any = None
2377
+ if agent:
2378
+ agent_engine_spec = {}
2379
+ agent = _agent_engines_utils._validate_agent_or_raise(agent=agent)
2380
+ if _agent_engines_utils._is_adk_agent(agent):
2381
+ env_vars = _agent_engines_utils._add_telemetry_enablement_env(env_vars)
2382
+ self._set_package_spec(
2383
+ spec=agent_engine_spec,
2384
+ update_masks=update_masks,
2385
+ agent=agent,
2386
+ staging_bucket=staging_bucket,
2387
+ requirements=requirements,
2388
+ gcs_dir_name=gcs_dir_name,
2389
+ extra_packages=extra_packages,
2390
+ class_methods=class_methods,
2391
+ sys_version=sys_version,
2392
+ build_options=build_options,
2393
+ )
2394
+ elif (
2395
+ source_packages
2396
+ or developer_connect_source
2397
+ or image_spec
2398
+ or agent_config_source
2399
+ ):
2400
+ agent_engine_spec = {}
2401
+ self._set_source_code_spec(
2402
+ spec=agent_engine_spec,
2403
+ update_masks=update_masks,
2404
+ source_packages=source_packages,
2405
+ developer_connect_source=developer_connect_source,
2406
+ class_methods=class_methods,
2407
+ entrypoint_module=entrypoint_module,
2408
+ entrypoint_object=entrypoint_object,
2409
+ requirements_file=requirements_file,
2410
+ sys_version=sys_version,
2411
+ build_options=build_options,
2412
+ image_spec=image_spec,
2413
+ agent_config_source=agent_config_source,
2414
+ )
2415
+ elif container_spec:
2416
+ agent_engine_spec = {}
2417
+ if class_methods is not None:
2418
+ update_masks.append("spec.class_methods")
2419
+ class_methods_spec_list = (
2420
+ _agent_engines_utils._class_methods_to_class_methods_spec(
2421
+ class_methods=class_methods
2422
+ )
2423
+ )
2424
+ agent_engine_spec["class_methods"] = [
2425
+ _agent_engines_utils._to_dict(class_method_spec)
2426
+ for class_method_spec in class_methods_spec_list
2427
+ ]
2428
+ update_masks.append("spec.container_spec")
2429
+ agent_engine_spec["container_spec"] = container_spec
2430
+
2431
+ is_deployment_spec_updated = (
2432
+ env_vars is not None
2433
+ or psc_interface_config is not None
2434
+ or agent_gateway_config is not None
2435
+ or min_instances is not None
2436
+ or max_instances is not None
2437
+ or resource_limits is not None
2438
+ or container_concurrency is not None
2439
+ or keep_alive_probe is not None
2440
+ )
2441
+ if agent_engine_spec is None and is_deployment_spec_updated:
2442
+ raise ValueError(
2443
+ "To update `env_vars`, `psc_interface_config`, `min_instances`, "
2444
+ "`max_instances`, `resource_limits`, `container_concurrency`, or "
2445
+ "`keep_alive_probe`, you must also provide the `agent` variable or "
2446
+ "the source code options (`source_packages`, "
2447
+ "`developer_connect_source` or `agent_config_source`)."
2448
+ )
2449
+
2450
+ if agent_engine_spec is not None:
2451
+ if is_deployment_spec_updated:
2452
+ (
2453
+ deployment_spec,
2454
+ deployment_update_masks,
2455
+ ) = self._generate_deployment_spec_or_raise(
2456
+ env_vars=env_vars,
2457
+ psc_interface_config=psc_interface_config,
2458
+ agent_gateway_config=agent_gateway_config,
2459
+ min_instances=min_instances,
2460
+ max_instances=max_instances,
2461
+ resource_limits=resource_limits,
2462
+ container_concurrency=container_concurrency,
2463
+ keep_alive_probe=keep_alive_probe,
2464
+ )
2465
+ update_masks.extend(deployment_update_masks)
2466
+ agent_engine_spec["deployment_spec"] = deployment_spec
2467
+
2468
+ if agent_server_mode:
2469
+ if not agent_engine_spec.get("deployment_spec"):
2470
+ agent_engine_spec["deployment_spec"] = (
2471
+ types.ReasoningEngineSpecDeploymentSpecDict()
2472
+ )
2473
+ agent_engine_spec["deployment_spec"][
2474
+ "agent_server_mode"
2475
+ ] = agent_server_mode
2476
+
2477
+ agent_engine_spec["agent_framework"] = (
2478
+ _agent_engines_utils._get_agent_framework(
2479
+ agent_framework=agent_framework,
2480
+ agent=agent,
2481
+ )
2482
+ )
2483
+
2484
+ if hasattr(agent, "agent_card"):
2485
+ agent_card = getattr(agent, "agent_card")
2486
+ if agent_card:
2487
+ try:
2488
+ from google.protobuf import json_format
2489
+
2490
+ agent_engine_spec["agent_card"] = json_format.MessageToDict(
2491
+ agent_card
2492
+ )
2493
+ except Exception as e:
2494
+ raise ValueError(
2495
+ f"Failed to convert agent card to dict (serialization error): {e}"
2496
+ ) from e
2497
+ update_masks.append("spec.agent_card")
2498
+ update_masks.append("spec.agent_framework")
2499
+
2500
+ if identity_type is not None or service_account is not None:
2501
+ if agent_engine_spec is None:
2502
+ agent_engine_spec = {}
2503
+
2504
+ if identity_type is not None:
2505
+ agent_engine_spec["identity_type"] = identity_type
2506
+ update_masks.append("spec.identity_type")
2507
+ if service_account is not None:
2508
+ # Clear the field in case of empty service_account.
2509
+ if service_account:
2510
+ agent_engine_spec["service_account"] = service_account
2511
+ update_masks.append("spec.service_account")
2512
+
2513
+ if build_config is not None:
2514
+ if agent_engine_spec is None:
2515
+ agent_engine_spec = {}
2516
+ build_spec: dict[str, Any] = {}
2517
+ if isinstance(build_config, dict):
2518
+ worker_pool = build_config.get("worker_pool")
2519
+ build_service_account = build_config.get("service_account")
2520
+ else:
2521
+ worker_pool = getattr(build_config, "worker_pool", None)
2522
+ build_service_account = getattr(build_config, "service_account", None)
2523
+ if worker_pool is not None:
2524
+ build_spec["worker_pool"] = worker_pool
2525
+ update_masks.append("spec.build_spec.worker_pool")
2526
+ if build_service_account is not None:
2527
+ build_spec["service_account"] = build_service_account
2528
+ update_masks.append("spec.build_spec.service_account")
2529
+ if build_spec:
2530
+ agent_engine_spec["build_spec"] = build_spec
2531
+
2532
+ if agent_engine_spec is not None:
2533
+ config["spec"] = agent_engine_spec
2534
+
2535
+ if update_masks and mode == "update":
2536
+ config["update_mask"] = ",".join(update_masks)
2537
+ return config
2538
+
2539
+ def _generate_deployment_spec_or_raise(
2540
+ self,
2541
+ *,
2542
+ env_vars: Optional[dict[str, Union[str, Any]]] = None,
2543
+ psc_interface_config: Optional[types.PscInterfaceConfigDict] = None,
2544
+ agent_gateway_config: Optional[
2545
+ types.ReasoningEngineSpecDeploymentSpecAgentGatewayConfigDict
2546
+ ] = None,
2547
+ min_instances: Optional[int] = None,
2548
+ max_instances: Optional[int] = None,
2549
+ resource_limits: Optional[dict[str, str]] = None,
2550
+ container_concurrency: Optional[int] = None,
2551
+ keep_alive_probe: Optional[dict[str, Any]] = None,
2552
+ ) -> Tuple[dict[str, Any], Sequence[str]]:
2553
+ deployment_spec: dict[str, Any] = {}
2554
+ update_masks = []
2555
+ if env_vars:
2556
+ deployment_spec["env"] = []
2557
+ deployment_spec["secret_env"] = []
2558
+ if isinstance(env_vars, dict):
2559
+ self._update_deployment_spec_with_env_vars_dict_or_raise(
2560
+ deployment_spec=deployment_spec,
2561
+ env_vars=env_vars,
2562
+ )
2563
+ else:
2564
+ raise TypeError(f"env_vars must be a dict, but got {type(env_vars)}.")
2565
+ if deployment_spec.get("env"):
2566
+ update_masks.append("spec.deployment_spec.env")
2567
+ if deployment_spec.get("secret_env"):
2568
+ update_masks.append("spec.deployment_spec.secret_env")
2569
+ if psc_interface_config:
2570
+ deployment_spec["psc_interface_config"] = psc_interface_config
2571
+ update_masks.append("spec.deployment_spec.psc_interface_config")
2572
+ if agent_gateway_config:
2573
+ deployment_spec["agent_gateway_config"] = agent_gateway_config
2574
+ update_masks.append("spec.deployment_spec.agent_gateway_config")
2575
+ if min_instances is not None:
2576
+ if not 0 <= min_instances <= 10:
2577
+ raise ValueError(
2578
+ f"min_instances must be between 0 and 10. Got {min_instances}"
2579
+ )
2580
+ deployment_spec["min_instances"] = min_instances
2581
+ update_masks.append("spec.deployment_spec.min_instances")
2582
+ if max_instances is not None:
2583
+ if psc_interface_config and not 1 <= max_instances <= 100:
2584
+ raise ValueError(
2585
+ f"max_instances must be between 1 and 100 when PSC-I is enabled. Got {max_instances}"
2586
+ )
2587
+ elif not psc_interface_config and not 1 <= max_instances <= 1000:
2588
+ raise ValueError(
2589
+ f"max_instances must be between 1 and 1000. Got {max_instances}"
2590
+ )
2591
+ deployment_spec["max_instances"] = max_instances
2592
+ update_masks.append("spec.deployment_spec.max_instances")
2593
+ if resource_limits:
2594
+ _agent_engines_utils._validate_resource_limits_or_raise(
2595
+ resource_limits=resource_limits
2596
+ )
2597
+ deployment_spec["resource_limits"] = resource_limits
2598
+ update_masks.append("spec.deployment_spec.resource_limits")
2599
+ if container_concurrency:
2600
+ deployment_spec["container_concurrency"] = container_concurrency
2601
+ update_masks.append("spec.deployment_spec.container_concurrency")
2602
+ if keep_alive_probe is not None:
2603
+ deployment_spec["keep_alive_probe"] = keep_alive_probe
2604
+ update_masks.append("spec.deployment_spec.keep_alive_probe")
2605
+ return deployment_spec, update_masks
2606
+
2607
+ def _update_deployment_spec_with_env_vars_dict_or_raise(
2608
+ self,
2609
+ *,
2610
+ deployment_spec: dict[str, Any],
2611
+ env_vars: dict[str, Any],
2612
+ ) -> None:
2613
+ for key, value in env_vars.items():
2614
+ if isinstance(value, dict):
2615
+ if "secret_env" not in deployment_spec:
2616
+ deployment_spec["secret_env"] = []
2617
+ deployment_spec["secret_env"].append({"name": key, "secret_ref": value})
2618
+ elif isinstance(value, str):
2619
+ if "env" not in deployment_spec:
2620
+ deployment_spec["env"] = []
2621
+ deployment_spec["env"].append({"name": key, "value": value})
2622
+ else:
2623
+ raise TypeError(
2624
+ f"Unknown value type in env_vars for {key}. "
2625
+ f"Must be a str or SecretRef: {value}"
2626
+ )
2627
+
2628
+ def _register_api_methods(
2629
+ self,
2630
+ *,
2631
+ agent_engine: types.AgentEngine,
2632
+ ) -> types.AgentEngine:
2633
+ """Registers the API methods for the agent engine."""
2634
+ try:
2635
+ _agent_engines_utils._register_api_methods_or_raise(
2636
+ agent_engine=agent_engine,
2637
+ wrap_operation_fn={
2638
+ "": _agent_engines_utils._wrap_query_operation, # type: ignore[dict-item]
2639
+ "async": _agent_engines_utils._wrap_async_query_operation, # type: ignore[dict-item]
2640
+ "stream": _agent_engines_utils._wrap_stream_query_operation, # type: ignore[dict-item]
2641
+ "async_stream": _agent_engines_utils._wrap_async_stream_query_operation, # type: ignore[dict-item]
2642
+ "a2a_extension": _agent_engines_utils._wrap_a2a_operation,
2643
+ },
2644
+ )
2645
+ except Exception as e:
2646
+ logger.warning(
2647
+ _agent_engines_utils._FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e
2648
+ )
2649
+ return agent_engine
2650
+
2651
+ def list(
2652
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
2653
+ ) -> Iterator[types.AgentEngine]:
2654
+ """List all instances of Agent Engine matching the filter.
2655
+
2656
+ Example Usage:
2657
+
2658
+ .. code-block:: python
2659
+ import agentplatform
2660
+
2661
+ client = agentplatform.Client(project="my_project", location="us-central1")
2662
+ for agent in client.agent_engines.list(
2663
+ config={"filter": "'display_name="My Custom Agent"'},
2664
+ ):
2665
+ print(agent.api_resource.name)
2666
+
2667
+ Args:
2668
+ config (ListAgentEngineConfig):
2669
+ Optional. The config (e.g. filter) for the agents to be listed.
2670
+
2671
+ Returns:
2672
+ Iterable[AgentEngine]: An iterable of Agent Engines matching the filter.
2673
+ """
2674
+
2675
+ for reasoning_engine in self._list_pager(config=config):
2676
+ yield types.AgentEngine(
2677
+ api_client=self,
2678
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
2679
+ api_resource=reasoning_engine,
2680
+ )
2681
+
2682
+ def update(
2683
+ self,
2684
+ *,
2685
+ name: str,
2686
+ agent: Any = None,
2687
+ agent_engine: Any = None,
2688
+ config: types.AgentEngineConfigOrDict,
2689
+ ) -> types.AgentEngine:
2690
+ """Updates an existing Agent Engine.
2691
+
2692
+ This method updates the configuration of an existing Agent Engine running
2693
+ remotely, which is identified by its name.
2694
+
2695
+ Args:
2696
+ name (str): Required. A fully-qualified resource name or ID such as
2697
+ "projects/123/locations/us-central1/reasoningEngines/456" or a
2698
+ shortened name such as "reasoningEngines/456".
2699
+ agent (Any):
2700
+ Optional. The instance to be used as the updated Agent Engine.
2701
+ If it is not specified, the existing instance will be used.
2702
+ agent_engine (Any):
2703
+ Optional. This is deprecated. Please use `agent` instead.
2704
+ config (AgentEngineConfig):
2705
+ Optional. The configurations to use for updating the Agent Engine.
2706
+
2707
+ Returns:
2708
+ AgentEngine: The updated Agent Engine.
2709
+
2710
+ Raises:
2711
+ ValueError: If the `project` was not set using `client.Client`.
2712
+ ValueError: If the `location` was not set using `client.Client`.
2713
+ ValueError: If `config.staging_bucket` was not set when `agent_engine`
2714
+ is specified.
2715
+ ValueError: If `config.staging_bucket` does not start with "gs://".
2716
+ ValueError: If `config.extra_packages` is specified but `agent_engine`
2717
+ is None.
2718
+ ValueError: If `config.requirements` is specified but `agent_engine` is
2719
+ None.
2720
+ ValueError: If `config.env_vars` has a dictionary entry that does not
2721
+ correspond to an environment variable value or a SecretRef.
2722
+ TypeError: If `config.env_vars` is not a dictionary.
2723
+ FileNotFoundError: If `config.extra_packages` includes a file or
2724
+ directory that does not exist.
2725
+ IOError: If `config.requirements` is a string that corresponds to a
2726
+ nonexistent file.
2727
+ """
2728
+ if isinstance(config, dict):
2729
+ config = types.AgentEngineConfig.model_validate(config)
2730
+ elif not isinstance(config, types.AgentEngineConfig):
2731
+ raise TypeError(
2732
+ f"config must be a dict or AgentEngineConfig, but got {type(config)}."
2733
+ )
2734
+ context_spec = config.context_spec
2735
+ if context_spec is not None:
2736
+ # Conversion to a dict for _create_config
2737
+ context_spec = json.loads(context_spec.model_dump_json())
2738
+ developer_connect_source = config.developer_connect_source
2739
+ if developer_connect_source is not None:
2740
+ developer_connect_source = json.loads(
2741
+ developer_connect_source.model_dump_json()
2742
+ )
2743
+ agent_config_source = config.agent_config_source
2744
+ if agent_config_source is not None:
2745
+ agent_config_source = json.loads(agent_config_source.model_dump_json())
2746
+ keep_alive_probe = config.keep_alive_probe
2747
+ if keep_alive_probe is not None:
2748
+ keep_alive_probe = json.loads(
2749
+ keep_alive_probe.model_dump_json(exclude_none=True)
2750
+ )
2751
+ traffic_config = config.traffic_config
2752
+ if traffic_config is not None:
2753
+ traffic_config = json.loads(traffic_config.model_dump_json())
2754
+ if agent and agent_engine:
2755
+ raise ValueError("Please specify only one of `agent` or `agent_engine`.")
2756
+ elif agent_engine:
2757
+ raise DeprecationWarning(
2758
+ "The `agent_engine` argument is deprecated. Please use `agent` instead."
2759
+ )
2760
+ image_spec = config.image_spec
2761
+ if image_spec is not None:
2762
+ # Conversion to a dict for _create_config
2763
+ image_spec = json.loads(image_spec.model_dump_json())
2764
+ container_spec = config.container_spec
2765
+ if container_spec is not None:
2766
+ # Conversion to a dict for _create_config
2767
+ container_spec = json.loads(container_spec.model_dump_json())
2768
+ agent = agent or agent_engine
2769
+ api_config = self._create_config(
2770
+ mode="update",
2771
+ agent=agent,
2772
+ identity_type=config.identity_type,
2773
+ staging_bucket=config.staging_bucket,
2774
+ requirements=config.requirements,
2775
+ display_name=config.display_name,
2776
+ description=config.description,
2777
+ gcs_dir_name=config.gcs_dir_name,
2778
+ extra_packages=config.extra_packages,
2779
+ env_vars=config.env_vars,
2780
+ service_account=config.service_account,
2781
+ context_spec=context_spec,
2782
+ psc_interface_config=config.psc_interface_config,
2783
+ agent_gateway_config=config.agent_gateway_config,
2784
+ min_instances=config.min_instances,
2785
+ max_instances=config.max_instances,
2786
+ resource_limits=config.resource_limits,
2787
+ container_concurrency=config.container_concurrency,
2788
+ labels=config.labels,
2789
+ class_methods=config.class_methods,
2790
+ source_packages=config.source_packages,
2791
+ developer_connect_source=developer_connect_source,
2792
+ entrypoint_module=config.entrypoint_module,
2793
+ entrypoint_object=config.entrypoint_object,
2794
+ requirements_file=config.requirements_file,
2795
+ agent_framework=config.agent_framework,
2796
+ python_version=config.python_version,
2797
+ build_options=config.build_options,
2798
+ image_spec=image_spec,
2799
+ agent_config_source=agent_config_source,
2800
+ container_spec=container_spec,
2801
+ keep_alive_probe=keep_alive_probe,
2802
+ traffic_config=traffic_config,
2803
+ build_config=config.build_config,
2804
+ )
2805
+ operation = self._update(name=name, config=api_config)
2806
+ reasoning_engine_id = _agent_engines_utils._get_reasoning_engine_id(
2807
+ resource_name=name
2808
+ )
2809
+ logger.info(
2810
+ "View progress and logs at https://console.cloud.google.com/logs/query?"
2811
+ f"project={self._api_client.project}"
2812
+ "&query=resource.type%3D%22aiplatform.googleapis.com%2FReasoningEngine%22%0A"
2813
+ f"resource.labels.reasoning_engine_id%3D%22{reasoning_engine_id}%22."
2814
+ )
2815
+ operation = _agent_engines_utils._await_operation(
2816
+ operation_name=operation.name,
2817
+ get_operation_fn=self._get_agent_operation,
2818
+ )
2819
+ agent_engine = types.AgentEngine(
2820
+ api_client=self,
2821
+ api_async_client=AsyncAgentEngines(api_client_=self._api_client),
2822
+ api_resource=operation.response,
2823
+ )
2824
+ if agent_engine.api_resource:
2825
+ logger.info("Agent Engine updated. To use it in another session:")
2826
+ logger.info(
2827
+ f"agent_engine=client.agent_engines.get(name='{agent_engine.api_resource.name}')"
2828
+ )
2829
+ elif operation.error:
2830
+ raise RuntimeError(f"Failed to update Agent Engine: {operation.error}")
2831
+ if agent_engine.api_resource.spec:
2832
+ self._register_api_methods(agent_engine=agent_engine)
2833
+ return agent_engine # type: ignore[no-any-return]
2834
+
2835
+ def _stream_query(
2836
+ self, *, name: str, config: Optional[types.QueryAgentEngineConfigOrDict] = None
2837
+ ) -> Iterator[Any]:
2838
+ """Streams the response of the agent engine."""
2839
+ parameter_model = types._QueryAgentEngineRequestParameters(
2840
+ name=name,
2841
+ config=config,
2842
+ )
2843
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
2844
+ request_url_dict = request_dict.get("_url")
2845
+ if request_url_dict:
2846
+ path = "{name}:streamQuery?alt=sse".format_map(request_url_dict)
2847
+ else:
2848
+ path = "{name}:streamQuery?alt=sse"
2849
+ query_params = request_dict.get("_query")
2850
+ if query_params:
2851
+ path = f"{path}?{urlencode(query_params)}"
2852
+ # TODO: remove the hack that pops config.
2853
+ request_dict.pop("config", None)
2854
+ http_options = None
2855
+ if (
2856
+ parameter_model.config is not None
2857
+ and parameter_model.config.http_options is not None
2858
+ ):
2859
+ http_options = parameter_model.config.http_options
2860
+
2861
+ request_dict = _common.convert_to_dict(request_dict)
2862
+ request_dict = _common.encode_unserializable_types(request_dict)
2863
+ for response in self._api_client.request_streamed(
2864
+ "post", path, request_dict, http_options
2865
+ ):
2866
+ yield response
2867
+
2868
+ # TODO: b/436704146 - Replace with generated methods
2869
+ # TODO: b/437129724 - Add replay test for async stream query
2870
+ async def _async_stream_query(
2871
+ self,
2872
+ *,
2873
+ name: str,
2874
+ config: Optional[types.QueryAgentEngineConfigOrDict] = None,
2875
+ ) -> AsyncIterator[Any]:
2876
+ """Streams the response of the agent engine asynchronously."""
2877
+ parameter_model = types._QueryAgentEngineRequestParameters(
2878
+ name=name,
2879
+ config=config,
2880
+ )
2881
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
2882
+ request_url_dict = request_dict.get("_url")
2883
+ if request_url_dict:
2884
+ path = "{name}:streamQuery?alt=sse".format_map(request_url_dict)
2885
+ else:
2886
+ path = "{name}:streamQuery?alt=sse"
2887
+ query_params = request_dict.get("_query")
2888
+ if query_params:
2889
+ path = f"{path}?{urlencode(query_params)}"
2890
+ # TODO: remove the hack that pops config.
2891
+ request_dict.pop("config", None)
2892
+ http_options = None
2893
+ if (
2894
+ parameter_model.config is not None
2895
+ and parameter_model.config.http_options is not None
2896
+ ):
2897
+ http_options = parameter_model.config.http_options
2898
+
2899
+ request_dict = _common.convert_to_dict(request_dict)
2900
+ request_dict = _common.encode_unserializable_types(request_dict)
2901
+ async_iterator = await self._api_client.async_request_streamed(
2902
+ "post", path, request_dict, http_options
2903
+ )
2904
+ async for response in async_iterator:
2905
+ yield response
2906
+
2907
+ def create_session(
2908
+ self,
2909
+ *,
2910
+ name: str,
2911
+ user_id: str,
2912
+ config: Optional[types.CreateAgentEngineSessionConfigOrDict] = None,
2913
+ ) -> types.AgentEngineSessionOperation:
2914
+ """Deprecated. Use agent_engines.sessions.create instead."""
2915
+ warnings.warn(
2916
+ (
2917
+ "agent_engines.create_session is deprecated. "
2918
+ "Use agent_engines.sessions.create instead."
2919
+ ),
2920
+ DeprecationWarning,
2921
+ stacklevel=2,
2922
+ )
2923
+ return self.sessions.create(name=name, user_id=user_id, config=config)
2924
+
2925
+ def delete_session(
2926
+ self,
2927
+ *,
2928
+ name: str,
2929
+ config: Optional[types.DeleteAgentEngineSessionConfigOrDict] = None,
2930
+ ) -> types.DeleteAgentEngineSessionOperation:
2931
+ """Deprecated. Use agent_engines.sessions.delete instead."""
2932
+ warnings.warn(
2933
+ (
2934
+ "agent_engines.delete_session is deprecated. "
2935
+ "Use agent_engines.sessions.delete instead."
2936
+ ),
2937
+ DeprecationWarning,
2938
+ stacklevel=2,
2939
+ )
2940
+ return self.sessions.delete(name=name, config=config)
2941
+
2942
+ def get_session(
2943
+ self,
2944
+ *,
2945
+ name: str,
2946
+ config: Optional[types.GetAgentEngineSessionConfigOrDict] = None,
2947
+ ) -> types.Session:
2948
+ """Deprecated. Use agent_engines.sessions.get instead."""
2949
+ warnings.warn(
2950
+ (
2951
+ "agent_engines.get_session is deprecated. "
2952
+ "Use agent_engines.sessions.get instead."
2953
+ ),
2954
+ DeprecationWarning,
2955
+ stacklevel=2,
2956
+ )
2957
+ return self.sessions.get(name=name, config=config)
2958
+
2959
+ def list_sessions(
2960
+ self,
2961
+ *,
2962
+ name: str,
2963
+ config: Optional[types.ListAgentEngineSessionsConfigOrDict] = None,
2964
+ ) -> Iterator[types.Session]:
2965
+ """Deprecated. Use agent_engines.sessions.list instead."""
2966
+ warnings.warn(
2967
+ (
2968
+ "agent_engines.list_sessions is deprecated. "
2969
+ "Use agent_engines.sessions.list instead."
2970
+ ),
2971
+ DeprecationWarning,
2972
+ stacklevel=2,
2973
+ )
2974
+ return self.sessions.list(name=name, config=config)
2975
+
2976
+ def append_session_event(
2977
+ self,
2978
+ *,
2979
+ name: str,
2980
+ author: str,
2981
+ invocation_id: str,
2982
+ timestamp: datetime.datetime,
2983
+ config: Optional[types.AppendAgentEngineSessionEventConfigOrDict] = None,
2984
+ ) -> types.AppendAgentEngineSessionEventResponse:
2985
+ """Deprecated. Use agent_engines.sessions.events.append instead."""
2986
+ warnings.warn(
2987
+ (
2988
+ "agent_engines.append_session_event is deprecated. "
2989
+ "Use agent_engines.sessions.events.append instead."
2990
+ ),
2991
+ DeprecationWarning,
2992
+ stacklevel=2,
2993
+ )
2994
+ return self.sessions.events.append(
2995
+ name=name,
2996
+ author=author,
2997
+ invocation_id=invocation_id,
2998
+ timestamp=timestamp,
2999
+ config=config,
3000
+ )
3001
+
3002
+ def list_session_events(
3003
+ self,
3004
+ *,
3005
+ name: str,
3006
+ config: Optional[types.ListAgentEngineSessionEventsConfigOrDict] = None,
3007
+ ) -> Iterator[types.SessionEvent]:
3008
+ """Deprecated. Use agent_engines.sessions.events.list instead."""
3009
+ warnings.warn(
3010
+ (
3011
+ "agent_engines.list_session_events is deprecated. "
3012
+ "Use agent_engines.sessions.events.list instead."
3013
+ ),
3014
+ DeprecationWarning,
3015
+ stacklevel=2,
3016
+ )
3017
+ return self.sessions.events.list(name=name, config=config)
3018
+
3019
+
3020
+ class AsyncAgentEngines(_api_module.BaseModule):
3021
+
3022
+ async def cancel_query_job(
3023
+ self,
3024
+ *,
3025
+ name: str,
3026
+ config: Optional[types.CancelQueryJobAgentEngineConfigOrDict] = None,
3027
+ ) -> types.CancelQueryJobResult:
3028
+ """
3029
+ Cancels a long-running query job on an Agent Engine.
3030
+
3031
+ Args:
3032
+ name (str):
3033
+ Required. The reasoning engine resource name.
3034
+ config (CancelQueryJobAgentEngineConfigOrDict):
3035
+ Optional. The configuration for the cancel_query_job.
3036
+
3037
+ """
3038
+
3039
+ parameter_model = types._CancelQueryJobAgentEngineRequestParameters(
3040
+ name=name,
3041
+ config=config,
3042
+ )
3043
+
3044
+ request_url_dict: Optional[dict[str, str]]
3045
+ if not self._api_client.vertexai:
3046
+ raise ValueError(
3047
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3048
+ )
3049
+ else:
3050
+ request_dict = _CancelQueryJobAgentEngineRequestParameters_to_vertex(
3051
+ parameter_model
3052
+ )
3053
+ request_url_dict = request_dict.get("_url")
3054
+ if request_url_dict:
3055
+ path = "{name}:cancelAsyncQuery".format_map(request_url_dict)
3056
+ else:
3057
+ path = "{name}:cancelAsyncQuery"
3058
+
3059
+ query_params = request_dict.get("_query")
3060
+ if query_params:
3061
+ path = f"{path}?{urlencode(query_params)}"
3062
+ # TODO: remove the hack that pops config.
3063
+ request_dict.pop("config", None)
3064
+
3065
+ http_options: Optional[types.HttpOptions] = None
3066
+ if (
3067
+ parameter_model.config is not None
3068
+ and parameter_model.config.http_options is not None
3069
+ ):
3070
+ http_options = parameter_model.config.http_options
3071
+
3072
+ request_dict = _common.convert_to_dict(request_dict)
3073
+ request_dict = _common.encode_unserializable_types(request_dict)
3074
+
3075
+ response = await self._api_client.async_request(
3076
+ "post", path, request_dict, http_options
3077
+ )
3078
+
3079
+ response_dict = {} if not response.body else json.loads(response.body)
3080
+
3081
+ return_value = types.CancelQueryJobResult._from_response(
3082
+ response=response_dict,
3083
+ kwargs=(
3084
+ {
3085
+ "config": {
3086
+ "response_schema": getattr(
3087
+ parameter_model.config, "response_schema", None
3088
+ ),
3089
+ "response_json_schema": getattr(
3090
+ parameter_model.config, "response_json_schema", None
3091
+ ),
3092
+ "include_all_fields": getattr(
3093
+ parameter_model.config, "include_all_fields", None
3094
+ ),
3095
+ }
3096
+ }
3097
+ if getattr(parameter_model, "config", None)
3098
+ else {}
3099
+ ),
3100
+ )
3101
+
3102
+ self._api_client._verify_response(return_value)
3103
+ return return_value
3104
+
3105
+ async def _check_query_job(
3106
+ self,
3107
+ *,
3108
+ name: str,
3109
+ config: Optional[types.CheckQueryJobAgentEngineConfigOrDict] = None,
3110
+ ) -> types.CheckQueryJobResult:
3111
+ """
3112
+ Query an Agent Engine asynchronously.
3113
+ """
3114
+
3115
+ parameter_model = types._CheckQueryJobAgentEngineRequestParameters(
3116
+ name=name,
3117
+ config=config,
3118
+ )
3119
+
3120
+ request_url_dict: Optional[dict[str, str]]
3121
+ if not self._api_client.vertexai:
3122
+ raise ValueError(
3123
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3124
+ )
3125
+ else:
3126
+ request_dict = _CheckQueryJobAgentEngineRequestParameters_to_vertex(
3127
+ parameter_model
3128
+ )
3129
+ request_url_dict = request_dict.get("_url")
3130
+ if request_url_dict:
3131
+ path = "{name}:checkQueryJob".format_map(request_url_dict)
3132
+ else:
3133
+ path = "{name}:checkQueryJob"
3134
+
3135
+ query_params = request_dict.get("_query")
3136
+ if query_params:
3137
+ path = f"{path}?{urlencode(query_params)}"
3138
+ # TODO: remove the hack that pops config.
3139
+ request_dict.pop("config", None)
3140
+
3141
+ http_options: Optional[types.HttpOptions] = None
3142
+ if (
3143
+ parameter_model.config is not None
3144
+ and parameter_model.config.http_options is not None
3145
+ ):
3146
+ http_options = parameter_model.config.http_options
3147
+
3148
+ request_dict = _common.convert_to_dict(request_dict)
3149
+ request_dict = _common.encode_unserializable_types(request_dict)
3150
+
3151
+ response = await self._api_client.async_request(
3152
+ "post", path, request_dict, http_options
3153
+ )
3154
+
3155
+ response_dict = {} if not response.body else json.loads(response.body)
3156
+
3157
+ if self._api_client.vertexai:
3158
+ response_dict = _CheckQueryJobResult_from_vertex(response_dict)
3159
+
3160
+ return_value = types.CheckQueryJobResult._from_response(
3161
+ response=response_dict,
3162
+ kwargs=(
3163
+ {
3164
+ "config": {
3165
+ "response_schema": getattr(
3166
+ parameter_model.config, "response_schema", None
3167
+ ),
3168
+ "response_json_schema": getattr(
3169
+ parameter_model.config, "response_json_schema", None
3170
+ ),
3171
+ "include_all_fields": getattr(
3172
+ parameter_model.config, "include_all_fields", None
3173
+ ),
3174
+ }
3175
+ }
3176
+ if getattr(parameter_model, "config", None)
3177
+ else {}
3178
+ ),
3179
+ )
3180
+
3181
+ self._api_client._verify_response(return_value)
3182
+ return return_value
3183
+
3184
+ async def _run_query_job(
3185
+ self,
3186
+ *,
3187
+ name: str,
3188
+ config: Optional[types._RunQueryJobAgentEngineConfigOrDict] = None,
3189
+ ) -> types.AgentEngineOperation:
3190
+ """
3191
+ Run a query job on an agent engine.
3192
+ """
3193
+
3194
+ parameter_model = types._RunQueryJobAgentEngineRequestParameters(
3195
+ name=name,
3196
+ config=config,
3197
+ )
3198
+
3199
+ request_url_dict: Optional[dict[str, str]]
3200
+ if not self._api_client.vertexai:
3201
+ raise ValueError(
3202
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3203
+ )
3204
+ else:
3205
+ request_dict = _RunQueryJobAgentEngineRequestParameters_to_vertex(
3206
+ parameter_model
3207
+ )
3208
+ request_url_dict = request_dict.get("_url")
3209
+ if request_url_dict:
3210
+ path = "{name}:asyncQuery".format_map(request_url_dict)
3211
+ else:
3212
+ path = "{name}:asyncQuery"
3213
+
3214
+ query_params = request_dict.get("_query")
3215
+ if query_params:
3216
+ path = f"{path}?{urlencode(query_params)}"
3217
+ # TODO: remove the hack that pops config.
3218
+ request_dict.pop("config", None)
3219
+
3220
+ http_options: Optional[types.HttpOptions] = None
3221
+ if (
3222
+ parameter_model.config is not None
3223
+ and parameter_model.config.http_options is not None
3224
+ ):
3225
+ http_options = parameter_model.config.http_options
3226
+
3227
+ request_dict = _common.convert_to_dict(request_dict)
3228
+ request_dict = _common.encode_unserializable_types(request_dict)
3229
+
3230
+ response = await self._api_client.async_request(
3231
+ "post", path, request_dict, http_options
3232
+ )
3233
+
3234
+ response_dict = {} if not response.body else json.loads(response.body)
3235
+
3236
+ if self._api_client.vertexai:
3237
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
3238
+
3239
+ return_value = types.AgentEngineOperation._from_response(
3240
+ response=response_dict,
3241
+ kwargs=(
3242
+ {
3243
+ "config": {
3244
+ "response_schema": getattr(
3245
+ parameter_model.config, "response_schema", None
3246
+ ),
3247
+ "response_json_schema": getattr(
3248
+ parameter_model.config, "response_json_schema", None
3249
+ ),
3250
+ "include_all_fields": getattr(
3251
+ parameter_model.config, "include_all_fields", None
3252
+ ),
3253
+ }
3254
+ }
3255
+ if getattr(parameter_model, "config", None)
3256
+ else {}
3257
+ ),
3258
+ )
3259
+
3260
+ self._api_client._verify_response(return_value)
3261
+ return return_value
3262
+
3263
+ async def _create(
3264
+ self, *, config: Optional[types.CreateAgentEngineConfigOrDict] = None
3265
+ ) -> types.AgentEngineOperation:
3266
+ """
3267
+ Creates a new Agent Engine.
3268
+ """
3269
+
3270
+ parameter_model = types._CreateAgentEngineRequestParameters(
3271
+ config=config,
3272
+ )
3273
+
3274
+ request_url_dict: Optional[dict[str, str]]
3275
+ if not self._api_client.vertexai:
3276
+ raise ValueError(
3277
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3278
+ )
3279
+ else:
3280
+ request_dict = _CreateAgentEngineRequestParameters_to_vertex(
3281
+ parameter_model
3282
+ )
3283
+ request_url_dict = request_dict.get("_url")
3284
+ if request_url_dict:
3285
+ path = "reasoningEngines".format_map(request_url_dict)
3286
+ else:
3287
+ path = "reasoningEngines"
3288
+
3289
+ query_params = request_dict.get("_query")
3290
+ if query_params:
3291
+ path = f"{path}?{urlencode(query_params)}"
3292
+ # TODO: remove the hack that pops config.
3293
+ request_dict.pop("config", None)
3294
+
3295
+ http_options: Optional[types.HttpOptions] = None
3296
+ if (
3297
+ parameter_model.config is not None
3298
+ and parameter_model.config.http_options is not None
3299
+ ):
3300
+ http_options = parameter_model.config.http_options
3301
+
3302
+ request_dict = _common.convert_to_dict(request_dict)
3303
+ request_dict = _common.encode_unserializable_types(request_dict)
3304
+
3305
+ response = await self._api_client.async_request(
3306
+ "post", path, request_dict, http_options
3307
+ )
3308
+
3309
+ response_dict = {} if not response.body else json.loads(response.body)
3310
+
3311
+ if self._api_client.vertexai:
3312
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
3313
+
3314
+ return_value = types.AgentEngineOperation._from_response(
3315
+ response=response_dict,
3316
+ kwargs=(
3317
+ {
3318
+ "config": {
3319
+ "response_schema": getattr(
3320
+ parameter_model.config, "response_schema", None
3321
+ ),
3322
+ "response_json_schema": getattr(
3323
+ parameter_model.config, "response_json_schema", None
3324
+ ),
3325
+ "include_all_fields": getattr(
3326
+ parameter_model.config, "include_all_fields", None
3327
+ ),
3328
+ }
3329
+ }
3330
+ if getattr(parameter_model, "config", None)
3331
+ else {}
3332
+ ),
3333
+ )
3334
+
3335
+ self._api_client._verify_response(return_value)
3336
+ return return_value
3337
+
3338
+ async def _delete(
3339
+ self,
3340
+ *,
3341
+ name: str,
3342
+ force: Optional[bool] = None,
3343
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
3344
+ ) -> types.DeleteAgentEngineOperation:
3345
+ """
3346
+ Delete an Agent Engine resource.
3347
+
3348
+ Args:
3349
+ name (str):
3350
+ Required. The name of the Agent Engine to be deleted. Format:
3351
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
3352
+ or `reasoningEngines/{resource_id}`.
3353
+ force (bool):
3354
+ Optional. If set to True, child resources will also be deleted.
3355
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
3356
+ the Agent Engine has undeleted child resources. Defaults to False.
3357
+ config (DeleteAgentEngineConfig):
3358
+ Optional. Additional configurations for deleting the Agent Engine.
3359
+
3360
+ """
3361
+
3362
+ parameter_model = types._DeleteAgentEngineRequestParameters(
3363
+ name=name,
3364
+ force=force,
3365
+ config=config,
3366
+ )
3367
+
3368
+ request_url_dict: Optional[dict[str, str]]
3369
+ if not self._api_client.vertexai:
3370
+ raise ValueError(
3371
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3372
+ )
3373
+ else:
3374
+ request_dict = _DeleteAgentEngineRequestParameters_to_vertex(
3375
+ parameter_model
3376
+ )
3377
+ request_url_dict = request_dict.get("_url")
3378
+ if request_url_dict:
3379
+ path = "{name}".format_map(request_url_dict)
3380
+ else:
3381
+ path = "{name}"
3382
+
3383
+ query_params = request_dict.get("_query")
3384
+ if query_params:
3385
+ path = f"{path}?{urlencode(query_params)}"
3386
+ # TODO: remove the hack that pops config.
3387
+ request_dict.pop("config", None)
3388
+
3389
+ http_options: Optional[types.HttpOptions] = None
3390
+ if (
3391
+ parameter_model.config is not None
3392
+ and parameter_model.config.http_options is not None
3393
+ ):
3394
+ http_options = parameter_model.config.http_options
3395
+
3396
+ request_dict = _common.convert_to_dict(request_dict)
3397
+ request_dict = _common.encode_unserializable_types(request_dict)
3398
+
3399
+ response = await self._api_client.async_request(
3400
+ "delete", path, request_dict, http_options
3401
+ )
3402
+
3403
+ response_dict = {} if not response.body else json.loads(response.body)
3404
+
3405
+ return_value = types.DeleteAgentEngineOperation._from_response(
3406
+ response=response_dict,
3407
+ kwargs=(
3408
+ {
3409
+ "config": {
3410
+ "response_schema": getattr(
3411
+ parameter_model.config, "response_schema", None
3412
+ ),
3413
+ "response_json_schema": getattr(
3414
+ parameter_model.config, "response_json_schema", None
3415
+ ),
3416
+ "include_all_fields": getattr(
3417
+ parameter_model.config, "include_all_fields", None
3418
+ ),
3419
+ }
3420
+ }
3421
+ if getattr(parameter_model, "config", None)
3422
+ else {}
3423
+ ),
3424
+ )
3425
+
3426
+ self._api_client._verify_response(return_value)
3427
+ return return_value
3428
+
3429
+ async def _get(
3430
+ self, *, name: str, config: Optional[types.GetAgentEngineConfigOrDict] = None
3431
+ ) -> types.ReasoningEngine:
3432
+ """
3433
+ Get an Agent Engine instance.
3434
+ """
3435
+
3436
+ parameter_model = types._GetAgentEngineRequestParameters(
3437
+ name=name,
3438
+ config=config,
3439
+ )
3440
+
3441
+ request_url_dict: Optional[dict[str, str]]
3442
+ if not self._api_client.vertexai:
3443
+ raise ValueError(
3444
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3445
+ )
3446
+ else:
3447
+ request_dict = _GetAgentEngineRequestParameters_to_vertex(parameter_model)
3448
+ request_url_dict = request_dict.get("_url")
3449
+ if request_url_dict:
3450
+ path = "{name}".format_map(request_url_dict)
3451
+ else:
3452
+ path = "{name}"
3453
+
3454
+ query_params = request_dict.get("_query")
3455
+ if query_params:
3456
+ path = f"{path}?{urlencode(query_params)}"
3457
+ # TODO: remove the hack that pops config.
3458
+ request_dict.pop("config", None)
3459
+
3460
+ http_options: Optional[types.HttpOptions] = None
3461
+ if (
3462
+ parameter_model.config is not None
3463
+ and parameter_model.config.http_options is not None
3464
+ ):
3465
+ http_options = parameter_model.config.http_options
3466
+
3467
+ request_dict = _common.convert_to_dict(request_dict)
3468
+ request_dict = _common.encode_unserializable_types(request_dict)
3469
+
3470
+ response = await self._api_client.async_request(
3471
+ "get", path, request_dict, http_options
3472
+ )
3473
+
3474
+ response_dict = {} if not response.body else json.loads(response.body)
3475
+
3476
+ if self._api_client.vertexai:
3477
+ response_dict = _ReasoningEngine_from_vertex(response_dict)
3478
+
3479
+ return_value = types.ReasoningEngine._from_response(
3480
+ response=response_dict,
3481
+ kwargs=(
3482
+ {
3483
+ "config": {
3484
+ "response_schema": getattr(
3485
+ parameter_model.config, "response_schema", None
3486
+ ),
3487
+ "response_json_schema": getattr(
3488
+ parameter_model.config, "response_json_schema", None
3489
+ ),
3490
+ "include_all_fields": getattr(
3491
+ parameter_model.config, "include_all_fields", None
3492
+ ),
3493
+ }
3494
+ }
3495
+ if getattr(parameter_model, "config", None)
3496
+ else {}
3497
+ ),
3498
+ )
3499
+
3500
+ self._api_client._verify_response(return_value)
3501
+ return return_value
3502
+
3503
+ async def _list(
3504
+ self, *, config: Optional[types.ListAgentEngineConfigOrDict] = None
3505
+ ) -> types.ListReasoningEnginesResponse:
3506
+ """
3507
+ Lists Agent Engines.
3508
+ """
3509
+
3510
+ parameter_model = types._ListAgentEngineRequestParameters(
3511
+ config=config,
3512
+ )
3513
+
3514
+ request_url_dict: Optional[dict[str, str]]
3515
+ if not self._api_client.vertexai:
3516
+ raise ValueError(
3517
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3518
+ )
3519
+ else:
3520
+ request_dict = _ListAgentEngineRequestParameters_to_vertex(parameter_model)
3521
+ request_url_dict = request_dict.get("_url")
3522
+ if request_url_dict:
3523
+ path = "reasoningEngines".format_map(request_url_dict)
3524
+ else:
3525
+ path = "reasoningEngines"
3526
+
3527
+ query_params = request_dict.get("_query")
3528
+ if query_params:
3529
+ path = f"{path}?{urlencode(query_params)}"
3530
+ # TODO: remove the hack that pops config.
3531
+ request_dict.pop("config", None)
3532
+
3533
+ http_options: Optional[types.HttpOptions] = None
3534
+ if (
3535
+ parameter_model.config is not None
3536
+ and parameter_model.config.http_options is not None
3537
+ ):
3538
+ http_options = parameter_model.config.http_options
3539
+
3540
+ request_dict = _common.convert_to_dict(request_dict)
3541
+ request_dict = _common.encode_unserializable_types(request_dict)
3542
+
3543
+ response = await self._api_client.async_request(
3544
+ "get", path, request_dict, http_options
3545
+ )
3546
+
3547
+ response_dict = {} if not response.body else json.loads(response.body)
3548
+
3549
+ if self._api_client.vertexai:
3550
+ response_dict = _ListReasoningEnginesResponse_from_vertex(response_dict)
3551
+
3552
+ return_value = types.ListReasoningEnginesResponse._from_response(
3553
+ response=response_dict,
3554
+ kwargs=(
3555
+ {
3556
+ "config": {
3557
+ "response_schema": getattr(
3558
+ parameter_model.config, "response_schema", None
3559
+ ),
3560
+ "response_json_schema": getattr(
3561
+ parameter_model.config, "response_json_schema", None
3562
+ ),
3563
+ "include_all_fields": getattr(
3564
+ parameter_model.config, "include_all_fields", None
3565
+ ),
3566
+ }
3567
+ }
3568
+ if getattr(parameter_model, "config", None)
3569
+ else {}
3570
+ ),
3571
+ )
3572
+
3573
+ self._api_client._verify_response(return_value)
3574
+ return return_value
3575
+
3576
+ async def _get_agent_operation(
3577
+ self,
3578
+ *,
3579
+ operation_name: str,
3580
+ config: Optional[types.GetAgentEngineOperationConfigOrDict] = None,
3581
+ ) -> types.AgentEngineOperation:
3582
+ parameter_model = types._GetAgentEngineOperationParameters(
3583
+ operation_name=operation_name,
3584
+ config=config,
3585
+ )
3586
+
3587
+ request_url_dict: Optional[dict[str, str]]
3588
+ if not self._api_client.vertexai:
3589
+ raise ValueError(
3590
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3591
+ )
3592
+ else:
3593
+ request_dict = _GetAgentEngineOperationParameters_to_vertex(parameter_model)
3594
+ request_url_dict = request_dict.get("_url")
3595
+ if request_url_dict:
3596
+ path = "{operationName}".format_map(request_url_dict)
3597
+ else:
3598
+ path = "{operationName}"
3599
+
3600
+ query_params = request_dict.get("_query")
3601
+ if query_params:
3602
+ path = f"{path}?{urlencode(query_params)}"
3603
+ # TODO: remove the hack that pops config.
3604
+ request_dict.pop("config", None)
3605
+
3606
+ http_options: Optional[types.HttpOptions] = None
3607
+ if (
3608
+ parameter_model.config is not None
3609
+ and parameter_model.config.http_options is not None
3610
+ ):
3611
+ http_options = parameter_model.config.http_options
3612
+
3613
+ request_dict = _common.convert_to_dict(request_dict)
3614
+ request_dict = _common.encode_unserializable_types(request_dict)
3615
+
3616
+ response = await self._api_client.async_request(
3617
+ "get", path, request_dict, http_options
3618
+ )
3619
+
3620
+ response_dict = {} if not response.body else json.loads(response.body)
3621
+
3622
+ if self._api_client.vertexai:
3623
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
3624
+
3625
+ return_value = types.AgentEngineOperation._from_response(
3626
+ response=response_dict,
3627
+ kwargs=(
3628
+ {
3629
+ "config": {
3630
+ "response_schema": getattr(
3631
+ parameter_model.config, "response_schema", None
3632
+ ),
3633
+ "response_json_schema": getattr(
3634
+ parameter_model.config, "response_json_schema", None
3635
+ ),
3636
+ "include_all_fields": getattr(
3637
+ parameter_model.config, "include_all_fields", None
3638
+ ),
3639
+ }
3640
+ }
3641
+ if getattr(parameter_model, "config", None)
3642
+ else {}
3643
+ ),
3644
+ )
3645
+
3646
+ self._api_client._verify_response(return_value)
3647
+ return return_value
3648
+
3649
+ async def _query(
3650
+ self, *, name: str, config: Optional[types.QueryAgentEngineConfigOrDict] = None
3651
+ ) -> types.QueryReasoningEngineResponse:
3652
+ """
3653
+ Query an Agent Engine.
3654
+ """
3655
+
3656
+ parameter_model = types._QueryAgentEngineRequestParameters(
3657
+ name=name,
3658
+ config=config,
3659
+ )
3660
+
3661
+ request_url_dict: Optional[dict[str, str]]
3662
+ if not self._api_client.vertexai:
3663
+ raise ValueError(
3664
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3665
+ )
3666
+ else:
3667
+ request_dict = _QueryAgentEngineRequestParameters_to_vertex(parameter_model)
3668
+ request_url_dict = request_dict.get("_url")
3669
+ if request_url_dict:
3670
+ path = "{name}:query".format_map(request_url_dict)
3671
+ else:
3672
+ path = "{name}:query"
3673
+
3674
+ query_params = request_dict.get("_query")
3675
+ if query_params:
3676
+ path = f"{path}?{urlencode(query_params)}"
3677
+ # TODO: remove the hack that pops config.
3678
+ request_dict.pop("config", None)
3679
+
3680
+ http_options: Optional[types.HttpOptions] = None
3681
+ if (
3682
+ parameter_model.config is not None
3683
+ and parameter_model.config.http_options is not None
3684
+ ):
3685
+ http_options = parameter_model.config.http_options
3686
+
3687
+ request_dict = _common.convert_to_dict(request_dict)
3688
+ request_dict = _common.encode_unserializable_types(request_dict)
3689
+
3690
+ response = await self._api_client.async_request(
3691
+ "post", path, request_dict, http_options
3692
+ )
3693
+
3694
+ response_dict = {} if not response.body else json.loads(response.body)
3695
+
3696
+ return_value = types.QueryReasoningEngineResponse._from_response(
3697
+ response=response_dict,
3698
+ kwargs=(
3699
+ {
3700
+ "config": {
3701
+ "response_schema": getattr(
3702
+ parameter_model.config, "response_schema", None
3703
+ ),
3704
+ "response_json_schema": getattr(
3705
+ parameter_model.config, "response_json_schema", None
3706
+ ),
3707
+ "include_all_fields": getattr(
3708
+ parameter_model.config, "include_all_fields", None
3709
+ ),
3710
+ }
3711
+ }
3712
+ if getattr(parameter_model, "config", None)
3713
+ else {}
3714
+ ),
3715
+ )
3716
+
3717
+ self._api_client._verify_response(return_value)
3718
+ return return_value
3719
+
3720
+ async def _update(
3721
+ self, *, name: str, config: Optional[types.UpdateAgentEngineConfigOrDict] = None
3722
+ ) -> types.AgentEngineOperation:
3723
+ """
3724
+ Updates an Agent Engine.
3725
+ """
3726
+
3727
+ parameter_model = types._UpdateAgentEngineRequestParameters(
3728
+ name=name,
3729
+ config=config,
3730
+ )
3731
+
3732
+ request_url_dict: Optional[dict[str, str]]
3733
+ if not self._api_client.vertexai:
3734
+ raise ValueError(
3735
+ "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
3736
+ )
3737
+ else:
3738
+ request_dict = _UpdateAgentEngineRequestParameters_to_vertex(
3739
+ parameter_model
3740
+ )
3741
+ request_url_dict = request_dict.get("_url")
3742
+ if request_url_dict:
3743
+ path = "{name}".format_map(request_url_dict)
3744
+ else:
3745
+ path = "{name}"
3746
+
3747
+ query_params = request_dict.get("_query")
3748
+ if query_params:
3749
+ path = f"{path}?{urlencode(query_params)}"
3750
+ # TODO: remove the hack that pops config.
3751
+ request_dict.pop("config", None)
3752
+
3753
+ http_options: Optional[types.HttpOptions] = None
3754
+ if (
3755
+ parameter_model.config is not None
3756
+ and parameter_model.config.http_options is not None
3757
+ ):
3758
+ http_options = parameter_model.config.http_options
3759
+
3760
+ request_dict = _common.convert_to_dict(request_dict)
3761
+ request_dict = _common.encode_unserializable_types(request_dict)
3762
+
3763
+ response = await self._api_client.async_request(
3764
+ "patch", path, request_dict, http_options
3765
+ )
3766
+
3767
+ response_dict = {} if not response.body else json.loads(response.body)
3768
+
3769
+ if self._api_client.vertexai:
3770
+ response_dict = _AgentEngineOperation_from_vertex(response_dict)
3771
+
3772
+ return_value = types.AgentEngineOperation._from_response(
3773
+ response=response_dict,
3774
+ kwargs=(
3775
+ {
3776
+ "config": {
3777
+ "response_schema": getattr(
3778
+ parameter_model.config, "response_schema", None
3779
+ ),
3780
+ "response_json_schema": getattr(
3781
+ parameter_model.config, "response_json_schema", None
3782
+ ),
3783
+ "include_all_fields": getattr(
3784
+ parameter_model.config, "include_all_fields", None
3785
+ ),
3786
+ }
3787
+ }
3788
+ if getattr(parameter_model, "config", None)
3789
+ else {}
3790
+ ),
3791
+ )
3792
+
3793
+ self._api_client._verify_response(return_value)
3794
+ return return_value
3795
+
3796
+ _a2a_tasks = None
3797
+ _sessions = None
3798
+ _runtimes = None
3799
+
3800
+ async def delete(
3801
+ self,
3802
+ *,
3803
+ name: str,
3804
+ force: Optional[bool] = None,
3805
+ config: Optional[types.DeleteAgentEngineConfigOrDict] = None,
3806
+ ) -> types.DeleteAgentEngineOperation:
3807
+ """
3808
+ Delete an Agent Engine resource.
3809
+
3810
+ Args:
3811
+ name (str):
3812
+ Required. The name of the Agent Engine to be deleted. Format:
3813
+ `projects/{project}/locations/{location}/reasoningEngines/{resource_id}`
3814
+ or `reasoningEngines/{resource_id}`.
3815
+ force (bool):
3816
+ Optional. If set to True, child resources will also be deleted.
3817
+ Otherwise, the request will fail with FAILED_PRECONDITION error when
3818
+ the Agent Engine has undeleted child resources. Defaults to False.
3819
+ config (DeleteAgentEngineConfig):
3820
+ Optional. Additional configurations for deleting the Agent Engine.
3821
+
3822
+ """
3823
+ logger.info(f"Deleting AgentEngine resource: {name}")
3824
+ operation = await self._delete(name=name, force=force, config=config)
3825
+ logger.info(f"Started AgentEngine delete operation: {operation.name}")
3826
+ return operation
3827
+
3828
+ @property
3829
+ def runtimes(self) -> "runtimes_module.AsyncRuntimes":
3830
+ if self._runtimes is None:
3831
+ try:
3832
+ # We need to lazy load the runtimes module to handle the
3833
+ # possibility of ImportError when dependencies are not installed.
3834
+ self._runtimes = importlib.import_module(".runtimes", __package__)
3835
+ except ImportError as e:
3836
+ raise ImportError(
3837
+ "The 'agent_engines.runtimes' module requires additional "
3838
+ "packages. Please install them using pip install "
3839
+ "google-cloud-aiplatform[agent_engines]"
3840
+ ) from e
3841
+ return self._runtimes.AsyncRuntimes(self._api_client) # type: ignore[no-any-return]
3842
+
3843
+ @property
3844
+ def a2a_tasks(self) -> "a2a_tasks_module.AsyncA2aTasks":
3845
+ if self._a2a_tasks is None:
3846
+ try:
3847
+ # We need to lazy load the a2a_tasks module to handle the
3848
+ # possibility of ImportError when dependencies are not installed.
3849
+ self._a2a_tasks = importlib.import_module(".a2a_tasks", __package__)
3850
+ except ImportError as e:
3851
+ raise ImportError(
3852
+ "The 'agent_engines.a2a_tasks' module requires additional "
3853
+ "packages. Please install them using pip install "
3854
+ "google-cloud-aiplatform[agent_engines]"
3855
+ ) from e
3856
+ return self._a2a_tasks.AsyncA2aTasks(self._api_client) # type: ignore[no-any-return]
3857
+
3858
+ @property
3859
+ def sessions(self) -> "sessions_module.AsyncSessions":
3860
+ if self._sessions is None:
3861
+ try:
3862
+ # We need to lazy load the sessions module to handle the
3863
+ # possibility of ImportError when dependencies are not installed.
3864
+ self._sessions = importlib.import_module(".sessions", __package__)
3865
+ except ImportError as e:
3866
+ raise ImportError(
3867
+ "The agent_engines.sessions module requires additional packages. "
3868
+ "Please install them using pip install "
3869
+ "google-cloud-aiplatform[agent_engines]"
3870
+ ) from e
3871
+ return self._sessions.AsyncSessions(self._api_client) # type: ignore[no-any-return]
3872
+
3873
+ async def append_session_event(
3874
+ self,
3875
+ *,
3876
+ name: str,
3877
+ author: str,
3878
+ invocation_id: str,
3879
+ timestamp: datetime.datetime,
3880
+ config: Optional[types.AppendAgentEngineSessionEventConfigOrDict] = None,
3881
+ ) -> types.AppendAgentEngineSessionEventResponse:
3882
+ """Deprecated. Use agent_engines.sessions.events.append instead."""
3883
+ warnings.warn(
3884
+ (
3885
+ "agent_engines.append_session_event is deprecated. "
3886
+ "Use agent_engines.sessions.events.append instead."
3887
+ ),
3888
+ DeprecationWarning,
3889
+ stacklevel=2,
3890
+ )
3891
+ return await self.sessions.events.append(
3892
+ name=name,
3893
+ author=author,
3894
+ invocation_id=invocation_id,
3895
+ timestamp=timestamp,
3896
+ config=config,
3897
+ )
3898
+
3899
+ async def delete_session(
3900
+ self,
3901
+ *,
3902
+ name: str,
3903
+ config: Optional[types.DeleteAgentEngineSessionConfigOrDict] = None,
3904
+ ) -> types.DeleteAgentEngineSessionOperation:
3905
+ """Deprecated. Use agent_engines.sessions.delete instead."""
3906
+ warnings.warn(
3907
+ (
3908
+ "agent_engines.delete_session is deprecated. "
3909
+ "Use agent_engines.sessions.delete instead."
3910
+ ),
3911
+ DeprecationWarning,
3912
+ stacklevel=2,
3913
+ )
3914
+ return await self.sessions.delete(name=name, config=config)
3915
+
3916
+ async def get_session(
3917
+ self,
3918
+ *,
3919
+ name: str,
3920
+ config: Optional[types.GetAgentEngineSessionConfigOrDict] = None,
3921
+ ) -> types.Session:
3922
+ """Deprecated. Use agent_engines.sessions.get instead."""
3923
+ warnings.warn(
3924
+ (
3925
+ "agent_engines.get_session is deprecated. "
3926
+ "Use agent_engines.sessions.get instead."
3927
+ ),
3928
+ DeprecationWarning,
3929
+ stacklevel=2,
3930
+ )
3931
+ return await self.sessions.get(name=name, config=config)