Skip to content

Commit 0c733ac

Browse files
GWealecopybara-github
authored andcommitted
chore: fix mypy strict type errors in adk tools
Co-authored-by: George Weale <gweale@google.com> PiperOrigin-RevId: 944705634
1 parent 6af5271 commit 0c733ac

20 files changed

Lines changed: 137 additions & 113 deletions

src/google/adk/tools/_automatic_function_calling_util.py

Lines changed: 47 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@
5959
}
6060

6161

62-
def _get_fields_dict(func: Callable) -> Dict:
62+
def _get_fields_dict(func: Callable[..., Any]) -> Dict[str, Any]:
6363
param_signature = dict(inspect.signature(func).parameters)
6464
fields_dict = {
6565
name: (
@@ -94,7 +94,7 @@ def _get_fields_dict(func: Callable) -> Dict:
9494
return fields_dict
9595

9696

97-
def _annotate_nullable_fields(schema: Dict):
97+
def _annotate_nullable_fields(schema: Dict[str, Any]) -> None:
9898
for _, property_schema in schema.get('properties', {}).items():
9999
# for Optional[T], the pydantic schema is:
100100
# {
@@ -117,7 +117,7 @@ def _annotate_nullable_fields(schema: Dict):
117117
break
118118

119119

120-
def _annotate_required_fields(schema: Dict):
120+
def _annotate_required_fields(schema: Dict[str, Any]) -> None:
121121
required = [
122122
field_name
123123
for field_name, field_schema in schema.get('properties', {}).items()
@@ -126,7 +126,7 @@ def _annotate_required_fields(schema: Dict):
126126
schema['required'] = required
127127

128128

129-
def _remove_any_of(schema: Dict):
129+
def _remove_any_of(schema: Dict[str, Any]) -> None:
130130
for _, property_schema in schema.get('properties', {}).items():
131131
union_types = property_schema.pop('anyOf', None)
132132
# Take the first non-null type.
@@ -136,17 +136,17 @@ def _remove_any_of(schema: Dict):
136136
property_schema.update(type_)
137137

138138

139-
def _remove_default(schema: Dict):
139+
def _remove_default(schema: Dict[str, Any]) -> None:
140140
for _, property_schema in schema.get('properties', {}).items():
141141
property_schema.pop('default', None)
142142

143143

144-
def _remove_nullable(schema: Dict):
144+
def _remove_nullable(schema: Dict[str, Any]) -> None:
145145
for _, property_schema in schema.get('properties', {}).items():
146146
property_schema.pop('nullable', None)
147147

148148

149-
def _remove_title(schema: Dict):
149+
def _remove_title(schema: Dict[str, Any]) -> None:
150150
for _, property_schema in schema.get('properties', {}).items():
151151
property_schema.pop('title', None)
152152

@@ -162,7 +162,9 @@ def _get_pydantic_schema(func: Callable) -> Dict:
162162
return pydantic.create_model(func.__name__, **fields_dict).model_json_schema()
163163

164164

165-
def _process_pydantic_schema(vertexai: bool, schema: Dict) -> Dict:
165+
def _process_pydantic_schema(
166+
vertexai: bool, schema: Dict[str, Any]
167+
) -> Dict[str, Any]:
166168
_annotate_nullable_fields(schema)
167169
_annotate_required_fields(schema)
168170
if not vertexai:
@@ -173,7 +175,9 @@ def _process_pydantic_schema(vertexai: bool, schema: Dict) -> Dict:
173175
return schema
174176

175177

176-
def _map_pydantic_type_to_property_schema(property_schema: Dict):
178+
def _map_pydantic_type_to_property_schema(
179+
property_schema: Dict[str, Any],
180+
) -> None:
177181
if 'type' in property_schema:
178182
property_schema['type'] = _py_type_2_schema_type.get(
179183
property_schema['type'], 'TYPE_UNSPECIFIED'
@@ -190,20 +194,20 @@ def _map_pydantic_type_to_property_schema(property_schema: Dict):
190194
property_schema['type'] = type_['type']
191195

192196

193-
def _map_pydantic_type_to_schema_type(schema: Dict):
197+
def _map_pydantic_type_to_schema_type(schema: Dict[str, Any]) -> None:
194198
for _, property_schema in schema.get('properties', {}).items():
195199
_map_pydantic_type_to_property_schema(property_schema)
196200

197201

198-
def _get_return_type(func: Callable) -> Any:
202+
def _get_return_type(func: Callable[..., Any]) -> Any:
199203
return _py_type_2_schema_type.get(
200204
inspect.signature(func).return_annotation.__name__,
201205
inspect.signature(func).return_annotation.__name__,
202206
)
203207

204208

205209
def build_function_declaration(
206-
func: Union[Callable, BaseModel],
210+
func: Union[Callable[..., Any], BaseModel],
207211
ignore_params: Optional[list[str]] = None,
208212
variant: GoogleLLMVariant = GoogleLLMVariant.GEMINI_API,
209213
) -> types.FunctionDeclaration:
@@ -222,45 +226,41 @@ def build_function_declaration(
222226

223227
# ========== ADK defined function tool declaration (old behavior) ==========
224228
signature = inspect.signature(func)
225-
should_update_signature = False
226-
new_func = None
227229
if not ignore_params:
228230
ignore_params = []
229-
for name, _ in signature.parameters.items():
230-
if name in ignore_params:
231-
should_update_signature = True
232-
break
233-
if should_update_signature:
234-
new_params = [
235-
param
231+
should_update_signature = any(
232+
name in ignore_params for name in signature.parameters
233+
)
234+
if not should_update_signature:
235+
return from_function_with_options(func, variant)
236+
237+
if isinstance(func, type):
238+
fields = {
239+
name: (param.annotation, param.default)
236240
for name, param in signature.parameters.items()
237241
if name not in ignore_params
238-
]
239-
if isinstance(func, type):
240-
fields = {
241-
name: (param.annotation, param.default)
242-
for name, param in signature.parameters.items()
243-
if name not in ignore_params
244-
}
245-
new_func = create_model(func.__name__, **fields)
246-
else:
247-
new_sig = signature.replace(parameters=new_params)
248-
new_func = FunctionType(
249-
func.__code__,
250-
func.__globals__,
251-
func.__name__,
252-
func.__defaults__,
253-
func.__closure__,
254-
)
255-
new_func.__signature__ = new_sig
256-
new_func.__doc__ = func.__doc__
257-
new_func.__annotations__ = func.__annotations__
258-
259-
return (
260-
from_function_with_options(func, variant)
261-
if not should_update_signature
262-
else from_function_with_options(new_func, variant)
242+
}
243+
return from_function_with_options(
244+
create_model(func.__name__, **fields), variant
245+
)
246+
247+
new_params = [
248+
param
249+
for name, param in signature.parameters.items()
250+
if name not in ignore_params
251+
]
252+
new_sig = signature.replace(parameters=new_params)
253+
new_func = FunctionType(
254+
func.__code__,
255+
func.__globals__,
256+
func.__name__,
257+
func.__defaults__,
258+
func.__closure__,
263259
)
260+
setattr(new_func, '__signature__', new_sig)
261+
new_func.__doc__ = func.__doc__
262+
new_func.__annotations__ = func.__annotations__
263+
return from_function_with_options(new_func, variant)
264264

265265

266266
def build_function_declaration_for_langchain(
@@ -316,7 +316,7 @@ def build_function_declaration_util(
316316

317317

318318
def from_function_with_options(
319-
func: Callable,
319+
func: Callable[..., Any],
320320
variant: GoogleLLMVariant = GoogleLLMVariant.GEMINI_API,
321321
) -> 'types.FunctionDeclaration':
322322

src/google/adk/tools/_function_parameter_parse_util.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def _raise_for_unsupported_param(
151151
) from exception
152152

153153

154-
def _raise_for_invalid_enum_value(param: inspect.Parameter):
154+
def _raise_for_invalid_enum_value(param: inspect.Parameter) -> None:
155155
"""Raises an error if the default value is not a valid enum value."""
156156
if inspect.isclass(param.annotation) and issubclass(param.annotation, Enum):
157157
if param.default is not inspect.Parameter.empty and param.default not in [
@@ -193,14 +193,14 @@ def _is_builtin_primitive_or_compound(
193193
return annotation in _py_builtin_type_to_schema_type.keys()
194194

195195

196-
def _raise_for_any_of_if_mldev(schema: types.Schema):
196+
def _raise_for_any_of_if_mldev(schema: types.Schema) -> None:
197197
if schema.any_of:
198198
raise ValueError(
199199
'AnyOf is not supported in function declaration schema for Google AI.'
200200
)
201201

202202

203-
def _update_for_default_if_mldev(schema: types.Schema):
203+
def _update_for_default_if_mldev(schema: types.Schema) -> None:
204204
if schema.default is not None:
205205
# TODO: Remove this workaround once mldev supports default value.
206206
schema.default = None
@@ -212,7 +212,7 @@ def _update_for_default_if_mldev(schema: types.Schema):
212212

213213
def _raise_if_schema_unsupported(
214214
variant: GoogleLLMVariant, schema: types.Schema
215-
):
215+
) -> None:
216216
if variant == GoogleLLMVariant.GEMINI_API:
217217
_raise_for_any_of_if_mldev(schema)
218218
# _update_for_default_if_mldev(schema) # No need of this since GEMINI now supports default value

src/google/adk/tools/bigtable/metadata_tool.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import enum
1818
import logging
19+
from typing import Any
1920

2021
from google.auth.credentials import Credentials
2122
from google.cloud.bigtable import enums
@@ -25,7 +26,7 @@
2526
logger = logging.getLogger(f"google_adk.{__name__}")
2627

2728

28-
def list_instances(project_id: str, credentials: Credentials) -> dict:
29+
def list_instances(project_id: str, credentials: Credentials) -> dict[str, Any]:
2930
"""List Bigtable instance ids in a Google Cloud project.
3031
3132
Args:
@@ -86,7 +87,7 @@ def list_instances(project_id: str, credentials: Credentials) -> dict:
8687

8788
def get_instance_info(
8889
project_id: str, instance_id: str, credentials: Credentials
89-
) -> dict:
90+
) -> dict[str, Any]:
9091
"""Get metadata information about a Bigtable instance.
9192
9293
Args:
@@ -128,7 +129,7 @@ def get_instance_info(
128129

129130
def list_tables(
130131
project_id: str, instance_id: str, credentials: Credentials
131-
) -> dict:
132+
) -> dict[str, Any]:
132133
"""List tables and their metadata in a Bigtable instance.
133134
134135
Args:
@@ -182,7 +183,7 @@ def get_table_info(
182183
instance_id: str,
183184
table_id: str,
184185
credentials: Credentials,
185-
) -> dict:
186+
) -> dict[str, Any]:
186187
"""Get metadata information about a Bigtable table.
187188
188189
Args:
@@ -241,7 +242,7 @@ def _enum_name_from_value(
241242

242243
def list_clusters(
243244
project_id: str, instance_id: str, credentials: Credentials
244-
) -> dict:
245+
) -> dict[str, Any]:
245246
"""List clusters and their metadata in a Bigtable instance.
246247
247248
Args:
@@ -315,7 +316,7 @@ def get_cluster_info(
315316
instance_id: str,
316317
cluster_id: str,
317318
credentials: Credentials,
318-
) -> dict:
319+
) -> dict[str, Any]:
319320
"""Get detailed metadata information about a Bigtable cluster.
320321
321322
Args:

src/google/adk/tools/bigtable/query_tool.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ async def execute_sql(
4343
parameters: Dict[str, Any] | None = None,
4444
parameter_types: Dict[str, Any] | None = None,
4545
_view_parameters: Dict[str, Any] | None = None,
46-
) -> dict:
46+
) -> Dict[str, Any]:
4747
"""Execute a GoogleSQL query from a Bigtable table.
4848
4949
Args:
@@ -83,7 +83,7 @@ async def execute_sql(
8383
"""
8484
del tool_context # Unused for now
8585

86-
def _execute_sql():
86+
def _execute_sql() -> Dict[str, Any]:
8787
try:
8888
bt_client = client.get_bigtable_data_client(
8989
project=project_id, credentials=credentials
@@ -122,7 +122,7 @@ def _execute_sql():
122122
finally:
123123
eqi.close()
124124

125-
result = {"status": "SUCCESS", "rows": rows}
125+
result: Dict[str, Any] = {"status": "SUCCESS", "rows": rows}
126126
if truncated:
127127
result["result_is_likely_truncated"] = True
128128
return result

src/google/adk/tools/enterprise_search_tool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ class EnterpriseWebSearchTool(BaseTool):
4141
4242
"""
4343

44-
def __init__(self):
44+
def __init__(self) -> None:
4545
"""Initializes the Enterprise Web Search tool."""
4646
# Name and description are not used because this is a model built-in tool.
4747
super().__init__(

src/google/adk/tools/exit_loop_tool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .tool_context import ToolContext
1818

1919

20-
def exit_loop(tool_context: ToolContext):
20+
def exit_loop(tool_context: ToolContext) -> None:
2121
"""Exits the loop.
2222
2323
Call this function only when you are instructed to do so.

src/google/adk/tools/google_api_tool/google_api_toolset.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,9 @@ async def get_tools(
118118
if self._is_tool_selected(tool, readonly_context)
119119
]
120120

121-
def set_tool_filter(self, tool_filter: Union[ToolPredicate, List[str]]):
121+
def set_tool_filter(
122+
self, tool_filter: Union[ToolPredicate, List[str]]
123+
) -> None:
122124
self.tool_filter = tool_filter
123125

124126
def _load_toolset_with_oidc_auth(self) -> OpenAPIToolset:
@@ -158,15 +160,15 @@ def _load_toolset_with_oidc_auth(self) -> OpenAPIToolset:
158160
httpx_client_factory=self._httpx_client_factory,
159161
)
160162

161-
def configure_auth(self, client_id: str, client_secret: str):
163+
def configure_auth(self, client_id: str, client_secret: str) -> None:
162164
self._client_id = client_id
163165
self._client_secret = client_secret
164166

165-
def configure_sa_auth(self, service_account: ServiceAccount):
167+
def configure_sa_auth(self, service_account: ServiceAccount) -> None:
166168
self._service_account = service_account
167169

168170
@override
169-
async def close(self):
171+
async def close(self) -> None:
170172
if self._openapi_toolset:
171173
await self._openapi_toolset.close()
172174
if hasattr(self, '_mtls_certs') and self._mtls_certs:

src/google/adk/tools/google_maps_grounding_tool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ class GoogleMapsGroundingTool(BaseTool):
3939
GOOGLE_GENAI_USE_ENTERPRISE=TRUE)
4040
"""
4141

42-
def __init__(self):
42+
def __init__(self) -> None:
4343
# Name and description are not used because this is a model built-in tool.
4444
super().__init__(name='google_maps', description='google_maps')
4545

src/google/adk/tools/load_mcp_resource_tool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ async def process_llm_request(
106106

107107
async def _append_resources_to_llm_request(
108108
self, *, tool_context: ToolContext, llm_request: LlmRequest
109-
):
109+
) -> None:
110110
try:
111111
resource_names = await self._mcp_toolset.list_resources()
112112
if resource_names:

src/google/adk/tools/load_memory_tool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ class LoadMemoryTool(FunctionTool):
5656
NOTE: Currently this tool only uses text part from the memory.
5757
"""
5858

59-
def __init__(self):
59+
def __init__(self) -> None:
6060
super().__init__(load_memory)
6161

6262
@override

0 commit comments

Comments
 (0)