|
32 | 32 | from typing import ( |
33 | 33 | Any, |
34 | 34 | AsyncIterator, |
35 | | - Awaitable, |
36 | 35 | Callable, |
37 | 36 | Coroutine, |
38 | 37 | Dict, |
|
59 | 58 | from . import types as genai_types |
60 | 59 |
|
61 | 60 |
|
| 61 | +if sys.version_info >= (3, 10): |
| 62 | + from typing import TypeAlias |
| 63 | +else: |
| 64 | + from typing_extensions import TypeAlias |
| 65 | + |
| 66 | + |
62 | 67 | try: |
63 | 68 | _BUILTIN_MODULE_NAMES: Sequence[str] = sys.builtin_module_names |
64 | 69 | except AttributeError: |
|
78 | 83 | _STDLIB_MODULE_NAMES: frozenset[str] = frozenset() # type: ignore[no-redef] |
79 | 84 |
|
80 | 85 |
|
81 | | -try: |
82 | | - from google.cloud import storage |
| 86 | +if typing.TYPE_CHECKING: |
| 87 | + from google.cloud import storage # type: ignore[attr-defined] |
83 | 88 |
|
84 | | - _StorageBucket: type[Any] = storage.Bucket |
85 | | -except (ImportError, AttributeError): |
86 | | - _StorageBucket: type[Any] = Any # type: ignore[no-redef] |
| 89 | + _StorageBucket: TypeAlias = storage.Bucket |
| 90 | +else: |
| 91 | + try: |
| 92 | + from google.cloud import storage # type: ignore[attr-defined] |
87 | 93 |
|
| 94 | + _StorageBucket: type[Any] = storage.Bucket |
| 95 | + except (ImportError, AttributeError): |
| 96 | + _StorageBucket: type[Any] = Any # type: ignore[no-redef] |
88 | 97 |
|
89 | | -try: |
| 98 | + |
| 99 | +if typing.TYPE_CHECKING: |
90 | 100 | import packaging |
91 | 101 |
|
92 | | - _SpecifierSet: type[Any] = packaging.specifiers.SpecifierSet |
93 | | -except (ImportError, AttributeError): |
94 | | - _SpecifierSet: type[Any] = Any # type: ignore[no-redef] |
| 102 | + _SpecifierSet = packaging.specifiers.SpecifierSet |
| 103 | +else: |
| 104 | + try: |
| 105 | + import packaging |
| 106 | + |
| 107 | + _SpecifierSet: type[Any] = packaging.specifiers.SpecifierSet |
| 108 | + except (ImportError, AttributeError): |
| 109 | + _SpecifierSet: type[Any] = Any # type: ignore[no-redef] |
95 | 110 |
|
96 | 111 |
|
97 | 112 | try: |
@@ -258,16 +273,22 @@ class OperationRegistrable(Protocol): |
258 | 273 | """Protocol for agents that have registered operations.""" |
259 | 274 |
|
260 | 275 | @abc.abstractmethod |
261 | | - def register_operations(self, **kwargs) -> Dict[str, Sequence[str]]: # type: ignore[no-untyped-def] |
| 276 | + def register_operations(self, **kwargs: Any) -> dict[str, list[str]]: |
262 | 277 | """Register the user provided operations (modes and methods).""" |
| 278 | + pass |
263 | 279 |
|
264 | 280 |
|
265 | | -try: |
| 281 | +if typing.TYPE_CHECKING: |
266 | 282 | from google.adk.agents import BaseAgent |
267 | 283 |
|
268 | | - ADKAgent: type[Any] = BaseAgent |
269 | | -except (ImportError, AttributeError): |
270 | | - ADKAgent: type[Any] = Any # type: ignore[no-redef] |
| 284 | + ADKAgent: TypeAlias = BaseAgent |
| 285 | +else: |
| 286 | + try: |
| 287 | + from google.adk.agents import BaseAgent |
| 288 | + |
| 289 | + ADKAgent: Optional[TypeAlias] = BaseAgent |
| 290 | + except (ImportError, AttributeError): |
| 291 | + ADKAgent = None # type: ignore[no-redef] |
271 | 292 |
|
272 | 293 | _AgentEngineInterface = Union[ |
273 | 294 | ADKAgent, |
@@ -283,8 +304,9 @@ def register_operations(self, **kwargs) -> Dict[str, Sequence[str]]: # type: ig |
283 | 304 | class _ModuleAgentAttributes(TypedDict, total=False): |
284 | 305 | module_name: str |
285 | 306 | agent_name: str |
286 | | - register_operations: Dict[str, Sequence[str]] |
| 307 | + register_operations: Dict[str, list[str]] |
287 | 308 | sys_paths: Optional[Sequence[str]] |
| 309 | + agent: _AgentEngineInterface |
288 | 310 |
|
289 | 311 |
|
290 | 312 | class ModuleAgent(Cloneable, OperationRegistrable): |
@@ -300,7 +322,7 @@ def __init__( |
300 | 322 | *, |
301 | 323 | module_name: str, |
302 | 324 | agent_name: str, |
303 | | - register_operations: Dict[str, Sequence[str]], |
| 325 | + register_operations: Dict[str, list[str]], |
304 | 326 | sys_paths: Optional[Sequence[str]] = None, |
305 | 327 | ): |
306 | 328 | """Initializes a module-based agent. |
@@ -310,7 +332,7 @@ def __init__( |
310 | 332 | Required. The name of the module to import. |
311 | 333 | agent_name (str): |
312 | 334 | Required. The name of the agent in the module to instantiate. |
313 | | - register_operations (Dict[str, Sequence[str]]): |
| 335 | + register_operations (Dict[str, list[str]]): |
314 | 336 | Required. A dictionary of API modes to a list of method names. |
315 | 337 | sys_paths (Sequence[str]): |
316 | 338 | Optional. The system paths to search for the module. It should |
@@ -336,8 +358,11 @@ def clone(self) -> "ModuleAgent": |
336 | 358 | sys_paths=self._tmpl_attrs.get("sys_paths"), |
337 | 359 | ) |
338 | 360 |
|
339 | | - def register_operations(self) -> Dict[str, Sequence[str]]: |
340 | | - self._tmpl_attrs.get("register_operations") |
| 361 | + def register_operations(self, **kwargs: Any) -> dict[str, list[str]]: |
| 362 | + reg_operations = self._tmpl_attrs.get("register_operations") |
| 363 | + if reg_operations is None: |
| 364 | + raise ValueError("Register operations is not set.") |
| 365 | + return reg_operations |
341 | 366 |
|
342 | 367 | def set_up(self) -> None: |
343 | 368 | """Sets up the agent for execution of queries at runtime. |
@@ -411,7 +436,7 @@ def __call__( |
411 | 436 | class GetAsyncOperationFunction(Protocol): |
412 | 437 | async def __call__( |
413 | 438 | self, *, operation_name: str, **kwargs: Any |
414 | | - ) -> Awaitable[AgentEngineOperationUnion]: |
| 439 | + ) -> AgentEngineOperationUnion: |
415 | 440 | pass |
416 | 441 |
|
417 | 442 |
|
@@ -507,7 +532,7 @@ def _await_operation( |
507 | 532 | def _compare_requirements( |
508 | 533 | *, |
509 | 534 | requirements: Mapping[str, str], |
510 | | - constraints: Union[Sequence[str], Mapping[str, "_SpecifierSet"]], |
| 535 | + constraints: Union[Sequence[str], Mapping[str, Optional["_SpecifierSet"]]], |
511 | 536 | required_packages: Optional[Iterator[str]] = None, |
512 | 537 | ) -> _RequirementsValidationResult: |
513 | 538 | """Compares the requirements with the constraints. |
@@ -536,7 +561,7 @@ def _compare_requirements( |
536 | 561 | """ |
537 | 562 | packaging_version = _import_packaging_version_or_raise() |
538 | 563 | if required_packages is None: |
539 | | - required_packages = _DEFAULT_REQUIRED_PACKAGES |
| 564 | + required_packages = _DEFAULT_REQUIRED_PACKAGES # type: ignore[assignment] |
540 | 565 | result = _RequirementsValidationResult( |
541 | 566 | warnings=_RequirementsValidationWarnings(missing=set(), incompatible=set()), |
542 | 567 | actions=_RequirementsValidationActions(append=set()), |
@@ -583,7 +608,7 @@ def _generate_class_methods_spec_or_raise( |
583 | 608 | if isinstance(agent, ModuleAgent): |
584 | 609 | # We do a dry-run of setting up the agent engine to have the operations |
585 | 610 | # needed for registration. |
586 | | - agent: ModuleAgent = agent.clone() |
| 611 | + agent: ModuleAgent = agent.clone() # type: ignore[no-redef] |
587 | 612 | try: |
588 | 613 | agent.set_up() |
589 | 614 | except Exception as e: |
@@ -819,13 +844,13 @@ def _get_gcs_bucket( |
819 | 844 | new_bucket = storage_client.bucket(staging_bucket) |
820 | 845 | gcs_bucket = storage_client.create_bucket(new_bucket, location=location) |
821 | 846 | logger.info(f"Creating bucket {staging_bucket} in {location=}") |
822 | | - return gcs_bucket # type: ignore[no-any-return] |
| 847 | + return gcs_bucket |
823 | 848 |
|
824 | 849 |
|
825 | 850 | def _get_registered_operations( |
826 | 851 | *, |
827 | 852 | agent: _AgentEngineInterface, |
828 | | -) -> Dict[str, List[str]]: |
| 853 | +) -> dict[str, list[str]]: |
829 | 854 | """Retrieves registered operations for a AgentEngine.""" |
830 | 855 | if isinstance(agent, OperationRegistrable): |
831 | 856 | return agent.register_operations() |
@@ -859,13 +884,13 @@ def _import_cloudpickle_or_raise() -> types.ModuleType: |
859 | 884 | def _import_cloud_storage_or_raise() -> types.ModuleType: |
860 | 885 | """Tries to import the Cloud Storage module.""" |
861 | 886 | try: |
862 | | - from google.cloud import storage |
| 887 | + from google.cloud import storage # type: ignore[attr-defined] |
863 | 888 | except ImportError as e: |
864 | 889 | raise ImportError( |
865 | 890 | "Cloud Storage is not installed. Please call " |
866 | 891 | "'pip install google-cloud-aiplatform[agent_engines]'." |
867 | 892 | ) from e |
868 | | - return storage |
| 893 | + return storage # type: ignore[no-any-return] |
869 | 894 |
|
870 | 895 |
|
871 | 896 | def _import_packaging_requirements_or_raise() -> types.ModuleType: |
@@ -1202,7 +1227,7 @@ def _upload_agent_engine( |
1202 | 1227 | ) -> None: |
1203 | 1228 | """Uploads the agent engine to GCS.""" |
1204 | 1229 | cloudpickle = _import_cloudpickle_or_raise() |
1205 | | - blob = gcs_bucket.blob(f"{gcs_dir_name}/{_BLOB_FILENAME}") # type: ignore[attr-defined] |
| 1230 | + blob = gcs_bucket.blob(f"{gcs_dir_name}/{_BLOB_FILENAME}") |
1206 | 1231 | with blob.open("wb") as f: |
1207 | 1232 | try: |
1208 | 1233 | cloudpickle.dump(agent, f) |
@@ -1216,7 +1241,7 @@ def _upload_agent_engine( |
1216 | 1241 | _ = cloudpickle.load(f) |
1217 | 1242 | except Exception as e: |
1218 | 1243 | raise TypeError("Agent engine serialized to an invalid format") from e |
1219 | | - dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}" # type: ignore[attr-defined] |
| 1244 | + dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}" |
1220 | 1245 | logger.info(f"Wrote to {dir_name}/{_BLOB_FILENAME}") |
1221 | 1246 |
|
1222 | 1247 |
|
@@ -1227,9 +1252,9 @@ def _upload_requirements( |
1227 | 1252 | gcs_dir_name: str, |
1228 | 1253 | ) -> None: |
1229 | 1254 | """Uploads the requirements file to GCS.""" |
1230 | | - blob = gcs_bucket.blob(f"{gcs_dir_name}/{_REQUIREMENTS_FILE}") # type: ignore[attr-defined] |
| 1255 | + blob = gcs_bucket.blob(f"{gcs_dir_name}/{_REQUIREMENTS_FILE}") |
1231 | 1256 | blob.upload_from_string("\n".join(requirements)) |
1232 | | - dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}" # type: ignore[attr-defined] |
| 1257 | + dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}" |
1233 | 1258 | logger.info(f"Writing to {dir_name}/{_REQUIREMENTS_FILE}") |
1234 | 1259 |
|
1235 | 1260 |
|
@@ -1246,9 +1271,9 @@ def _upload_extra_packages( |
1246 | 1271 | for file in extra_packages: |
1247 | 1272 | tar.add(file) |
1248 | 1273 | tar_fileobj.seek(0) |
1249 | | - blob = gcs_bucket.blob(f"{gcs_dir_name}/{_EXTRA_PACKAGES_FILE}") # type: ignore[attr-defined] |
| 1274 | + blob = gcs_bucket.blob(f"{gcs_dir_name}/{_EXTRA_PACKAGES_FILE}") |
1250 | 1275 | blob.upload_from_string(tar_fileobj.read()) |
1251 | | - dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}" # type: ignore[attr-defined] |
| 1276 | + dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}" |
1252 | 1277 | logger.info(f"Writing to {dir_name}/{_EXTRA_PACKAGES_FILE}") |
1253 | 1278 |
|
1254 | 1279 |
|
@@ -1369,7 +1394,7 @@ def _validate_requirements_or_warn( |
1369 | 1394 | *, |
1370 | 1395 | obj: Any, |
1371 | 1396 | requirements: List[str], |
1372 | | -) -> Mapping[str, str]: |
| 1397 | +) -> List[str]: |
1373 | 1398 | """Compiles the requirements into a list of requirements.""" |
1374 | 1399 | requirements = requirements.copy() |
1375 | 1400 | try: |
@@ -1380,16 +1405,14 @@ def _validate_requirements_or_warn( |
1380 | 1405 | requirements=current_requirements, |
1381 | 1406 | constraints=constraints, |
1382 | 1407 | ) |
1383 | | - for warning_type, warnings in missing_requirements.get( |
1384 | | - _WARNINGS_KEY, {} |
1385 | | - ).items(): |
| 1408 | + for warning_type, warnings in missing_requirements["warnings"].items(): |
1386 | 1409 | if warnings: |
1387 | 1410 | logger.warning( |
1388 | 1411 | f"The following requirements are {warning_type}: {warnings}" |
1389 | 1412 | ) |
1390 | | - for action_type, actions in missing_requirements.get(_ACTIONS_KEY, {}).items(): |
| 1413 | + for action_type, actions in missing_requirements["actions"].items(): |
1391 | 1414 | if actions and action_type == _ACTION_APPEND: |
1392 | | - for action in actions: |
| 1415 | + for action in actions: # type: ignore[attr-defined] |
1393 | 1416 | requirements.append(action) |
1394 | 1417 | logger.info(f"The following requirements are appended: {actions}") |
1395 | 1418 | except Exception as e: |
@@ -1413,7 +1436,7 @@ def _validate_requirements_or_raise( |
1413 | 1436 | logger.info(f"Read the following lines: {requirements}") |
1414 | 1437 | except IOError as err: |
1415 | 1438 | raise IOError(f"Failed to read requirements from {requirements=}") from err |
1416 | | - requirements = _validate_requirements_or_warn( # type: ignore[assignment] |
| 1439 | + requirements = _validate_requirements_or_warn( |
1417 | 1440 | obj=agent, |
1418 | 1441 | requirements=requirements, |
1419 | 1442 | ) |
@@ -1560,19 +1583,6 @@ def _method(self, **kwargs) -> Any: # type: ignore[no-untyped-def] |
1560 | 1583 | return _method |
1561 | 1584 |
|
1562 | 1585 |
|
1563 | | -AgentEngineOperationUnion = Union[ |
1564 | | - genai_types.AgentEngineOperation, |
1565 | | - genai_types.AgentEngineMemoryOperation, |
1566 | | - genai_types.AgentEngineGenerateMemoriesOperation, |
1567 | | -] |
1568 | | - |
1569 | | - |
1570 | | -class GetOperationFunction(Protocol): |
1571 | | - def __call__( # noqa: E704 |
1572 | | - self, *, operation_name: str, **kwargs: Any |
1573 | | - ) -> AgentEngineOperationUnion: ... |
1574 | | - |
1575 | | - |
1576 | 1586 | def _wrap_query_operation(*, method_name: str) -> Callable[..., Any]: |
1577 | 1587 | """Wraps an Agent Engine method, creating a callable for `query` API. |
1578 | 1588 |
|
@@ -1835,7 +1845,7 @@ async def _method(self, **kwargs) -> Any: # type: ignore[no-untyped-def] |
1835 | 1845 |
|
1836 | 1846 | return response |
1837 | 1847 |
|
1838 | | - return _method |
| 1848 | + return _method # type: ignore[return-value] |
1839 | 1849 |
|
1840 | 1850 |
|
1841 | 1851 | def _yield_parsed_json(http_response: google_genai_types.HttpResponse) -> Iterator[Any]: |
|