8000 refactor: refactor google api toolset to hide non-public field · Syntax404-coder/adk-python@00e0035 · GitHub
[go: up one dir, main page]

Skip to content

Commit 00e0035

Browse files
seanzhougooglecopybara-github
authored andcommitted
refactor: refactor google api toolset to hide non-public field
PiperOrigin-RevId: 758469484
1 parent 30947b4 commit 00e0035

File tree

4 files changed

+69
-65
lines changed

4 files changed

+69
-65
lines changed

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,22 @@ def __init__(self, rest_api_tool: RestApiTool):
3535
description=rest_api_tool.description,
3636
is_long_running=rest_api_tool.is_long_running,
3737
)
38-
self.rest_api_tool = rest_api_tool
38+
self._rest_api_tool = rest_api_tool
3939

4040
@override
4141
def _get_declaration(self) -> FunctionDeclaration:
42-
return self.rest_api_tool._get_declaration()
42+
return self._rest_api_tool._get_declaration()
4343

4444
@override
4545
async def run_async(
4646
self, *, args: dict[str, Any], tool_context: Optional[ToolContext]
4747
) -> Dict[str, Any]:
48-
return await self.rest_api_tool.run_async(
48+
return await self._rest_api_tool.run_async(
4949
args=args, too 8000 l_context=tool_context
5050
)
5151

5252
def configure_auth(self, client_id: str, client_secret: str):
53-
self.rest_api_tool.auth_credential = AuthCredential(
53+
self._rest_api_tool.auth_credential = AuthCredential(
5454
auth_type=AuthCredentialTypes.OPEN_ID_CONNECT,
5555
oauth2=OAuth2Auth(
5656
client_id=client_id,

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

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,10 @@ def __init__(
4848
client_secret: Optional[str] = None,
4949
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
5050
):
51-
self.openapi_toolset = openapi_toolset
51+
self._openapi_toolset = openapi_toolset
5252
self.tool_filter = tool_filter
53-
self.client_id = client_id
54-
self.client_secret = client_secret
53+
self._client_id = client_id
54+
self._client_secret = client_secret
5555

5656
@override
5757
async def get_tools(
@@ -60,7 +60,7 @@ async def get_tools(
6060
"""Get all tools in the toolset."""
6161
tools = []
6262

63-
for tool in await self.openapi_toolset.get_tools(readonly_context):
63+
for tool in await self._openapi_toolset.get_tools(readonly_context):
6464
if self.tool_filter and (
6565
isinstance(self.tool_filter, ToolPredicate)
6666
and not self.tool_filter(tool, readonly_context)
@@ -69,7 +69,7 @@ async def get_tools(
6969
):
7070
continue
7171
google_api_tool = GoogleApiTool(tool)
72-
google_api_tool.configure_auth(self.client_id, self.client_secret)
72+
google_api_tool.configure_auth(self._client_id, self._client_secret)
7373
tools.append(google_api_tool)
7474

7575
return tools
@@ -119,8 +119,8 @@ def _load_toolset_with_oidc_auth(
119119
return toolset
120120

121121
def configure_auth(self, client_id: str, client_secret: str):
122-
self.client_id = client_id
123-
self.client_secret = client_secret
122+
self._client_id = client_id
123+
self._client_secret = client_secret
124124

125125
@classmethod
126126
def load_toolset(
@@ -140,5 +140,5 @@ def load_toolset(
140140

141141
@override
142142
async def close(self):
143-
if self.openapi_toolset:
144-
await self.openapi_toolset.close()
143+
if self._openapi_toolset:
144+
await self._openapi_toolset.close()

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

Lines changed: 39 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ def __init__(self, api_name: str, api_version: str):
3737
api_name: The name of the Google API (e.g., "calendar")
3838
api_version: The version of the API (e.g., "v3")
3939
"""
40-
self.api_name = api_name
41-
self.api_version = api_version
42-
self.google_api_resource = None
43-
self.google_api_spec = None
44-
self.openapi_spec = {
40+
self._api_name = api_name
41+
self._api_version = api_version
42+
self._google_api_resource = None
43+
self._google_api_spec = None
44+
self._openapi_spec = {
4545
"openapi": "3.0.0",
4646
"info": {},
4747
"servers": [],
@@ -53,18 +53,20 @@ def fetch_google_api_spec(self) -> None:
5353
"""Fetches the Google API specification using discovery service."""
5454
try:
5555
logger.info(
56-
"Fetching Google API spec for %s %s", self.api_name, self.api_version
56+
"Fetching Google API spec for %s %s",
57+
self._api_name,
58+
self._api_version,
5759
)
5860
# Build a resource object for the specified API
59-
self.google_api_resource = build(self.api_name, self.api_version)
61+
self._google_api_resource = build(self._api_name, self._api_version)
6062

6163
# Access the underlying API discovery document
62-
self.google_api_spec = self.google_api_resource._rootDesc
64+
self._google_api_spec = self._google_api_resource._rootDesc
6365

64-
if not self.google_api_spec:
66+
if not self._google_api_spec:
6567
raise ValueError("Failed to retrieve API specification")
6668

67-
logger.info("Successfully fetched %s API specification", self.api_name)
69+
logger.info("Successfully fetched %s API specification", self._api_name)
6870
except HttpError as e:
6971
logger.error("HTTP Error: %s", e)
7072
raise
@@ -78,7 +80,7 @@ def convert(self) -> Dict[str, Any]:
7880
Returns:
7981
Dict containing the converted OpenAPI v3 specification
8082
"""
81-
if not self.google_api_spec:
83+
if not self._google_api_spec:
8284
self.fetch_google_api_spec()
8385

8486
# Convert basic API information
@@ -94,49 +96,49 @@ def convert(self) -> Dict[str, Any]:
9496
self._convert_schemas()
9597

9698
# Convert endpoints/paths
97-
self._convert_resources(self.google_api_spec.get("resources", {}))
99+
self._convert_resources(self._google_api_spec.get("resources", {}))
98100

99101
# Convert top-level methods, if any
100-
self._convert_methods(self.google_api_spec.get("methods", {}), "/")
102+
self._convert_methods(self._google_api_spec.get("methods", {}), "/")
101103

102-
return self.openapi_spec
104+
return self._openapi_spec
103105

104106
def _convert_info(self) -> None:
105107
"""Convert basic API information."""
106-
self.openapi_spec["info"] = {
107-
"title": self.google_api_spec.get("title", f"{self.api_name} API"),
108-
"description": self.google_api_spec.get("description", ""),
109-
"version": self.google_api_spec.get("version", self.api_version),
108+
self._openapi_spec["info"] = {
109+
"title": self._google_api_spec.get("title", f"{self._api_name} API"),
110+
"description": self._google_api_spec.get("description", ""),
111+
"version": self._google_api_spec.get("version", self._api_version),
110112
"contact": {},
111-
"termsOfService": self.google_api_spec.get("documentationLink", ""),
113+
"termsOfService": self._google_api_spec.get("documentationLink", ""),
112114
}
113115

114116
# Add documentation links if available
115-
docs_link = self.google_api_spec.get("documentationLink")
117+
docs_link = self._google_api_spec.get("documentationLink")
116118
if docs_link:
117-
self.openapi_spec["externalDocs"] = {
119+
self._openapi_spec["externalDocs"] = {
118120
"description": "API Documentation",
119121
"url": docs_link,
120122
}
121123

122124
def _convert_servers(self) -> None:
123125
"""Convert server information."""
124-
base_url = self.google_api_spec.get(
126+
base_url = self._google_api_spec.get(
125127
"rootUrl", ""
126-
) + self.google_api_spec.get("servicePath", "")
128+
) + self._google_api_spec.get("servicePath", "")
127129

128130
# Remove trailing slash if present
129131
if base_url.endswith("/"):
130132
base_url = base_url[:-1]
131133

132-
self.openapi_spec["servers"] = [{
134+
self._openapi_spec["servers"] = [{
133135
"url": base_url,
134-
"description": f"{self.api_name} {self.api_version} API",
136+
"description": f"{self._api_name} {self._api_version} API",
135137
}]
136138

137139
def _convert_security_schemes(self) -> None:
138140
"""Convert authentication and authorization schemes."""
139-
auth = self.google_api_spec.get("auth", {})
141+
auth = self._google_api_spec.get("auth", {})
140142
oauth2 = auth.get("oauth2", {})
141143

142144
if oauth2:
@@ -147,7 +149,7 @@ def _convert_security_schemes(self) -> None:
147149
for scope, scope_info in scopes.items():
148150
formatted_scopes[scope] = scope_info.get("description", "")
149151

150-
self.openapi_spec["components"]["securitySchemes"]["oauth2"] = {
152+
self._openapi_spec["components"]["securitySchemes"]["oauth2"] = {
151153
"type": "oauth2",
152154
"description": "OAuth 2.0 authentication",
153155
"flows": {
@@ -162,26 +164,28 @@ def _convert_security_schemes(self) -> None:
162164
}
163165

164166
# Add API key authentication (most Google APIs support this)
165-
self.openapi_spec["components"]["securitySchemes"]["apiKey"] = {
167+
self._openapi_spec["components"]["securitySchemes"]["apiKey"] = {
166168
"type": "apiKey",
167169
"in": "query",
168170
"name": "key",
169171
"description": "API key for accessing this API",
170172
}
171173

172174
# Create global security requirement
173-
self.openapi_spec["security"] = [
175+
self._openapi_spec["security"] = [
174176
{"oauth2": list(formatted_scopes.keys())} if oauth2 else {},
175177
{"apiKey": []},
176178
]
177179

178180
def _convert_schemas(self) -> None:
179181
"""Convert schema definitions (models)."""
180-
schemas = self.google_api_spec.get("schemas", {})
182+
schemas = self._google_api_spec.get("schemas", {})
181183

182184
for schema_name, schema_def in schemas.items():
183185
converted_schema = self._convert_schema_object(schema_def)
184-
self.openapi_spec["components"]["schemas"][schema_name] = converted_schema
186+
self._openapi_spec["components"]["schemas"][
187+
schema_name
188+
] = converted_schema
185189

186190
def _convert_schema_object(
187191
self, schema_def: Dict[str, Any]
@@ -314,11 +318,11 @@ def _convert_methods(
314318
path_params = self._extract_path_parameters(rest_path)
315319

316320
# Create path entry if it doesn't exist
317-
if rest_path not in self.openapi_spec["paths"]:
318-
self.openapi_spec["paths"][rest_path] = {}
321+
if rest_path not in self._openapi_spec["paths"]:
322+
self._openapi_spec["paths"][rest_path] = {}
319323

320324
# Add the operation for this method
321-
self.openapi_spec["paths"][rest_path][http_method] = (
325+
self._openapi_spec["paths"][rest_path][http_method] = (
322326
self._convert_operation(method_data, path_params)
323327
)
324328

@@ -472,7 +476,7 @@ def save_openapi_spec(self, output_path: str) -> None:
472476
output_path: Path where the OpenAPI spec should be saved
473477
"""
474478
with open(output_path, "w", encoding="utf-8") as f:
475-
json.dump(self.openapi_spec, f, indent=2)
10000 479+
json.dump(self._openapi_spec, f, indent=2)
476480
logger.info("OpenAPI specification saved to %s", output_path)
477481

478482

tests/unittests/tools/google_api_tool/test_googleapi_to_openapi_converter.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ def mock_api_resource(calendar_api_spec):
214214
@pytest.fixture
215215
def prepared_converter(converter, calendar_api_spec):
216216
"""Fixture that provides a converter with the API spec already set."""
217-
converter.google_api_spec = calendar_api_spec
217+
converter._google_api_spec = calendar_api_spec
218218
return converter
219219

220220

@@ -242,14 +242,14 @@ class TestGoogleApiToOpenApiConverter:
242242

243243
def test_init(self, converter):
244244
"""Test converter initialization."""
245-
assert converter.api_name == "calendar"
246-
assert converter.api_version == "v3"
247-
assert converter.google_api_resource is None
248-
assert converter.google_api_spec is None
249-
assert converter.openapi_spec["openapi"] == "3.0.0"
250-
assert "info" in converter.openapi_spec
251-
assert "paths" in converter.openapi_spec
252-
assert "components" in converter.openapi_spec
245+
assert converter._api_name == "calendar"
246+
assert converter._api_version == "v3"
247+
assert converter._google_api_resource is None
248+
assert converter._google_api_spec is None
249+
assert converter._openapi_spec["openapi"] == "3.0.0"
250+
assert "info" in converter._openapi_spec
251+
assert "paths" in converter._openapi_spec
252+
assert "components" in converter._openapi_spec
253253

254254
def test_fetch_google_api_spec(
255255
self, converter_with_patched_build, calendar_api_spec
@@ -259,7 +259,7 @@ def test_fetch_google_api_spec(
259259
converter_with_patched_build.fetch_google_api_spec()
260260

261261
# Verify the results
262-
assert converter_with_patched_build.google_api_spec == calendar_api_spec
262+
assert converter_with_patched_build._google_api_spec == calendar_api_spec
263263

264264
def test_fetch_google_api_spec_error(self, monkeypatch, converter):
265265
"""Test error handling when fetching Google API specification."""
@@ -282,14 +282,14 @@ def test_convert_info(self, prepared_converter):
282282
prepared_converter._convert_info()
283283

284284
# Verify the results
285-
info = prepared_converter.openapi_spec["info"]
285+
info = prepared_converter._openapi_spec["info"]
286286
assert info["title"] == "Google Calendar API"
287287
assert info["description"] == "Accesses the Google Calendar API"
288288
assert info["version"] == "v3"
289289
assert info["termsOfService"] == "https://developers.google.com/calendar/"
290290

291291
# Check external docs
292-
external_docs = prepared_converter.openapi_spec["externalDocs"]
292+
external_docs = prepared_converter._openapi_spec["externalDocs"]
293293
assert external_docs["url"] == "https://developers.google.com/calendar/"
294294

295295
def test_convert_servers(self, prepared_converter):
@@ -298,7 +298,7 @@ def test_convert_servers(self, prepared_converter):
298298
prepared_converter._convert_servers()
299299

300300
# Verify the results
301-
servers = prepared_converter.openapi_spec["servers"]
301+
servers = prepared_converter._openapi_spec["servers"]
302302
assert len(servers) == 1
303303
assert servers[0]["url"] == "https://www.googleapis.com/calendar/v3"
304304
assert servers[0]["description"] == "calendar v3 API"
@@ -309,7 +309,7 @@ def test_convert_security_schemes(self, prepared_converter):
309309
prepared_converter._convert_security_schemes()
310310

311311
# Verify the results
312-
security_schemes = prepared_converter.openapi_spec["components"][
312+
security_schemes = prepared_converter._openapi_spec["components"][
313313
"securitySchemes"
314314
]
315315

@@ -335,7 +335,7 @@ def test_convert_schemas(self, prepared_converter):
335335
prepared_converter._convert_schemas()
336336

337337
# Verify the results
338< B9B8 span class="diff-text-marker">-
schemas = prepared_converter.openapi_spec["components"]["schemas"]
338+
schemas = prepared_converter._openapi_spec["components"]["schemas"]
339339

340340
# Check Calendar schema
341341
assert "Calendar" in schemas
@@ -524,7 +524,7 @@ def test_convert_methods(self, prepared_converter, calendar_api_spec):
524524
prepared_converter._convert_methods(methods, "/calendars")
525525

526526
# Verify the results
527-
paths = prepared_converter.openapi_spec["paths"]
527+
paths = prepared_converter._openapi_spec["paths"]
528528

529529
# Check GET method
530530
assert "/calendars/{calendarId}" in paths
@@ -565,7 +565,7 @@ def test_convert_resources(self, prepared_converter, calendar_api_spec):
565565
prepared_converter._convert_resources(resources)
566566

567567
# Verify the results
568-
paths = prepared_converter.openapi_spec["paths"]
568+
paths = prepared_converter._openapi_spec["paths"]
569569

570570
# Check top-level resource methods
571571
assert "/calendars/{calendarId}" in paths

0 commit comments

Comments
 (0)
0