-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy path_agent_engines_utils.py
More file actions
2266 lines (1935 loc) · 79.8 KB
/
_agent_engines_utils.py
File metadata and controls
2266 lines (1935 loc) · 79.8 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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Utility functions for agent engines."""
import abc
import asyncio
import base64
import dataclasses
from importlib import metadata as importlib_metadata
import inspect
import io
import json
import logging
import os
import re
import sys
import tarfile
import time
import types
import typing
from typing import (
Any,
AsyncIterator,
Callable,
Coroutine,
Dict,
Iterator,
List,
Mapping,
Optional,
Protocol,
Sequence,
Set,
TypedDict,
Union,
)
import httpx
import proto
from google.api_core import exceptions
from google.genai import types as google_genai_types
from google.protobuf import struct_pb2
from google.protobuf import json_format
from . import types as genai_types
if sys.version_info >= (3, 10):
from typing import TypeAlias
else:
from typing_extensions import TypeAlias
try:
_BUILTIN_MODULE_NAMES: Sequence[str] = sys.builtin_module_names
except AttributeError:
_BUILTIN_MODULE_NAMES: Sequence[str] = [] # type: ignore[no-redef]
try:
_PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = (
importlib_metadata.packages_distributions()
)
except AttributeError:
_PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = {} # type: ignore[no-redef]
try:
# sys.stdlib_module_names is available from Python 3.10 onwards.
_STDLIB_MODULE_NAMES: frozenset[str] = sys.stdlib_module_names
except AttributeError:
_STDLIB_MODULE_NAMES: frozenset[str] = frozenset() # type: ignore[no-redef]
if typing.TYPE_CHECKING:
from google.cloud import storage # type: ignore[attr-defined]
_StorageBucket: TypeAlias = storage.Bucket
else:
try:
from google.cloud import storage # type: ignore[attr-defined]
_StorageBucket: type[Any] = storage.Bucket
except (ImportError, AttributeError):
_StorageBucket: type[Any] = Any # type: ignore[no-redef]
if typing.TYPE_CHECKING:
import packaging
_SpecifierSet = packaging.specifiers.SpecifierSet
else:
try:
import packaging
_SpecifierSet: type[Any] = packaging.specifiers.SpecifierSet
except (ImportError, AttributeError):
_SpecifierSet: type[Any] = Any # type: ignore[no-redef]
try:
from a2a.types import (
AgentCard,
TransportProtocol,
Message,
TaskIdParams,
TaskQueryParams,
)
from a2a.client import ClientConfig, ClientFactory
AgentCard = AgentCard
TransportProtocol = TransportProtocol
Message = Message
ClientConfig = ClientConfig
ClientFactory = ClientFactory
TaskIdParams = TaskIdParams
TaskQueryParams = TaskQueryParams
except (ImportError, AttributeError):
AgentCard = None
TransportProtocol = None
Message = None
ClientConfig = None
ClientFactory = None
TaskIdParams = None
TaskQueryParams = None
try:
from autogen.agentchat import chat
AutogenChatResult = chat.ChatResult
except ImportError:
AutogenChatResult = Any
try:
from autogen.io import run_response
AutogenRunResponse = run_response.RunResponse
except ImportError:
AutogenRunResponse = Any
try:
from llama_index.core.base.response import schema as llama_index_schema
from llama_index.core.base.llms import types as llama_index_types
LlamaIndexResponse = llama_index_schema.Response
LlamaIndexBaseModel = llama_index_schema.BaseModel
LlamaIndexChatResponse = llama_index_types.ChatResponse
except ImportError:
LlamaIndexResponse = Any
LlamaIndexBaseModel = Any
LlamaIndexChatResponse = Any
try:
import pydantic
BaseModel = pydantic.BaseModel
except ImportError:
BaseModel = Any
JsonDict = Dict[str, Any]
_ACTIONS_KEY = "actions"
_ACTION_APPEND = "append"
_AGENT_FRAMEWORK_ATTR = "agent_framework"
_ASYNC_API_MODE = "async"
_ASYNC_STREAM_API_MODE = "async_stream"
_BIDI_STREAM_API_MODE = "bidi_stream"
_BASE_MODULES = set(_BUILTIN_MODULE_NAMES).union(_STDLIB_MODULE_NAMES)
_BLOB_FILENAME = "agent_engine.pkl"
_DEFAULT_AGENT_FRAMEWORK = "custom"
_SUPPORTED_AGENT_FRAMEWORKS = frozenset(
[
"google-adk",
"langchain",
"langgraph",
"ag2",
"llama-index",
"custom",
"a2a",
]
)
_DEFAULT_ASYNC_METHOD_NAME = "async_query"
_DEFAULT_ASYNC_METHOD_RETURN_TYPE = "Coroutine[Any]"
_DEFAULT_ASYNC_STREAM_METHOD_NAME = "async_stream_query"
_DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE = "AsyncIterable[Any]"
_DEFAULT_GCS_DIR_NAME = "agent_engine"
_DEFAULT_METHOD_DOCSTRING_TEMPLATE = """
Runs the Agent Engine to serve the user request.
This will be based on the `.{method_name}(...)` of the python object that
was passed in when creating the Agent Engine. The method will invoke the
`{default_method_name}` API client of the python object.
Args:
**kwargs:
Optional. The arguments of the `.{method_name}(...)` method.
Returns:
{return_type}: The response from serving the user request.
"""
_DEFAULT_METHOD_NAME = "query"
_DEFAULT_METHOD_RETURN_TYPE = "dict[str, Any]"
_DEFAULT_STREAM_METHOD_RETURN_TYPE = "Iterable[Any]"
_DEFAULT_REQUIRED_PACKAGES = frozenset(["cloudpickle", "pydantic"])
_DEFAULT_STREAM_METHOD_NAME = "stream_query"
_DEFAULT_BIDI_STREAM_METHOD_NAME = "bidi_stream_query"
_EXTRA_PACKAGES_FILE = "dependencies.tar.gz"
_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE = (
"Failed to register API methods. Please follow the guide to "
"register the API methods: "
"https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#custom-methods. "
"Error: {%s}"
)
_INSTALLATION_SUBDIR = "installation_scripts"
_METHOD_NAME_KEY_IN_SCHEMA = "name"
_MODE_KEY_IN_SCHEMA = "api_mode"
_REQUIREMENTS_FILE = "requirements.txt"
_STANDARD_API_MODE = ""
_STREAM_API_MODE = "stream"
_A2A_EXTENSION_MODE = "a2a_extension"
_A2A_AGENT_CARD = "a2a_agent_card"
_WARNINGS_KEY = "warnings"
_WARNING_MISSING = "missing"
_WARNING_INCOMPATIBLE = "incompatible"
_DEFAULT_METHOD_NAME_MAP = {
_STANDARD_API_MODE: _DEFAULT_METHOD_NAME,
_ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_NAME,
_STREAM_API_MODE: _DEFAULT_STREAM_METHOD_NAME,
_ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_NAME,
}
_DEFAULT_METHOD_RETURN_TYPE_MAP = {
_STANDARD_API_MODE: _DEFAULT_METHOD_RETURN_TYPE,
_ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_RETURN_TYPE,
_STREAM_API_MODE: _DEFAULT_STREAM_METHOD_RETURN_TYPE,
_ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE,
}
logger = logging.getLogger("agentplatform_genai.agentengines")
@typing.runtime_checkable
class Queryable(Protocol):
"""Protocol for Agent Engines that can be queried."""
@abc.abstractmethod
def query(self, **kwargs): # type: ignore[no-untyped-def]
"""Runs the Agent Engine to serve the user query."""
@typing.runtime_checkable
class AsyncQueryable(Protocol):
"""Protocol for Agent Engines that can be queried asynchronously."""
@abc.abstractmethod
def async_query(self, **kwargs): # type: ignore[no-untyped-def]
"""Runs the Agent Engine to serve the user query asynchronously."""
@typing.runtime_checkable
class AsyncStreamQueryable(Protocol):
"""Protocol for Agent Engines that can stream responses asynchronously."""
@abc.abstractmethod
async def async_stream_query(self, **kwargs) -> AsyncIterator[Any]: # type: ignore[no-untyped-def]
"""Asynchronously stream responses to serve the user query."""
@typing.runtime_checkable
class StreamQueryable(Protocol):
"""Protocol for Agent Engines that can stream responses."""
@abc.abstractmethod
def stream_query(self, **kwargs) -> Iterator[Any]: # type: ignore[no-untyped-def]
"""Stream responses to serve the user query."""
@typing.runtime_checkable
class BidiStreamQueryable(Protocol):
"""Protocol for Agent Engines that can stream requests and responses."""
@abc.abstractmethod
async def bidi_stream_query(
self, input_queue: asyncio.Queue[Any]
) -> AsyncIterator[Any]:
"""Stream requests and responses to serve the user queries."""
@typing.runtime_checkable
class Cloneable(Protocol):
"""Protocol for Agent Engines that can be cloned."""
@abc.abstractmethod
def clone(self) -> Any:
"""Return a clone of the object."""
@typing.runtime_checkable
class OperationRegistrable(Protocol):
"""Protocol for agents that have registered operations."""
@abc.abstractmethod
def register_operations(self, **kwargs: Any) -> dict[str, list[str]]:
"""Register the user provided operations (modes and methods)."""
pass
if typing.TYPE_CHECKING:
from google.adk.agents import BaseAgent
ADKAgent: TypeAlias = BaseAgent
else:
try:
from google.adk.agents import BaseAgent
ADKAgent: Optional[TypeAlias] = BaseAgent
except (ImportError, AttributeError):
ADKAgent = None # type: ignore[no-redef]
_AgentEngineInterface = Union[
ADKAgent,
AsyncQueryable,
AsyncStreamQueryable,
OperationRegistrable,
Queryable,
StreamQueryable,
BidiStreamQueryable,
]
class _ModuleAgentAttributes(TypedDict, total=False):
module_name: str
agent_name: str
register_operations: Dict[str, list[str]]
sys_paths: Optional[Sequence[str]]
agent: _AgentEngineInterface
class ModuleAgent(Cloneable, OperationRegistrable):
"""Agent that is defined by a module and an agent name.
This agent is instantiated by importing a module and instantiating an agent
from that module. It also allows to register operations that are defined in
the agent.
"""
def __init__(
self,
*,
module_name: str,
agent_name: str,
register_operations: Dict[str, list[str]],
sys_paths: Optional[Sequence[str]] = None,
):
"""Initializes a module-based agent.
Args:
module_name (str):
Required. The name of the module to import.
agent_name (str):
Required. The name of the agent in the module to instantiate.
register_operations (Dict[str, list[str]]):
Required. A dictionary of API modes to a list of method names.
sys_paths (Sequence[str]):
Optional. The system paths to search for the module. It should
be relative to the directory where the code will be running.
I.e. it should correspond to the directory being passed to
`extra_packages=...` in the create method. It will be appended
to the system path in the sequence being specified here, and
only be appended if it is not already in the system path.
"""
self._tmpl_attrs: _ModuleAgentAttributes = {
"module_name": module_name,
"agent_name": agent_name,
"register_operations": register_operations,
"sys_paths": sys_paths,
}
def clone(self) -> "ModuleAgent":
"""Return a clone of the agent."""
return ModuleAgent(
module_name=self._tmpl_attrs.get("module_name"),
agent_name=self._tmpl_attrs.get("agent_name"),
register_operations=self._tmpl_attrs.get("register_operations"),
sys_paths=self._tmpl_attrs.get("sys_paths"),
)
def register_operations(self, **kwargs: Any) -> dict[str, list[str]]:
reg_operations = self._tmpl_attrs.get("register_operations")
if reg_operations is None:
raise ValueError("Register operations is not set.")
return reg_operations
def set_up(self) -> None:
"""Sets up the agent for execution of queries at runtime.
It runs the code to import the agent from the module, and registers the
operations of the agent.
"""
sys_paths = self._tmpl_attrs.get("sys_paths")
if isinstance(sys_paths, Sequence):
import sys
for sys_path in sys_paths:
abs_path = os.path.abspath(sys_path)
if abs_path not in sys.path:
sys.path.append(abs_path)
import importlib
module = importlib.import_module(self._tmpl_attrs.get("module_name"))
try:
importlib.reload(module)
except Exception as e:
logger.warning(
f"Failed to reload module {self._tmpl_attrs.get('module_name')}: {e}"
)
agent_name = self._tmpl_attrs.get("agent_name")
try:
agent = getattr(module, agent_name)
except AttributeError as e:
raise AttributeError(
f"Agent {agent_name} not found in module "
f"{self._tmpl_attrs.get('module_name')}"
) from e
self._tmpl_attrs["agent"] = agent
if hasattr(agent, "set_up"):
agent.set_up()
for operations in self.register_operations().values():
for operation in operations:
op = _wrap_agent_operation(agent=agent, operation=operation)
setattr(self, operation, types.MethodType(op, self))
class _RequirementsValidationActions(TypedDict):
append: Set[str]
class _RequirementsValidationWarnings(TypedDict):
missing: Set[str]
incompatible: Set[str]
class _RequirementsValidationResult(TypedDict):
warnings: _RequirementsValidationWarnings
actions: _RequirementsValidationActions
AgentEngineOperationUnion = Union[
genai_types.AgentEngineOperation,
genai_types.AgentEngineMemoryOperation,
genai_types.AgentEngineGenerateMemoriesOperation,
]
class GetOperationFunction(Protocol):
def __call__(
self, *, operation_name: str, **kwargs: Any
) -> AgentEngineOperationUnion:
pass
class GetAsyncOperationFunction(Protocol):
async def __call__(
self, *, operation_name: str, **kwargs: Any
) -> AgentEngineOperationUnion:
pass
def _get_reasoning_engine_id(operation_name: str = "", resource_name: str = "") -> str:
"""Returns reasoning engine ID from operation name or resource name."""
if not resource_name and not operation_name:
raise ValueError("Resource name or operation name cannot be empty.")
if resource_name:
match = re.match(
r"^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)$",
resource_name,
)
if match:
return match.group(1)
else:
raise ValueError(
"Failed to parse reasoning engine ID from resource name: "
f"`{resource_name}`"
)
if not operation_name:
raise ValueError("Operation name cannot be empty.")
match = re.match(
r"^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)/operations/[^/]+$",
operation_name,
)
if match:
return match.group(1)
raise ValueError(
"Failed to parse reasoning engine ID from operation name: "
f"`{operation_name}`"
)
async def _await_async_operation(
*,
operation_name: str,
get_operation_fn: GetAsyncOperationFunction,
poll_interval_seconds: float = 10,
) -> Any:
"""Waits for the operation for creating an agent engine to complete.
Args:
operation_name (str):
Required. The name of the operation for creating the Agent Engine.
poll_interval_seconds (float):
The number of seconds to wait between each poll.
get_operation_fn (Callable[[str], Awaitable[Any]]):
Optional. The async function to use for getting the operation. If not
provided, `self._get_agent_operation` will be used.
Returns:
The operation that has completed (i.e. `operation.done==True`).
"""
operation = await get_operation_fn(operation_name=operation_name)
while not operation.done:
await asyncio.sleep(poll_interval_seconds)
operation = await get_operation_fn(operation_name=operation.name)
return operation
def _await_operation(
*,
operation_name: str,
get_operation_fn: GetOperationFunction,
poll_interval_seconds: float = 10,
) -> Any:
"""Waits for the operation for creating an agent engine to complete.
Args:
operation_name (str):
Required. The name of the operation for creating the Agent Engine.
poll_interval_seconds (float):
The number of seconds to wait between each poll.
get_operation_fn (Callable[[str], Any]):
Optional. The function to use for getting the operation. If not
provided, `self._get_agent_operation` will be used.
Returns:
The operation that has completed (i.e. `operation.done==True`).
"""
operation = get_operation_fn(operation_name=operation_name)
while not operation.done:
time.sleep(poll_interval_seconds)
operation = get_operation_fn(operation_name=operation.name)
return operation
def _compare_requirements(
*,
requirements: Mapping[str, str],
constraints: Union[Sequence[str], Mapping[str, Optional["_SpecifierSet"]]],
required_packages: Optional[Iterator[str]] = None,
) -> _RequirementsValidationResult:
"""Compares the requirements with the constraints.
Args:
requirements (Mapping[str, str]):
Required. The packages (and their versions) to compare with the constraints.
This is assumed to be the result of `scan_requirements`.
constraints (Union[Sequence[str], Mapping[str, SpecifierSet]]):
Required. The package constraints to compare against. This is assumed
to be the result of `parse_constraints`.
required_packages (Iterator[str]):
Optional. The set of packages that are required to be in the
constraints. It defaults to the set of packages that are required
for deployment on Agent Engine.
Returns:
dict[str, dict[str, Any]]: The comparison result as a dictionary containing:
* warnings:
* missing: The set of packages that are not in the constraints.
* incompatible: The set of packages that are in the constraints
but have versions that are not in the constraint specifier.
* actions:
* append: The set of packages that are not in the constraints
but should be appended to the constraints.
"""
packaging_version = _import_packaging_version_or_raise()
if required_packages is None:
required_packages = _DEFAULT_REQUIRED_PACKAGES # type: ignore[assignment]
result = _RequirementsValidationResult(
warnings=_RequirementsValidationWarnings(missing=set(), incompatible=set()),
actions=_RequirementsValidationActions(append=set()),
)
if isinstance(constraints, list):
constraints = _parse_constraints(constraints=constraints)
for package, package_version in requirements.items():
if package not in constraints:
result[_WARNINGS_KEY][_WARNING_MISSING].add(package) # type: ignore[literal-required]
if package in required_packages: # type: ignore[operator]
result[_ACTIONS_KEY][_ACTION_APPEND].add( # type: ignore[literal-required]
f"{package}=={package_version}"
)
continue
if package_version:
package_specifier = constraints[package] # type: ignore[call-overload]
if not package_specifier:
continue
if packaging_version.Version(package_version) not in package_specifier:
result[_WARNINGS_KEY][_WARNING_INCOMPATIBLE].add( # type: ignore[literal-required]
f"{package}=={package_version} (required: {str(package_specifier)})"
)
return result
def _generate_class_methods_spec_or_raise(
*,
agent: _AgentEngineInterface,
operations: Dict[str, List[str]],
) -> List[proto.Message]:
"""Generates a ReasoningEngineSpec based on the registered operations.
Args:
agent: The AgentEngine instance.
operations: A dictionary of API modes and method names.
Returns:
A list of ReasoningEngineSpec.ClassMethod messages.
Raises:
ValueError: If a method defined in `register_operations` is not found on
the AgentEngine.
"""
if isinstance(agent, ModuleAgent):
# We do a dry-run of setting up the agent engine to have the operations
# needed for registration.
agent: ModuleAgent = agent.clone() # type: ignore[no-redef]
try:
agent.set_up()
except Exception as e:
raise ValueError(f"Failed to set up agent {agent}: {e}") from e
class_methods_spec = []
for mode, method_names in operations.items():
for method_name in method_names:
if not hasattr(agent, method_name):
raise ValueError(
f"Method `{method_name}` defined in `register_operations`"
" not found on agent."
)
method = getattr(agent, method_name)
try:
schema_dict = _generate_schema(method, schema_name=method_name)
except Exception as e:
logger.warning(f"failed to generate schema for {method_name}: {e}")
continue
class_method = _to_proto(schema_dict)
class_method[_MODE_KEY_IN_SCHEMA] = mode
if hasattr(agent, "agent_card"):
card = getattr(agent, "agent_card")
if hasattr(card, "model_dump_json"):
class_method[_A2A_AGENT_CARD] = card.model_dump_json()
elif hasattr(card, "DESCRIPTOR"):
class_method[_A2A_AGENT_CARD] = json_format.MessageToJson(card)
elif isinstance(card, str):
class_method[_A2A_AGENT_CARD] = card
else:
class_method[_A2A_AGENT_CARD] = json.dumps(card)
class_methods_spec.append(class_method)
return class_methods_spec
def _class_methods_to_class_methods_spec(
class_methods: List[dict[str, Any]],
) -> List[proto.Message]:
"""Converts a list of class methods to a list of ReasoningEngineSpec.ClassMethod messages."""
return [_to_proto(class_method) for class_method in class_methods]
def _is_pydantic_serializable(param: inspect.Parameter) -> bool:
"""Checks if the parameter is pydantic serializable."""
if param.annotation == inspect.Parameter.empty:
return True
if "ForwardRef" in repr(param.annotation):
return True
if isinstance(param.annotation, str):
return False
pydantic = _import_pydantic_or_raise()
try:
pydantic.TypeAdapter(param.annotation)
return True
except Exception:
return False
def _generate_schema(
f: Callable[..., Any],
*,
schema_name: Optional[str] = None,
descriptions: Mapping[str, str] = {},
required: Sequence[str] = [],
) -> Dict[str, Any]:
"""Generates the OpenAPI Schema for a callable object.
Only positional and keyword arguments of the function `f` will be supported
in the OpenAPI Schema that is generated. I.e. `*args` and `**kwargs` will
not be present in the OpenAPI schema returned from this function. For those
cases, you can either include it in the docstring for `f`, or modify the
OpenAPI schema returned from this function to include additional arguments.
Args:
f (Callable):
Required. The function to generate an OpenAPI Schema for.
schema_name (str):
Optional. The name for the OpenAPI schema. If unspecified, the name
of the Callable will be used.
descriptions (Mapping[str, str]):
Optional. A `{name: description}` mapping for annotating input
arguments of the function with user-provided descriptions. It
defaults to an empty dictionary (i.e. there will not be any
description for any of the inputs).
required (Sequence[str]):
Optional. For the user to specify the set of required arguments in
function calls to `f`. If specified, it will be automatically
inferred from `f`.
Returns:
dict[str, Any]: The OpenAPI Schema for the function `f` in JSON format.
"""
pydantic = _import_pydantic_or_raise()
defaults = dict(inspect.signature(f).parameters)
fields_dict = {
name: (
# 1. We infer the argument type here: use Any rather than None so
# it will not try to auto-infer the type based on the default value.
(
param.annotation
if param.annotation != inspect.Parameter.empty
and "ForwardRef" not in repr(param.annotation)
else Any
),
pydantic.Field(
# 2. We do not support default values for now.
# default=(
# param.default if param.default != inspect.Parameter.empty
# else None
# ),
# 3. We support user-provided descriptions.
description=descriptions.get(name, None),
),
)
for name, param in defaults.items()
# We do not support *args or **kwargs
if param.kind
in (
inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.KEYWORD_ONLY,
inspect.Parameter.POSITIONAL_ONLY,
)
# For a bidi endpoint, it requires an asyncio.Queue as the input, but
# it is not JSON serializable. We hence exclude it from the schema.
and param.annotation != asyncio.Queue and _is_pydantic_serializable(param)
}
parameters = pydantic.create_model(f.__name__, **fields_dict).schema()
# Postprocessing
# 4. Suppress unnecessary title generation:
# * https://github.com/pydantic/pydantic/issues/1051
# * http://cl/586221780
parameters.pop("title", "")
for name, function_arg in parameters.get("properties", {}).items():
function_arg.pop("title", "")
annotation = defaults[name].annotation
# 5. Nullable fields:
# * https://github.com/pydantic/pydantic/issues/1270
# * https://stackoverflow.com/a/58841311
# * https://github.com/pydantic/pydantic/discussions/4872
if typing.get_origin(annotation) is Union and type(None) in typing.get_args(
annotation
):
# for "typing.Optional" arguments, function_arg might be a
# dictionary like
#
# {'anyOf': [{'type': 'integer'}, {'type': 'null'}]
for schema in function_arg.pop("anyOf", []):
schema_type = schema.get("type")
if schema_type and schema_type != "null":
function_arg["type"] = schema_type
break
function_arg["nullable"] = True
# 6. Annotate required fields.
if required:
# We use the user-provided "required" fields if specified.
parameters["required"] = required
else:
# Otherwise we infer it from the function signature.
parameters["required"] = [
k
for k in defaults
if (
defaults[k].default == inspect.Parameter.empty
and defaults[k].kind
in (
inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.KEYWORD_ONLY,
inspect.Parameter.POSITIONAL_ONLY,
)
)
]
schema = dict(name=f.__name__, description=f.__doc__, parameters=parameters)
if schema_name:
schema["name"] = schema_name
return schema
def _get_agent_framework(
*,
agent_framework: Optional[str],
agent: _AgentEngineInterface,
) -> Union[str, Any]:
"""Gets the agent framework to use.
The agent framework is determined in the following order of priority:
1. The `agent_framework` passed to this function.
2. The `agent_framework` attribute on the `agent` object.
3. The default framework, "custom".
Args:
agent_framework (str):
The agent framework provided by the user.
agent (_AgentEngineInterface):
The agent engine instance.
Returns:
str: The name of the agent framework to use.
"""
if agent_framework is not None and agent_framework in _SUPPORTED_AGENT_FRAMEWORKS:
logger.info(f"Using agent framework: {agent_framework}")
return agent_framework
if hasattr(agent, _AGENT_FRAMEWORK_ATTR):
agent_framework_attr = getattr(agent, _AGENT_FRAMEWORK_ATTR)
if (
agent_framework_attr is not None
and isinstance(agent_framework_attr, str)
and agent_framework_attr in _SUPPORTED_AGENT_FRAMEWORKS
):
logger.info(f"Using agent framework: {agent_framework_attr}")
return agent_framework_attr
logger.info(
f"The provided agent framework {agent_framework} is not supported."
f" Defaulting to {_DEFAULT_AGENT_FRAMEWORK}."
)
return _DEFAULT_AGENT_FRAMEWORK
def _get_gcs_bucket(
*,
project: str,
location: str,
staging_bucket: str,
credentials: Optional[Any] = None,
) -> _StorageBucket:
"""Gets or creates the GCS bucket."""
storage = _import_cloud_storage_or_raise()
storage_client = storage.Client(project=project, credentials=credentials)
staging_bucket = staging_bucket.replace("gs://", "")
try:
gcs_bucket = storage_client.get_bucket(staging_bucket)
logger.info(f"Using bucket {staging_bucket}")
except exceptions.NotFound:
new_bucket = storage_client.bucket(staging_bucket)
gcs_bucket = storage_client.create_bucket(new_bucket, location=location)
logger.info(f"Creating bucket {staging_bucket} in {location=}")
return gcs_bucket
def _get_registered_operations(
*,
agent: _AgentEngineInterface,
) -> dict[str, list[str]]:
"""Retrieves registered operations for a AgentEngine."""
if isinstance(agent, OperationRegistrable):
return agent.register_operations()
operations = {}
if isinstance(agent, Queryable):
operations[_STANDARD_API_MODE] = [_DEFAULT_METHOD_NAME]
if isinstance(agent, AsyncQueryable):
operations[_ASYNC_API_MODE] = [_DEFAULT_ASYNC_METHOD_NAME]
if isinstance(agent, StreamQueryable):
operations[_STREAM_API_MODE] = [_DEFAULT_STREAM_METHOD_NAME]
if isinstance(agent, AsyncStreamQueryable):
operations[_ASYNC_STREAM_API_MODE] = [_DEFAULT_ASYNC_STREAM_METHOD_NAME]
if isinstance(agent, BidiStreamQueryable):
operations[_BIDI_STREAM_API_MODE] = [_DEFAULT_BIDI_STREAM_METHOD_NAME]
return operations
def _import_cloudpickle_or_raise() -> types.ModuleType:
"""Tries to import the cloudpickle module."""
try:
import cloudpickle # noqa:F401
except ImportError as e:
raise ImportError(
"cloudpickle is not installed. Please call "
"'pip install google-cloud-aiplatform[agent_engines]'."
) from e
return cloudpickle # type: ignore[no-any-return]
def _import_cloud_storage_or_raise() -> types.ModuleType:
"""Tries to import the Cloud Storage module."""
try:
from google.cloud import storage # type: ignore[attr-defined]
except ImportError as e:
raise ImportError(
"Cloud Storage is not installed. Please call "
"'pip install google-cloud-aiplatform[agent_engines]'."
) from e
return storage # type: ignore[no-any-return]
def _import_packaging_requirements_or_raise() -> types.ModuleType:
"""Tries to import the packaging.requirements module."""
try:
from packaging import requirements
except ImportError as e:
raise ImportError(
"packaging.requirements is not installed. Please call "
"'pip install google-cloud-aiplatform[agent_engines]'."
) from e
return requirements
def _import_packaging_version_or_raise() -> types.ModuleType:
"""Tries to import the packaging.requirements module."""
try:
from packaging import version
except ImportError as e:
raise ImportError(
"packaging.version is not installed. Please call "
"'pip install google-cloud-aiplatform[agent_engines]'."
) from e
return version
def _import_pydantic_or_raise() -> types.ModuleType:
"""Tries to import the pydantic module."""
try:
import pydantic
_ = pydantic.Field
except AttributeError:
from pydantic import v1 as pydantic # type: ignore[no-redef]
except ImportError as e:
raise ImportError(
"pydantic is not installed. Please call "
"'pip install google-cloud-aiplatform[agent_engines]'."
) from e
return pydantic
def _parse_constraints(
*,
constraints: Sequence[str],
) -> Mapping[str, Optional["_SpecifierSet"]]:
"""Parses a list of constraints into a dict of requirements.
Args:
constraints (list[str]):
Required. The list of package requirements to parse. This is assumed
to come from the `requirements.txt` file.
Returns:
dict[str, SpecifierSet]: The specifiers for each package.
"""
requirements = _import_packaging_requirements_or_raise()
result: Dict[str, Optional[_SpecifierSet]] = {}
for constraint in constraints:
try:
if constraint.endswith(".whl"):
constraint = os.path.basename(constraint)
requirement = requirements.Requirement(constraint)
except Exception as e:
logger.warning(f"Failed to parse constraint: {constraint}. Exception: {e}")
continue
result[requirement.name] = requirement.specifier or None
return result