Skip to content

chore(toolbox-core): Move util functions to a separate file in toolbox core #174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
c00b4ad
dep: Add pytest-cov package as a test dependency.
anubhav756 Apr 3, 2025
915a4fd
chore: Remove unused imports from sync_client.py
anubhav756 Apr 3, 2025
8f7fe72
chore: Add unit tests for the tool and client classes
anubhav756 Apr 9, 2025
952aed2
chore: Delint
anubhav756 Apr 9, 2025
da4efff
chore: Delint
anubhav756 Apr 9, 2025
51f2f04
chore: Cover tool not found case
anubhav756 Apr 9, 2025
56dea10
chore: Add toolbox tool unit test cases
anubhav756 Apr 9, 2025
2991eca
chore: Add additional test cases to cover tool invocation and better …
anubhav756 Apr 10, 2025
d1d3aaa
chore: Add test cases for sync and static bound parameter.
anubhav756 Apr 10, 2025
d3e20e5
chore: Reorder tests in matching classes.
anubhav756 Apr 10, 2025
a945a4b
feat: Add support for async token getters to ToolboxTool
anubhav756 Apr 4, 2025
1fc2a85
chore: Improve variable names and docstring for more clarity
anubhav756 Apr 5, 2025
e3fcade
chore: Improve docstring
anubhav756 Apr 5, 2025
17d7f85
chore: Add unit test cases
anubhav756 Apr 9, 2025
538b384
chore: Add e2e test case
anubhav756 Apr 10, 2025
c80fadc
chore: Fix e2e test case
anubhav756 Apr 11, 2025
e005dab
chore(toolbox-core): Move util functions to a separate file in toolbo…
anubhav756 Apr 15, 2025
613ed14
chore: Add licence header to tests file
anubhav756 Apr 15, 2025
1a60828
Merge branch 'main' of https://github.com/googleapis/genai-toolbox-la…
anubhav756 Apr 16, 2025
a0eb9d1
doc: Fix a typo
anubhav756 Apr 16, 2025
3a58213
chore: Rename helper function to better reflect the functionality.
anubhav756 Apr 16, 2025
71613e8
Merge branch 'main' of https://github.com/googleapis/genai-toolbox-la…
anubhav756 Apr 16, 2025
c4adf84
Merge branch 'main' of https://github.com/googleapis/genai-toolbox-la…
anubhav756 Apr 16, 2025
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
94 changes: 7 additions & 87 deletions packages/toolbox-core/src/toolbox_core/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,28 @@
# limitations under the License.


import asyncio
import types
from inspect import Signature
from typing import (
Any,
Awaitable,
Callable,
Iterable,
Mapping,
Optional,
Sequence,
Type,
Union,
cast,
)

from aiohttp import ClientSession
from pydantic import BaseModel, Field, create_model

from toolbox_core.protocol import ParameterSchema

from .utils import (
create_docstring,
identify_required_authn_params,
params_to_pydantic_model,
resolve_value,
)


class ToolboxTool:
"""
Expand Down Expand Up @@ -271,84 +272,3 @@ def bind_parameters(
params=new_params,
bound_params=types.MappingProxyType(all_bound_params),
)


def create_docstring(description: str, params: Sequence[ParameterSchema]) -> str:
"""Convert tool description and params into its function docstring"""
docstring = description
if not params:
return docstring
docstring += "\n\nArgs:"
for p in params:
docstring += (
f"\n {p.name} ({p.to_param().annotation.__name__}): {p.description}"
)
return docstring


def identify_required_authn_params(
req_authn_params: Mapping[str, list[str]], auth_service_names: Iterable[str]
) -> dict[str, list[str]]:
"""
Identifies authentication parameters that are still required; because they
not covered by the provided `auth_service_names`.

Args:
req_authn_params: A mapping of parameter names to sets of required
authentication services.
auth_service_names: An iterable of authentication service names for which
token getters are available.

Returns:
A new dictionary representing the subset of required authentication parameters
that are not covered by the provided `auth_services`.
"""
required_params = {} # params that are still required with provided auth_services
for param, services in req_authn_params.items():
# if we don't have a token_getter for any of the services required by the param,
# the param is still required
required = not any(s in services for s in auth_service_names)
if required:
required_params[param] = services
return required_params


def params_to_pydantic_model(
tool_name: str, params: Sequence[ParameterSchema]
) -> Type[BaseModel]:
"""Converts the given parameters to a Pydantic BaseModel class."""
field_definitions = {}
for field in params:
field_definitions[field.name] = cast(
Any,
(
field.to_param().annotation,
Field(description=field.description),
),
)
return create_model(tool_name, **field_definitions)


async def resolve_value(
source: Union[Callable[[], Awaitable[Any]], Callable[[], Any], Any],
) -> Any:
"""
Asynchronously or synchronously resolves a given source to its value.

If the `source` is a coroutine function, it will be awaited.
If the `source` is a regular callable, it will be called.
Otherwise (if it's not a callable), the `source` itself is returned directly.

Args:
source: The value, a callable returning a value, or a callable
returning an awaitable value.

Returns:
The resolved value.
"""

if asyncio.iscoroutinefunction(source):
return await source()
elif callable(source):
return source()
return source
112 changes: 112 additions & 0 deletions packages/toolbox-core/src/toolbox_core/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import asyncio
from typing import (
Any,
Awaitable,
Callable,
Iterable,
Mapping,
Sequence,
Type,
Union,
cast,
)

from pydantic import BaseModel, Field, create_model

from toolbox_core.protocol import ParameterSchema


def create_docstring(description: str, params: Sequence[ParameterSchema]) -> str:
"""Convert tool description and params into its function docstring"""
docstring = description
if not params:
return docstring
docstring += "\n\nArgs:"
for p in params:
docstring += (
f"\n {p.name} ({p.to_param().annotation.__name__}): {p.description}"
)
return docstring


def identify_required_authn_params(
req_authn_params: Mapping[str, list[str]], auth_service_names: Iterable[str]
) -> dict[str, list[str]]:
"""
Identifies authentication parameters that are still required; because they
are not covered by the provided `auth_service_names`.

Args:
req_authn_params: A mapping of parameter names to sets of required
authentication services.
auth_service_names: An iterable of authentication service names for which
token getters are available.

Returns:
A new dictionary representing the subset of required authentication parameters
that are not covered by the provided `auth_services`.
"""
required_params = {} # params that are still required with provided auth_services
for param, services in req_authn_params.items():
# if we don't have a token_getter for any of the services required by the param,
# the param is still required
required = not any(s in services for s in auth_service_names)
if required:
required_params[param] = services
return required_params


def params_to_pydantic_model(
tool_name: str, params: Sequence[ParameterSchema]
) -> Type[BaseModel]:
"""Converts the given parameters to a Pydantic BaseModel class."""
field_definitions = {}
for field in params:
field_definitions[field.name] = cast(
Any,
(
field.to_param().annotation,
Field(description=field.description),
),
)
return create_model(tool_name, **field_definitions)


async def resolve_value(
source: Union[Callable[[], Awaitable[Any]], Callable[[], Any], Any],
) -> Any:
"""
Asynchronously or synchronously resolves a given source to its value.

If the `source` is a coroutine function, it will be awaited.
If the `source` is a regular callable, it will be called.
Otherwise (if it's not a callable), the `source` itself is returned directly.

Args:
source: The value, a callable returning a value, or a callable
returning an awaitable value.

Returns:
The resolved value.
"""

if asyncio.iscoroutinefunction(source):
return await source()
elif callable(source):
return source()
return source
Loading