8000 refactor: refactor openapi toolset and tool parser to hide non public… · DarioMR1/adk-python@9647426 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9647426

Browse files
seanzhougooglecopybara-github
authored andcommitted
refactor: refactor openapi toolset and tool parser to hide non public field
PiperOrigin-RevId: 758436303
1 parent 1f0fd7b commit 9647426

File tree

4 files changed

+87
-87
lines changed

4 files changed

+87
-87
lines changed

src/google/adk/tools/openapi_tool/openapi_spec_parser/openapi_toolset.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def __init__(
105105
"""
106106
if not spec_dict:
107107
spec_dict = self._load_spec(spec_str, spec_str_type)
108-
self.tools: Final[List[RestApiTool]] = list(self._parse(spec_dict))
108+
self._tools: Final[List[RestApiTool]] = list(self._parse(spec_dict))
109109
if auth_scheme or auth_credential:
110110
self._configure_auth_all(auth_scheme, auth_credential)
111111
self.tool_filter = tool_filter
@@ -115,7 +115,7 @@ def _configure_auth_all(
115115
):
116116
"""Configure auth scheme and credential for all tools."""
117117

118-
for tool in self.tools:
118+
for tool in self._tools:
119119
if auth_scheme:
120120
tool.configure_auth_scheme(auth_scheme)
121121
if auth_credential:
@@ -128,7 +128,7 @@ async def get_tools(
128128
"""Get all tools in the toolset."""
129129
return [
130130
tool
131-
for tool in self.tools
131+
for tool in self._tools
132132
if self.tool_filter is None
133133
or (
134134
self.tool_filter(tool, readonly_context)
@@ -139,7 +139,7 @@ async def get_tools(
139139

140140
def get_tool(self, tool_name: str) -> Optional[RestApiTool]:
141141
"""Get a tool by name."""
142-
matching_tool = filter(lambda t: t.name == tool_name, self.tools)
142+
matching_tool = filter(lambda t: t.name == tool_name, self._tools)
143143
return next(matching_tool, None)
144144

145145
def _load_spec(

src/google/adk/tools/openapi_tool/openapi_spec_parser/operation_parser.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,14 @@ def __init__(
4545
should_p 8000 arse: Whether to parse the operation during initialization.
4646
"""
4747
if isinstance(operation, dict):
48-
self.operation = Operation.model_validate(operation)
48+
self._operation = Operation.model_validate(operation)
4949
elif isinstance(operation, str):
50-
self.operation = Operation.model_validate_json(operation)
50+
self._operation = Operation.model_validate_json(operation)
5151
else:
52-
self.operation = operation
52+
self._operation = operation
5353

54-
self.params: List[ApiParameter] = []
55-
self.return_value: Optional[ApiParameter] = None
54+
self._params: List[ApiParameter] = []
55+
self._return_value: Optional[ApiParameter] = None
5656
if should_parse:
5757
self._process_operation_parameters()
5858
self._process_request_body()
@@ -67,13 +67,13 @@ def load(
6767
return_value: Optional[ApiParameter] = None,
6868
) -> 'OperationParser':
6969
parser = cls(operation, should_parse=False)
70-
parser.params = params
71-
parser.return_value = return_value
70+
parser._params = params
71+
parser._return_value = return_value
7272
return parser
7373

7474
def _process_operation_parameters(self):
7575
"""Processes parameters from the OpenAPI operation."""
76-
parameters = self.operation.parameters or []
76+
parameters = self._operation.parameters or []
7777
for param in parameters:
7878
if isinstance(param, Parameter):
7979
original_name = param.name
@@ -86,7 +86,7 @@ def _process_operation_parameters(self):
8686
# param.required can be None
8787
required = param.required if param.required is not None else False
8888

89-
self.params.append(
89+
self._params.append(
9090
ApiParameter(
9191
original_name=original_name,
9292
param_location=location,
@@ -98,7 +98,7 @@ def _process_operation_parameters(self):
9898

9999
def _process_request_body(self):
100100
"""Processes the request body from the OpenAPI operation."""
101-
request_body = self.operation.requestBody
101+
request_body = self._operation.requestBody
102102
if not request_body:
103103
return
104104

@@ -114,7 +114,7 @@ def _process_request_body(self):
114114
if schema and schema.type == 'object':
115115
properties = schema.properties or {}
116116
for prop_name, prop_details in properties.items():
117-
self.params.append(
117+
self._params.append(
118118
ApiParameter(
119119
original_name=prop_name,
120120
param_location='body',
@@ -124,7 +124,7 @@ def _process_request_body(self):
124124
)
125125

126126
elif schema and schema.type == 'array':
127-
self.params.append(
127+
self._params.append(
128128
ApiParameter(
129129
original_name='array',
130130
param_location='body',
@@ -133,7 +133,7 @@ def _process_request_body(self):
133133
)
134134
)
135135
else:
136-
self.params.append(
136+
self._params.append(
137137
# Empty name for unnamed body param
138138
ApiParameter(
139139
original_name='',
@@ -147,7 +147,7 @@ def _process_request_body(self):
147147
def _dedupe_param_names(self):
148148
"""Deduplicates parameter names to avoid conflicts."""
149149
params_cnt = {}
150-
for param in self.params:
150+
for param in self._params:
151151
name = param.py_name
152152
if name not in params_cnt:
153153
params_cnt[name] = 0
@@ -157,7 +157,7 @@ def _dedupe_param_names(self):
157157

158158
def _process_return_value(self) -> Parameter:
159159
"""Returns a Parameter object representing the return type."""
160-
responses = self.operation.responses or {}
160+
responses = self._operation.responses or {}
161161
# Default to Any if no 2xx response or if schema is missing
162162
return_schema = Schema(type='Any')
163163

@@ -174,50 +174,50 @@ def _process_return_value(self) -> Parameter:
174174
return_schema = content[mime_type].schema_
175175
break
176176

177-
self.return_value = ApiParameter(
177+
self._return_value = ApiParameter(
178178
original_name='',
179179
param_location='',
180180
param_schema=return_schema,
181181
)
182182

183183
def get_function_name(self) -> str:
184184
"""Returns the generated function name."""
185-
operation_id = self.operation.operationId
185+
operation_id = self._operation.operationId
186186
if not operation_id:
187187
raise ValueError('Operation ID is missing')
188188
return to_snake_case(operation_id)[:60]
189189

190190
def get_return_type_hint(self) -> str:
191191
"""Returns the return type hint string (like 'str', 'int', etc.)."""
192-
return self.return_value.type_hint
192+
return self._return_value.type_hint
193193

194194
def get_return_type_value(self) -> Any:
195195
"""Returns the return type value (like str, int, List[str], etc.)."""
196-
return self.return_value.type_value
196+
return self._return_value.type_value
197197

198198
def get_parameters(self) -> List[ApiParameter]:
199199
"""Returns the list of Parameter objects."""
200-
return self.params
200+
return self._params
201201

202202
def get_return_value(self) -> ApiParameter:
203203
"""Returns the list of Parameter objects."""
204-
return self.return_value
204+
return self._return_value
205205

206206
def get_auth_scheme_name(self) -> str:
207207
"""Returns the name of the auth scheme for this operation from the spec."""
208-
if self.operation.security:
209-
scheme_name = list(self.operation.security[0].keys())[0]
208+
if self._operation.security:
209+
scheme_name = list(self._operation.security[0].keys())[0]
210210
return scheme_name
211211
return ''
212212

213213
def get_pydoc_string(self) -> str:
214214
"""Returns the generated PyDoc string."""
215-
pydoc_params = [param.to_pydoc_string() for param in self.params]
215+
pydoc_params = [param.to_pydoc_string() for param in self._params]
216216
pydoc_description = (
217-
self.operation.summary or self.operation.description or ''
217+
self._operation.summary or self._operation.description or ''
218218
)
219219
pydoc_return = PydocHelper.generate_return_doc(
220-
self.operation.responses or {}
220+
self._operation.responses or {}
221221
)
222222
pydoc_arg_list = chr(10).join(
223223
f' {param_doc}' for param_doc in pydoc_params
@@ -236,12 +236,12 @@ def get_json_schema(self) -> Dict[str, Any]:
236236
"""Returns the JSON schema for the function arguments."""
237237
properties = {
238238
p.py_name: jsonable_encoder(p.param_schema, exclude_none=True)
239-
for p in self.params
239+
for p in self._params
240240
}
241241
return {
242242
'properties': properties,
243-
'required': [p.py_name for p in self.params if p.required],
244-
'title': f"{self.operation.operationId or 'unnamed'}_Arguments",
243+
'required': [p.py_name for p in self._params if p.required],
244+
'title': f"{self._operation.operationId or 'unnamed'}_Arguments",
245245
'type': 'object',
246246
}
247247

@@ -253,11 +253,11 @@ def get_signature_parameters(self) -> List[inspect.Parameter]:
253253
inspect.Parameter.POSITIONAL_OR_KEYWORD,
254254
annotation=param.type_value,
255255
)
256-
for param in self.params
256+
for param in self._params
257257
]
258258

259259
def get_annotations(self) -> Dict[str, Any]:
260260
"""Returns a dictionary of parameter annotations for the function."""
261-
annotations = {p.py_name: p.type_value for p in self.params}
261+
annotations = {p.py_name: p.type_value for p in self._params}
262262
annotations['return'] = self.get_return_type_value()
263263
return annotations

tests/unittests/tools/openapi_tool/openapi_spec_parser/test_openapi_toolset.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,18 +47,18 @@ def openapi_spec() -> Dict:
4747
def test_openapi_toolset_initialization_from_dict(openapi_spec: Dict):
4848
"""Test initialization of OpenAPIToolset with a dictionary."""
4949
toolset = OpenAPIToolset(spec_dict=openapi_spec)
50-
assert isinstance(toolset.tools, list)
51-
assert len(toolset.tools) == 5
52-
assert all(isinstance(tool, RestApiTool) for tool in toolset.tools)
50+
assert isinstance(toolset._tools, list)
51+
assert len(toolset._tools) == 5
52+
assert all(isinstance(tool, RestApiTool) for tool in toolset._tools)
5353

5454

5555
def test_openapi_toolset_initialization_from_yaml_string(openapi_spec: Dict):
5656
"""Test initialization of OpenAPIToolset with a YAML string."""
5757
spec_str = yaml.dump(openapi_spec)
5858
toolset = OpenAPIToolset(spec_str=spec_str, spec_str_type="yaml")
59-
assert isinstance(toolset.tools, list)
60-
assert len(toolset.tools) == 5
61-
assert all(isinstance(tool, RestApiTool) for tool in toolset.tools)
59+
assert isinstance(toolset._tools, list)
60+
assert len(toolset._tools) == 5
61+
assert all(isinstance(tool, RestApiTool) for tool in toolset._tools)
6262

6363

6464
def test_openapi_toolset_tool_existing(openapi_spec: Dict):
@@ -134,6 +134,6 @@ def test_openapi_toolset_configure_auth_on_init(openapi_spec: Dict):
134134
auth_scheme=auth_scheme,
135135
auth_credential=auth_credential,
136136
)
137-
for tool in toolset.tools:
137+
for tool in toolset._tools:
138138
assert tool.auth_scheme == auth_scheme
139139
assert tool.auth_credential == auth_credential

0 commit comments

Comments
 (0)
0