-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy path_agent_engines.py
More file actions
1992 lines (1776 loc) · 77.9 KB
/
_agent_engines.py
File metadata and controls
1992 lines (1776 loc) · 77.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import abc
import inspect
import io
import json
import logging
import os
import sys
import tarfile
import types
import typing
from typing import (
Any,
AsyncIterable,
Callable,
Coroutine,
Dict,
Iterable,
List,
Optional,
Protocol,
Sequence,
Tuple,
Union,
)
from google.api_core import exceptions
from google.cloud import storage
from google.cloud.aiplatform import base
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform import utils as aip_utils
from google.cloud.aiplatform_v1 import types as aip_types
from google.cloud.aiplatform_v1.types import reasoning_engine_service
from vertexai.agent_engines import _utils
import httpx
import proto
from google.protobuf import field_mask_pb2
_LOGGER = _utils.LOGGER
_SUPPORTED_PYTHON_VERSIONS = ("3.9", "3.10", "3.11", "3.12", "3.13", "3.14")
_DEFAULT_GCS_DIR_NAME = "agent_engine"
_BLOB_FILENAME = "agent_engine.pkl"
_REQUIREMENTS_FILE = "requirements.txt"
_EXTRA_PACKAGES_FILE = "dependencies.tar.gz"
_STANDARD_API_MODE = ""
_ASYNC_API_MODE = "async"
_STREAM_API_MODE = "stream"
_ASYNC_STREAM_API_MODE = "async_stream"
_BIDI_STREAM_API_MODE = "bidi_stream"
_A2A_EXTENSION_MODE = "a2a_extension"
_A2A_AGENT_CARD = "a2a_agent_card"
_MODE_KEY_IN_SCHEMA = "api_mode"
_METHOD_NAME_KEY_IN_SCHEMA = "name"
_DEFAULT_METHOD_NAME = "query"
_DEFAULT_ASYNC_METHOD_NAME = "async_query"
_DEFAULT_STREAM_METHOD_NAME = "stream_query"
_DEFAULT_ASYNC_STREAM_METHOD_NAME = "async_stream_query"
_DEFAULT_METHOD_RETURN_TYPE = "dict[str, Any]"
_DEFAULT_ASYNC_METHOD_RETURN_TYPE = "Coroutine[Any, Any, Any]"
_DEFAULT_STREAM_METHOD_RETURN_TYPE = "Iterable[Any]"
_DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE = "AsyncIterable[Any]"
_DEFAULT_METHOD_DOCSTRING_TEMPLATE = """
Runs the Agent Engine to serve the user request.
This will be based on the `.{method_name}(...)` of the python object that
was passed in when creating the Agent Engine. The method will invoke the
`{default_method_name}` API client of the python object.
Args:
**kwargs:
Optional. The arguments of the `.{method_name}(...)` method.
Returns:
{return_type}: The response from serving the user request.
"""
_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE = (
"Failed to register API methods. Please follow the guide to "
"register the API methods: "
"https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#custom-methods. "
"Error: {%s}"
)
_AGENT_FRAMEWORK_ATTR = "agent_framework"
_DEFAULT_AGENT_FRAMEWORK = "custom"
_BUILD_OPTIONS_INSTALLATION = "installation_scripts"
_DEFAULT_METHOD_NAME_MAP = {
_STANDARD_API_MODE: _DEFAULT_METHOD_NAME,
_ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_NAME,
_STREAM_API_MODE: _DEFAULT_STREAM_METHOD_NAME,
_ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_NAME,
}
_DEFAULT_METHOD_RETURN_TYPE_MAP = {
_STANDARD_API_MODE: _DEFAULT_METHOD_RETURN_TYPE,
_ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_RETURN_TYPE,
_STREAM_API_MODE: _DEFAULT_STREAM_METHOD_RETURN_TYPE,
_ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE,
}
try:
from google.adk.agents import BaseAgent
ADKAgent = BaseAgent
except (ImportError, AttributeError):
ADKAgent = None
try:
from a2a.types import (
AgentCard,
TransportProtocol,
Message,
TaskIdParams,
TaskQueryParams,
)
from a2a.client import ClientConfig, ClientFactory
AgentCard = AgentCard
TransportProtocol = TransportProtocol
Message = Message
ClientConfig = ClientConfig
ClientFactory = ClientFactory
TaskIdParams = TaskIdParams
TaskQueryParams = TaskQueryParams
except (ImportError, AttributeError):
AgentCard = None
TransportProtocol = None
Message = None
ClientConfig = None
ClientFactory = None
TaskIdParams = None
TaskQueryParams = None
@typing.runtime_checkable
class Queryable(Protocol):
"""Protocol for Agent Engines that can be queried."""
@abc.abstractmethod
def query(self, **kwargs) -> Any:
"""Runs the Agent Engine to serve the user query."""
@typing.runtime_checkable
class AsyncQueryable(Protocol):
"""Protocol for Agent Engines that can be queried asynchronously."""
@abc.abstractmethod
def async_query(self, **kwargs) -> Coroutine[Any, Any, Any]:
"""Runs the Agent Engine to serve the user query asynchronously."""
@typing.runtime_checkable
class AsyncStreamQueryable(Protocol):
"""Protocol for Agent Engines that can stream responses asynchronously."""
@abc.abstractmethod
async def async_stream_query(self, **kwargs) -> AsyncIterable[Any]:
"""Asynchronously stream responses to serve the user query."""
@typing.runtime_checkable
class StreamQueryable(Protocol):
"""Protocol for Agent Engines that can stream responses."""
@abc.abstractmethod
def stream_query(self, **kwargs) -> Iterable[Any]:
"""Stream responses to serve the user query."""
@typing.runtime_checkable
class BidiStreamQueryable(Protocol):
"""Protocol for Agent Engines that can stream requests and responses."""
@abc.abstractmethod
async def bidi_stream_query(self, **kwargs) -> AsyncIterable[Any]:
"""Asynchronously stream requests and responses to serve the user query."""
@typing.runtime_checkable
class Cloneable(Protocol):
"""Protocol for Agent Engines that can be cloned."""
@abc.abstractmethod
def clone(self) -> Any:
"""Return a clone of the object."""
@typing.runtime_checkable
class OperationRegistrable(Protocol):
"""Protocol for agents that have registered operations."""
@abc.abstractmethod
def register_operations(self, **kwargs) -> Dict[str, Sequence[str]]:
"""Register the user provided operations (modes and methods)."""
_AgentEngineInterface = Union[
ADKAgent,
AsyncQueryable,
AsyncStreamQueryable,
BidiStreamQueryable,
OperationRegistrable,
Queryable,
StreamQueryable,
]
def _wrap_agent_operation(agent: Any, operation: str):
"""Wraps an agent operation into a method (works for all API modes)."""
def _method(self, **kwargs):
if not self._tmpl_attrs.get("agent"):
self.set_up()
return getattr(self._tmpl_attrs["agent"], operation)(**kwargs)
_method.__name__ = operation
_method.__doc__ = getattr(agent, operation).__doc__
return _method
class ModuleAgent(Cloneable, OperationRegistrable):
"""Agent that is defined by a module and an agent name.
This agent is instantiated by importing a module and instantiating an agent
from that module. It also allows to register operations that are defined in
the agent.
"""
def __init__(
self,
*,
module_name: str,
agent_name: str,
register_operations: Dict[str, Sequence[str]],
sys_paths: Optional[Sequence[str]] = None,
agent_framework: Optional[str] = None,
):
"""Initializes a module-based agent.
Args:
module_name (str):
Required. The name of the module to import.
agent_name (str):
Required. The name of the agent in the module to instantiate.
register_operations (Dict[str, Sequence[str]]):
Required. A dictionary of API modes to a list of method names.
sys_paths (Sequence[str]):
Optional. The system paths to search for the module. It should
be relative to the directory where the code will be running.
I.e. it should correspond to the directory being passed to
`extra_packages=...` in the create method. It will be appended
to the system path in the sequence being specified here, and
only be appended if it is not already in the system path.
"""
self.agent_framework = agent_framework
self._tmpl_attrs = {
"module_name": module_name,
"agent_name": agent_name,
"register_operations": register_operations,
"sys_paths": sys_paths,
}
def clone(self):
"""Return a clone of the agent."""
return ModuleAgent(
module_name=self._tmpl_attrs.get("module_name"),
agent_name=self._tmpl_attrs.get("agent_name"),
register_operations=self._tmpl_attrs.get("register_operations"),
sys_paths=self._tmpl_attrs.get("sys_paths"),
agent_framework=self.agent_framework,
)
def register_operations(self, **kwargs) -> Dict[str, Sequence[str]]:
return self._tmpl_attrs.get("register_operations")
def set_up(self) -> None:
"""Sets up the agent for execution of queries at runtime.
It runs the code to import the agent from the module, and registers the
operations of the agent.
"""
if self._tmpl_attrs.get("sys_paths"):
import sys
for sys_path in self._tmpl_attrs.get("sys_paths"):
abs_path = os.path.abspath(sys_path)
if abs_path not in sys.path:
sys.path.append(abs_path)
import importlib
module = importlib.import_module(self._tmpl_attrs.get("module_name"))
try:
importlib.reload(module)
except Exception as e:
_LOGGER.warning(
f"Failed to reload module {self._tmpl_attrs.get('module_name')}: {e}"
)
agent_name = self._tmpl_attrs.get("agent_name")
try:
agent = getattr(module, agent_name)
except AttributeError as e:
raise AttributeError(
f"Agent {agent_name} not found in module "
f"{self._tmpl_attrs.get('module_name')}"
) from e
if not self.agent_framework:
self.agent_framework = _get_agent_framework(agent)
self._tmpl_attrs["agent"] = agent
if hasattr(agent, "set_up"):
agent.set_up()
for operations in self.register_operations().values():
for operation in operations:
op = _wrap_agent_operation(agent, operation)
setattr(self, operation, types.MethodType(op, self))
class AgentEngine(base.VertexAiResourceNounWithFutureManager):
"""Represents a Vertex AI Agent Engine resource."""
client_class = aip_utils.AgentEngineClientWithOverride
_resource_noun = "reasoning_engine"
_getter_method = "get_reasoning_engine"
_list_method = "list_reasoning_engines"
_delete_method = "delete_reasoning_engine"
_parse_resource_name_method = "parse_reasoning_engine_path"
_format_resource_name_method = "reasoning_engine_path"
def __init__(self, resource_name: str):
"""Retrieves an Agent Engine resource.
Args:
resource_name (str):
Required. A fully-qualified resource name or ID such as
"projects/123/locations/us-central1/reasoningEngines/456" or
"456" when project and location are initialized or passed.
"""
super().__init__(resource_name=resource_name)
self.execution_api_client = initializer.global_config.create_client(
client_class=aip_utils.AgentEngineExecutionClientWithOverride,
)
self.execution_async_client = initializer.global_config.create_client(
client_class=aip_utils.AgentEngineExecutionAsyncClientWithOverride,
)
self._gca_resource = self._get_gca_resource(resource_name=resource_name)
try:
_register_api_methods_or_raise(self)
except Exception as e:
_LOGGER.warning(_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e)
self._operation_schemas = None
@property
def resource_name(self) -> str:
"""Fully-qualified resource name."""
return self._gca_resource.name
@classmethod
def create(
cls,
agent_engine: Optional[_AgentEngineInterface] = None,
*,
requirements: Optional[Union[str, Sequence[str]]] = None,
display_name: Optional[str] = None,
description: Optional[str] = None,
gcs_dir_name: Optional[str] = None,
extra_packages: Optional[Sequence[str]] = None,
env_vars: Optional[
Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
] = None,
build_options: Optional[Dict[str, Sequence[str]]] = None,
service_account: Optional[str] = None,
psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
min_instances: Optional[int] = None,
max_instances: Optional[int] = None,
resource_limits: Optional[Dict[str, str]] = None,
container_concurrency: Optional[int] = None,
encryption_spec: Optional[aip_types.EncryptionSpec] = None,
) -> "AgentEngine":
"""Creates a new Agent Engine.
The Agent Engine will be an instance of the `agent_engine` that
was passed in, running remotely on Vertex AI.
Sample `src_dir` contents (e.g. `./user_src_dir`):
.. code-block:: python
user_src_dir/
|-- main.py
|-- requirements.txt
|-- user_code/
| |-- utils.py
| |-- ...
|-- installation_scripts/
| |-- install_package.sh
| |-- ...
|-- ...
To build an Agent Engine with the above files, run:
.. code-block:: python
remote_agent = agent_engines.create(
agent_engine=local_agent,
requirements=[
# I.e. the PyPI dependencies listed in requirements.txt
"google-cloud-aiplatform==1.25.0",
"langchain==0.0.242",
...
],
extra_packages=[
"./user_src_dir/main.py", # a single file
"./user_src_dir/user_code", # a directory
...
],
build_options={
"installation_scripts": [
"./user_src_dir/installation_scripts/install_package.sh",
...
],
},
)
Args:
agent_engine (AgentEngineInterface):
Optional. The Agent Engine to be created.
requirements (Union[str, Sequence[str]]):
Optional. The set of PyPI dependencies needed. It can either be
the path to a single file (requirements.txt), or an ordered list
of strings corresponding to each line of the requirements file.
display_name (str):
Optional. The user-defined name of the Agent Engine.
The name can be up to 128 characters long and can comprise any
UTF-8 character.
description (str):
Optional. The description of the Agent Engine.
gcs_dir_name (str):
Optional. The GCS bucket directory under `staging_bucket` to
use for staging the artifacts needed.
extra_packages (Sequence[str]):
Optional. The set of extra user-provided packages (if any).
env_vars (Union[Sequence[str], Dict[str, Union[str, SecretRef]]]):
Optional. The environment variables to be set when running the
Agent Engine. If it is a list of strings, each string should be
a valid key to `os.environ`. If it is a dictionary, the keys are
the environment variable names, and the values are the
corresponding values.
build_options (Dict[str, Sequence[str]]):
Optional. The build options for the Agent Engine.
The following keys are supported:
- installation_scripts:
Optional. The paths to the installation scripts to be
executed in the Docker image.
The scripts must be located in the `installation_scripts`
subdirectory and the path must be added to `extra_packages`.
service_account (str):
Optional. The service account to be used for the Agent Engine.
If not specified, the default reasoning engine service agent
service account will be used.
psc_interface_config (aip_types.PscInterfaceConfig):
Optional. The Private Service Connect interface config for the
Agent Engine.
min_instances (int):
Optional. The minimum number of instances to be running for the
Agent Engine.
max_instances (int):
Optional. The maximum number of instances to be running for the
Agent Engine.
resource_limits (Dict[str, str]):
Optional. The resource limits for the Agent Engine.
container_concurrency (int):
Optional. The container concurrency for the Agent Engine.
encryption_spec (aip_types.EncryptionSpec):
Optional. The Cloud KMS resource identifier of the customer
managed encryption key used to protect the model. Has the
form:
`projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`.
The key needs to be in the same region as the model.
Returns:
AgentEngine: The Agent Engine that was created.
Raises:
ValueError: If the `project` was not set using `vertexai.init`.
ValueError: If the `location` was not set using `vertexai.init`.
ValueError: If the `staging_bucket` was not set using vertexai.init.
ValueError: If the `staging_bucket` does not start with "gs://".
ValueError: If `extra_packages` is specified but `agent_engine` is None.
ValueError: If `requirements` is specified but `agent_engine` is None.
ValueError: If `env_vars` has a dictionary entry that does not
correspond to a SecretRef.
ValueError: If `env_vars` is a list which contains a string that
does not exist in `os.environ`.
TypeError: If `env_vars` is not a list of strings or a dictionary.
TypeError: If `env_vars` has a value that is not a string or SecretRef.
FileNotFoundError: If `extra_packages` includes a file or directory
that does not exist.
IOError: If requirements is a string that corresponds to a
nonexistent file.
"""
sys_version = f"{sys.version_info.major}.{sys.version_info.minor}"
_validate_sys_version_or_raise(sys_version)
gcs_dir_name = gcs_dir_name or _DEFAULT_GCS_DIR_NAME
staging_bucket = initializer.global_config.staging_bucket
if agent_engine is not None:
agent_engine = _validate_agent_engine_or_raise(agent_engine)
staging_bucket = _validate_staging_bucket_or_raise(staging_bucket)
if _is_adk_agent(None, agent_engine):
env_vars = _add_telemetry_enablement_env(env_vars=env_vars)
if agent_engine is None:
if requirements is not None:
raise ValueError("requirements must be None if agent_engine is None.")
if extra_packages is not None:
raise ValueError("extra_packages must be None if agent_engine is None.")
requirements = _validate_requirements_or_raise(
agent_engine=agent_engine,
requirements=requirements,
)
extra_packages = _validate_extra_packages_or_raise(
extra_packages=extra_packages,
build_options=build_options,
)
sdk_resource = cls.__new__(cls)
base.VertexAiResourceNounWithFutureManager.__init__(sdk_resource)
# Prepares the Agent Engine for creation in Vertex AI.
# This involves packaging and uploading the artifacts for
# agent_engine, requirements and extra_packages to
# `staging_bucket/gcs_dir_name`.
_prepare(
agent_engine=agent_engine,
requirements=requirements,
project=sdk_resource.project,
location=sdk_resource.location,
staging_bucket=staging_bucket,
gcs_dir_name=gcs_dir_name,
extra_packages=extra_packages,
)
reasoning_engine = aip_types.ReasoningEngine(
display_name=display_name,
description=description,
encryption_spec=encryption_spec,
)
if agent_engine is not None:
# Update the package spec.
package_spec = aip_types.ReasoningEngineSpec.PackageSpec(
python_version=sys_version,
pickle_object_gcs_uri="{}/{}/{}".format(
staging_bucket,
gcs_dir_name,
_BLOB_FILENAME,
),
)
if extra_packages:
package_spec.dependency_files_gcs_uri = "{}/{}/{}".format(
staging_bucket,
gcs_dir_name,
_EXTRA_PACKAGES_FILE,
)
if requirements:
package_spec.requirements_gcs_uri = "{}/{}/{}".format(
staging_bucket,
gcs_dir_name,
_REQUIREMENTS_FILE,
)
agent_engine_spec = aip_types.ReasoningEngineSpec(
package_spec=package_spec,
)
if (
env_vars
or psc_interface_config
or min_instances is not None
or max_instances is not None
or resource_limits
or container_concurrency is not None
):
deployment_spec, _ = _generate_deployment_spec_or_raise(
env_vars=env_vars,
psc_interface_config=psc_interface_config,
min_instances=min_instances,
max_instances=max_instances,
resource_limits=resource_limits,
container_concurrency=container_concurrency,
)
agent_engine_spec.deployment_spec = deployment_spec
class_methods_spec = _generate_class_methods_spec_or_raise(
agent_engine=agent_engine,
operations=_get_registered_operations(agent_engine),
)
agent_engine_spec.class_methods.extend(class_methods_spec)
if service_account:
agent_engine_spec.service_account = service_account
reasoning_engine.spec = agent_engine_spec
reasoning_engine.spec.agent_framework = _get_agent_framework(agent_engine)
operation_future = sdk_resource.api_client.create_reasoning_engine(
parent=initializer.global_config.common_location_path(
project=sdk_resource.project, location=sdk_resource.location
),
reasoning_engine=reasoning_engine,
)
_LOGGER.log_create_with_lro(cls, operation_future)
_LOGGER.info(
f"View progress and logs at https://console.cloud.google.com/logs/query?project={sdk_resource.project}"
)
created_resource = operation_future.result()
_LOGGER.info(f"{cls.__name__} created. Resource name: {created_resource.name}")
_LOGGER.info(f"To use this {cls.__name__} in another session:")
_LOGGER.info(
f"agent_engine = vertexai.agent_engines.get('{created_resource.name}')"
)
# We use `._get_gca_resource(...)` instead of `created_resource` to
# fully instantiate the attributes of the agent engine.
sdk_resource._gca_resource = sdk_resource._get_gca_resource(
resource_name=created_resource.name
)
sdk_resource.execution_api_client = initializer.global_config.create_client(
client_class=aip_utils.AgentEngineExecutionClientWithOverride,
credentials=sdk_resource.credentials,
location_override=sdk_resource.location,
)
sdk_resource.execution_async_client = initializer.global_config.create_client(
client_class=aip_utils.AgentEngineExecutionAsyncClientWithOverride,
credentials=sdk_resource.credentials,
location_override=sdk_resource.location,
)
if agent_engine is not None:
try:
_register_api_methods_or_raise(sdk_resource)
except Exception as e:
_LOGGER.warning(_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e)
sdk_resource._operation_schemas = None
return sdk_resource
def update(
self,
*,
agent_engine: Optional[_AgentEngineInterface] = None,
requirements: Optional[Union[str, Sequence[str]]] = None,
display_name: Optional[str] = None,
description: Optional[str] = None,
gcs_dir_name: Optional[str] = None,
extra_packages: Optional[Sequence[str]] = None,
env_vars: Optional[
Union[Sequence[str], Dict[str, Union[str, aip_types.SecretRef]]]
] = None,
build_options: Optional[Dict[str, Sequence[str]]] = None,
service_account: Optional[str] = None,
psc_interface_config: Optional[aip_types.PscInterfaceConfig] = None,
min_instances: Optional[int] = None,
max_instances: Optional[int] = None,
resource_limits: Optional[Dict[str, str]] = None,
container_concurrency: Optional[int] = None,
encryption_spec: Optional[aip_types.EncryptionSpec] = None,
) -> "AgentEngine":
"""Updates an existing Agent Engine.
This method updates the configuration of an existing Agent Engine
running remotely, which is identified by its resource name.
Unlike the `create` function which requires a `agent_engine` object,
all arguments in this method are optional.
This method allows you to modify individual aspects of the configuration
by providing any of the optional arguments.
Args:
agent_engine (AgentEngineInterface):
Optional. The instance to be used as the updated Agent Engine.
If it is not specified, the existing instance will be used.
requirements (Union[str, Sequence[str]]):
Optional. The set of PyPI dependencies needed. It can either be
the path to a single file (requirements.txt), or an ordered list
of strings corresponding to each line of the requirements file.
If it is not specified, the existing requirements will be used.
If it is set to an empty string or list, the existing
requirements will be removed.
display_name (str):
Optional. The user-defined name of the Agent Engine.
The name can be up to 128 characters long and can comprise any
UTF-8 character.
description (str):
Optional. The description of the Agent Engine.
gcs_dir_name (str):
Optional. The GCS bucket directory under `staging_bucket` to
use for staging the artifacts needed.
extra_packages (Sequence[str]):
Optional. The set of extra user-provided packages (if any). If
it is not specified, the existing extra packages will be used.
If it is set to an empty list, the existing extra packages will
be removed.
env_vars (Union[Sequence[str], Dict[str, Union[str, SecretRef]]]):
Optional. The environment variables to be set when running the
Agent Engine. If it is a list of strings, each string should be
a valid key to `os.environ`. If it is a dictionary, the keys are
the environment variable names, and the values are the
corresponding values.
build_options (Dict[str, Sequence[str]]):
Optional. The build options for the Agent Engine.
The following keys are supported:
- installation_scripts:
Optional. The paths to the installation scripts to be
executed in the Docker image.
The scripts must be located in the `installation_scripts`
subdirectory and the path must be added to `extra_packages`.
service_account (str):
Optional. The service account to be used for the Agent Engine.
If not specified, the default reasoning engine service agent
service account will be used.
psc_interface_config (aip_types.PscInterfaceConfig):
Optional. The Private Service Connect interface config for the
Agent Engine.
min_instances (int):
Optional. The minimum number of instances to be running for the
Agent Engine.
max_instances (int):
Optional. The maximum number of instances to be running for the
Agent Engine.
resource_limits (Dict[str, str]):
Optional. The resource limits for the Agent Engine.
container_concurrency (int):
Optional. The container concurrency for the Agent Engine.
encryption_spec (aip_types.EncryptionSpec):
Optional. The Cloud KMS resource identifier of the customer
managed encryption key used to protect the model. Has the
form:
`projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`.
The key needs to be in the same region as the model.
Returns:
AgentEngine: The Agent Engine that was updated.
Raises:
ValueError: If the `staging_bucket` was not set using vertexai.init.
ValueError: If the `staging_bucket` does not start with "gs://".
ValueError: If `env_vars` has a dictionary entry that does not
correspond to a SecretRef.
ValueError: If `env_vars` is a list which contains a string that
does not exist in `os.environ`.
TypeError: If `env_vars` is not a list of strings or a dictionary.
TypeError: If `env_vars` has a value that is not a string or SecretRef.
FileNotFoundError: If `extra_packages` includes a file or directory
that does not exist.
ValueError: if none of `display_name`, `description`, `requirements`,
`extra_packages`, `env_vars`, or `agent_engine` were specified.
IOError: If requirements is a string that corresponds to a
nonexistent file.
"""
staging_bucket = initializer.global_config.staging_bucket
staging_bucket = _validate_staging_bucket_or_raise(staging_bucket)
historical_operation_schemas = self.operation_schemas()
gcs_dir_name = gcs_dir_name or _DEFAULT_GCS_DIR_NAME
# Validate the arguments.
if not any(
[
agent_engine,
requirements,
extra_packages,
display_name,
description,
env_vars,
build_options,
service_account,
psc_interface_config,
min_instances is not None,
max_instances is not None,
resource_limits,
container_concurrency is not None,
encryption_spec,
]
):
raise ValueError(
"At least one of `agent_engine`, `requirements`, "
"`extra_packages`, `display_name`, `description`, "
"`env_vars`, `build_options`, `service_account`, "
"`psc_interface_config`, `min_instances`, `max_instances`, "
"`resource_limits`, `container_concurrency`, or "
"`encryption_spec` must be specified."
)
if requirements is not None:
requirements = _validate_requirements_or_raise(
agent_engine=agent_engine,
requirements=requirements,
)
if extra_packages is not None:
extra_packages = _validate_extra_packages_or_raise(
extra_packages=extra_packages,
build_options=build_options,
)
if agent_engine is not None:
agent_engine = _validate_agent_engine_or_raise(agent_engine)
if _is_adk_agent(self, agent_engine):
env_vars = _add_telemetry_enablement_env(env_vars=env_vars)
# Prepares the Agent Engine for update in Vertex AI. This involves
# packaging and uploading the artifacts for agent_engine, requirements
# and extra_packages to `staging_bucket/gcs_dir_name`.
_prepare(
agent_engine=agent_engine,
requirements=requirements,
project=self.project,
location=self.location,
staging_bucket=staging_bucket,
gcs_dir_name=gcs_dir_name,
extra_packages=extra_packages,
)
update_request = _generate_update_request_or_raise(
resource_name=self.resource_name,
staging_bucket=staging_bucket,
gcs_dir_name=gcs_dir_name,
agent_engine=agent_engine,
requirements=requirements,
extra_packages=extra_packages,
display_name=display_name,
description=description,
env_vars=env_vars,
service_account=service_account,
psc_interface_config=psc_interface_config,
min_instances=min_instances,
max_instances=max_instances,
resource_limits=resource_limits,
container_concurrency=container_concurrency,
encryption_spec=encryption_spec,
)
operation_future = self.api_client.update_reasoning_engine(
request=update_request
)
_LOGGER.info(
f"Update Agent Engine backing LRO: {operation_future.operation.name}"
)
created_resource = operation_future.result()
_LOGGER.info(f"Agent Engine updated. Resource name: {created_resource.name}")
self._operation_schemas = None
self.execution_api_client = initializer.global_config.create_client(
client_class=aip_utils.AgentEngineExecutionClientWithOverride,
)
# We use `._get_gca_resource(...)` instead of `created_resource` to
# fully instantiate the attributes of the agent engine.
self._gca_resource = self._get_gca_resource(resource_name=self.resource_name)
if (
agent_engine is None
or historical_operation_schemas == self.operation_schemas()
):
# The operations of the agent engine are unchanged, so we return it.
return self
# If the agent engine has changed and the historical operation
# schemas are different from the current operation schemas, we need to
# unregister the historical operation schemas and register the current
# operation schemas.
_unregister_api_methods(self, historical_operation_schemas)
try:
_register_api_methods_or_raise(self)
except Exception as e:
_LOGGER.warning(_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE, e)
return self
def delete(
self,
*,
force: bool = False,
**kwargs,
) -> None:
"""Deletes the ReasoningEngine.
Args:
force (bool):
Optional. If set to True, child resources will also be deleted.
Otherwise, the request will fail with FAILED_PRECONDITION error
when the Agent Engine has undeleted child resources. Defaults to
False.
**kwargs (dict[str, Any]):
Optional. Additional keyword arguments to pass to the
delete_reasoning_engine method.
"""
kwargs = kwargs or {}
operation_future = self.api_client.delete_reasoning_engine(
request=aip_types.DeleteReasoningEngineRequest(
name=self.resource_name,
force=force,
**kwargs,
),
)
_LOGGER.info(
f"Delete Agent Engine backing LRO: {operation_future.operation.name}"
)
operation_future.result()
_LOGGER.info(f"Agent Engine deleted. Resource name: {self.resource_name}")
def operation_schemas(self) -> Sequence[_utils.JsonDict]:
"""Returns the (Open)API schemas for the Agent Engine."""
spec = _utils.to_dict(self._gca_resource.spec)
if not hasattr(self, "_operation_schemas") or self._operation_schemas is None:
self._operation_schemas = spec.get("class_methods", [])
return self._operation_schemas
def _validate_sys_version_or_raise(sys_version: str) -> None:
"""Tries to validate the python system version."""
if sys_version not in _SUPPORTED_PYTHON_VERSIONS:
raise ValueError(
f"Unsupported python version: {sys_version}. AgentEngine "
f"only supports {_SUPPORTED_PYTHON_VERSIONS} at the moment."
)
if sys_version != f"{sys.version_info.major}.{sys.version_info.minor}":
_LOGGER.warning(
f"{sys_version=} is inconsistent with {sys.version_info=}. "
"This might result in issues with deployment, and should only "
"be used as a workaround for advanced cases."
)
def _validate_staging_bucket_or_raise(staging_bucket: Optional[str]) -> str:
"""Tries to validate the staging bucket."""
if not staging_bucket:
raise ValueError("Please provide a `staging_bucket` in `vertexai.init(...)`")
if not staging_bucket.startswith("gs://"):
raise ValueError(f"{staging_bucket=} must start with `gs://`")
return staging_bucket
def _validate_agent_engine_or_raise(
agent_engine: _AgentEngineInterface,
logger: base.Logger = _LOGGER,
) -> _AgentEngineInterface:
"""Tries to validate the agent engine.
The agent engine must have one of the following:
* a callable method named `query`
* a callable method named `stream_query`
* a callable method named `async_stream_query`
* a callable method named `bidi_stream_query`
* a callable method named `register_operations`
Args:
agent_engine: The agent engine to be validated.
logger: The logger to use for logging.
Returns:
The validated agent engine.
Raises:
TypeError: If `agent_engine` has no callable method named `query`,
`stream_query` or `register_operations`.
ValueError: If `agent_engine` has an invalid `query`, `stream_query` or
`register_operations` signature.
"""
try:
from google.adk.agents import BaseAgent
if isinstance(agent_engine, BaseAgent):
logger.info("Deploying google.adk.agents.Agent as an application.")
from vertexai import agent_engines
agent_engine = agent_engines.AdkApp(agent=agent_engine)
except Exception:
pass
is_queryable = isinstance(agent_engine, Queryable) and callable(agent_engine.query)
is_async_queryable = isinstance(agent_engine, AsyncQueryable) and callable(
agent_engine.async_query
)
is_stream_queryable = isinstance(agent_engine, StreamQueryable) and callable(
agent_engine.stream_query
)
is_async_stream_queryable = isinstance(
agent_engine, AsyncStreamQueryable
) and callable(agent_engine.async_stream_query)
is_bidi_stream_queryable = isinstance(
agent_engine, BidiStreamQueryable
) and callable(agent_engine.bidi_stream_query)
is_operation_registrable = isinstance(
agent_engine, OperationRegistrable
) and callable(agent_engine.register_operations)
if not (
is_queryable
or is_async_queryable
or is_stream_queryable
or is_operation_registrable
or is_async_stream_queryable
or is_bidi_stream_queryable
):
raise TypeError(
"agent_engine has none of the following callable methods: "
"`query`, `async_query`, `stream_query`, `async_stream_query`, "