Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/google/adk/tools/openapi_tool/common/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@
from ..._gemini_schema_util import _to_snake_case


def _is_json_media_type(content_type: str) -> bool:
"""Returns whether the media type denotes a JSON representation."""
media_type = content_type.partition(';')[0].strip().lower()
return media_type == 'application/json' or media_type.endswith('+json')


def _schema_from_openapi(value: object, *, context: str) -> Schema:
"""Normalizes a schema-bearing OpenAPI field to a concrete Schema.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ def __init__(
httpx_client_factory: Optional[HttpxClientFactory] = None,
preserve_property_names: bool = False,
allow_private_network_access: bool = False,
include_response_schema: bool = False,
) -> None:
"""Initializes the OpenAPIToolset.

Expand Down Expand Up @@ -172,6 +173,14 @@ def __init__(
``*.local`` targets and return an error response. Set this to ``True``
to allow requests to private networks, localhost, and custom non-DNS
transports.
include_response_schema: If True, each generated tool's function
declaration includes the tool's declared success shapes as
``response_json_schema`` when known. Explicitly non-JSON responses
are returned as a text object. A response that lists JSON beside other
media types is declared by its JSON alone, which the tool requests
with an ``Accept`` header.
This adds the schemas to every model request that includes the tools.
Defaults to False.
"""
super().__init__(tool_filter=tool_filter, tool_name_prefix=tool_name_prefix)
self._header_provider = header_provider
Expand All @@ -195,6 +204,7 @@ def __init__(
self._ssl_verify = ssl_verify
self._httpx_client_factory = httpx_client_factory
self._allow_private_network_access = allow_private_network_access
self._include_response_schema = include_response_schema
self._tools: Final[List[RestApiTool]] = list(self._parse(spec_dict))
if auth_scheme or auth_credential:
self._configure_auth_all(auth_scheme, auth_credential)
Expand Down Expand Up @@ -290,6 +300,7 @@ def _parse(self, openapi_spec_dict: Dict[str, Any]) -> List[RestApiTool]:
header_provider=self._header_provider,
httpx_client_factory=self._httpx_client_factory,
allow_private_network_access=self._allow_private_network_access,
include_response_schema=self._include_response_schema,
)
for o in operations
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

import inspect
import json
from textwrap import dedent
from typing import Any
from typing import cast
Expand All @@ -23,6 +24,7 @@
from typing import Optional

from fastapi.encoders import jsonable_encoder
from fastapi.openapi.models import MediaType
from fastapi.openapi.models import Operation
from fastapi.openapi.models import Parameter
from fastapi.openapi.models import ParameterInType
Expand All @@ -32,6 +34,7 @@
from fastapi.openapi.models import Schema

from ..._gemini_schema_util import _to_snake_case
from ..common.common import _is_json_media_type
from ..common.common import _schema_from_openapi
from ..common.common import ApiParameter
from ..common.common import PydocHelper
Expand All @@ -40,6 +43,59 @@
_MAX_TOOL_NAME_LENGTH = 60


def _normalize_response_schema(schema: dict[str, Any]) -> None:
"""Translates OpenAPI schema keywords for use as a JSON response schema."""
schema_type = schema.get('type')
if (
schema.pop('nullable', False) is True
and isinstance(schema_type, str)
and schema_type != 'null'
):
schema['type'] = [schema_type, 'null']

properties = schema.get('properties') or {}
if schema.get('required'):
schema['required'] = [
name
for name in schema['required']
if not (
isinstance(properties.get(name), dict)
and properties[name].get('writeOnly') is True
)
]

for key in ('properties', 'patternProperties', 'dependentSchemas', '$defs'):
for child in (schema.get(key) or {}).values():
if isinstance(child, dict):
_normalize_response_schema(child)
for key in ('allOf', 'anyOf', 'oneOf', 'prefixItems'):
for child in schema.get(key) or ():
if isinstance(child, dict):
_normalize_response_schema(child)
for key in (
'items',
'additionalProperties',
'contains',
'propertyNames',
'not',
'if',
'then',
'else',
'unevaluatedItems',
'unevaluatedProperties',
'contentSchema',
):
child = schema.get(key)
if isinstance(child, dict):
_normalize_response_schema(child)


def _requested_media_types(content: dict[str, MediaType]) -> list[str]:
"""Returns the media types a tool asks for: the JSON ones, if any."""
json_types = [t for t in content if _is_json_media_type(t)]
return json_types or list(content)


def _required_scheme_name(
security: Optional[List[Dict[str, List[str]]]],
) -> str:
Expand Down Expand Up @@ -355,6 +411,69 @@ def get_json_schema(self) -> Dict[str, Any]:
'type': 'object',
}

def get_response_json_schema(self) -> Dict[str, Any] | None:
"""Returns the tool's declared success shapes, or None if unknown."""
schemas: dict[str, dict[str, Any]] = {}
text_response = False
for status, response in (self._operation.responses or {}).items():
if not status.startswith('2'):
continue
if not isinstance(response, Response):
return None
if not response.content or status in ('204', '205'):
text_response = True
continue
for media_type in _requested_media_types(response.content):
media = response.content[media_type]
if '*' in media_type:
return None
if not _is_json_media_type(media_type):
text_response = True
continue
if not isinstance(media.schema_, Schema):
return None
schema = media.schema_.model_dump(
mode='json', by_alias=True, exclude_unset=True
)
_normalize_response_schema(schema)
if not schema:
return None
schemas[json.dumps(schema, sort_keys=True)] = schema

variants = list(schemas.values())
if text_response:
variants.append({
'type': 'object',
'properties': {'text': {'type': 'string'}},
'required': ['text'],
})
if len(variants) > 1:
return {'anyOf': variants}
return variants[0] if variants else None

def get_accept_header(self) -> str | None:
"""Returns an Accept value for the declared success shapes.

A success response that lists JSON beside other media types is declared by
its JSON alone, so the tool must ask for it. Returns None when the response
schema is unknown or every listed media type is declared.
"""
if self.get_response_json_schema() is None:
return None
listed: list[str] = []
requested: list[str] = []
for status, response in (self._operation.responses or {}).items():
if (
status.startswith('2')
and isinstance(response, Response)
and response.content
):
listed.extend(response.content)
requested.extend(_requested_media_types(response.content))
if len(requested) == len(listed):
return None
return ', '.join(dict.fromkeys(requested))

def get_signature_parameters(self) -> List[inspect.Parameter]:
"""Returns a list of inspect.Parameter objects for the function."""
return [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
from ..auth.auth_helpers import credential_to_param
from ..auth.auth_helpers import dict_to_auth_scheme
from ..auth.credential_exchangers.auto_auth_credential_exchanger import AutoAuthCredentialExchanger
from ..common.common import _is_json_media_type
from ..common.common import ApiParameter
from .openapi_spec_parser import OperationEndpoint
from .openapi_spec_parser import ParsedOperation
Expand Down Expand Up @@ -205,6 +206,7 @@ def __init__(
*,
credential_key: Optional[str] = None,
allow_private_network_access: bool = False,
include_response_schema: bool = False,
):
"""Initializes the RestApiTool with the given parameters.

Expand Down Expand Up @@ -261,6 +263,13 @@ def __init__(
``*.local`` targets and return an error response. Set this to ``True``
to allow requests to private networks, localhost, and custom non-DNS
transports.
include_response_schema: If True, the function declaration includes
the tool's declared success shapes as ``response_json_schema`` when
known. Explicitly non-JSON responses are returned as a text object.
A response that lists JSON beside other media types is declared by
its JSON alone, which the tool requests with an ``Accept`` header.
This adds the schema to every model request that includes the tool.
Defaults to False.
"""
# Gemini restrict the length of function name to be less than 64 characters
self.name = name[:_MAX_TOOL_NAME_LENGTH]
Expand Down Expand Up @@ -289,6 +298,7 @@ def __init__(
self._httpx_client_factory = httpx_client_factory
self._logger = logger
self._allow_private_network_access = allow_private_network_access
self._include_response_schema = include_response_schema
if should_parse_operation:
self._operation_parser = OperationParser(self.operation)

Expand All @@ -303,6 +313,7 @@ def from_parsed_operation(
httpx_client_factory: Optional[HttpxClientFactory] = None,
*,
allow_private_network_access: bool = False,
include_response_schema: bool = False,
) -> "RestApiTool":
"""Initializes the RestApiTool from a ParsedOperation object.

Expand All @@ -322,6 +333,8 @@ def from_parsed_operation(
``*.local`` targets and return an error response. Set this to ``True``
to allow requests to private networks, localhost, and custom non-DNS
transports.
include_response_schema: Whether the function declaration includes the
tool's declared success shapes. See ``RestApiTool.__init__``.

Returns:
A RestApiTool object.
Expand All @@ -344,6 +357,7 @@ def from_parsed_operation(
header_provider=header_provider,
httpx_client_factory=httpx_client_factory,
allow_private_network_access=allow_private_network_access,
include_response_schema=include_response_schema,
)
generated._operation_parser = operation_parser
return generated
Expand Down Expand Up @@ -372,6 +386,11 @@ def _get_declaration(self) -> FunctionDeclaration:
name=self.name,
description=self.description,
parameters_json_schema=schema_dict,
response_json_schema=(
self._operation_parser.get_response_json_schema()
if self._include_response_schema
else None
),
)
else:
parameters = _to_gemini_schema(schema_dict)
Expand Down Expand Up @@ -478,6 +497,13 @@ def _prepare_request_params(
user_agent = f"google-adk/{adk_version} (tool: {self.name})"
header_params["User-Agent"] = user_agent

if self._include_response_schema:
# Without it, httpx sends `*/*` and the server may pick a media type
# that the declaration leaves out.
accept = self._operation_parser.get_accept_header()
if accept:
header_params["Accept"] = accept

if (
self.auth_credential
and self.auth_credential.http
Expand Down Expand Up @@ -630,12 +656,13 @@ def _prepare_request_params(
@override
async def run_async(
self, *, args: dict[str, Any], tool_context: Optional[ToolContext]
) -> Dict[str, Any]:
) -> Any:
"""Runs the REST operation and returns its decoded result."""
return await self.call(args=args, tool_context=tool_context)

async def call(
self, *, args: dict[str, Any], tool_context: Optional[ToolContext]
) -> Dict[str, Any]:
) -> Any:
"""Executes the REST API call.

Args:
Expand All @@ -645,9 +672,9 @@ async def call(
attempt and the guard that bounds the retry.

Returns:
The API response as a dictionary. HTTP, authorization, and URL
validation failures are reported as an "error" entry rather than
raised.
The decoded JSON value or a dictionary containing the response text.
HTTP, authorization, and URL validation failures return an "error"
entry.
"""
# Prepare auth credentials for the API call
tool_auth_handler = ToolAuthHandler.from_tool_context(
Expand Down Expand Up @@ -764,7 +791,11 @@ async def call(
# Parse API response
try:
response.raise_for_status() # Raise HTTPStatusError for bad responses
return response.json() # Try to decode JSON
if self._include_response_schema:
content_type = response.headers.get("content-type")
if content_type and not _is_json_media_type(content_type):
return {"text": response.text}
return response.json()
except httpx.HTTPStatusError:
error_details = response.text
self._logger.warning(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,23 @@ def test_openapi_toolset_preserve_property_names(openapi_spec: Dict[str, Any]):
assert "calendarId" in schema["properties"]


@pytest.mark.parametrize("include_response_schema", [True, False])
def test_openapi_toolset_include_response_schema(
openapi_spec: Dict[str, Any], include_response_schema: bool
):
toolset = OpenAPIToolset(
spec_dict=openapi_spec, include_response_schema=include_response_schema
)
tool = toolset.get_tool("calendar_calendars_get")
assert tool is not None

declaration = tool._get_declaration()

assert (declaration.response_json_schema is not None) == (
include_response_schema
)


def test_openapi_toolset_default_snake_case_conversion(
openapi_spec: Dict[str, Any],
):
Expand Down
Loading
Loading