-
Notifications
You must be signed in to change notification settings - Fork 15
feat: Added a sync toolbox client #131
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
Changes from 9 commits
Commits
Show all changes
41 commits
Select commit
Hold shift + click to select a range
3e6336f
create sync tool
twishabansal b6442b4
create sync client
twishabansal 2095970
add sync client and its tests
twishabansal 190ae98
lint
twishabansal fe45341
small fix
twishabansal fad580a
docs fix
twishabansal 7737c84
lint
twishabansal 5a866b9
Export sync as well as async client
twishabansal e3272ae
remove mixed implementations
twishabansal 1231006
Merge branch 'main' into twisha-sync-wrapper
twishabansal 9b8776f
fix toolbox sync client and tool name
twishabansal 5d5338d
fix default port
twishabansal c7603f2
PR comments resolve
twishabansal 50217d3
Merge remote-tracking branch 'origin/twisha-sync-wrapper' into twisha…
twishabansal 9c0d0db
small fix
twishabansal 954d7d2
Apply suggestions from code review
twishabansal 239143f
fix docstrings
twishabansal 0e370f3
Merge remote-tracking branch 'origin/twisha-sync-wrapper' into twisha…
twishabansal 351dd11
lint
twishabansal aea643b
Merge branch 'main' into twisha-sync-wrapper
twishabansal 27aa9d8
small fix
twishabansal 9ace575
resolve comment
twishabansal 360b4be
fix
twishabansal 68c82d2
Merge remote-tracking branch 'origin/twisha-sync-wrapper' into twisha…
twishabansal 033c85d
remove run_as_sync and run_as_async methods
twishabansal cacec35
lint
twishabansal 9bab4c0
lint
twishabansal d81a790
change from function attributes to properties
twishabansal dd4ebd9
fix mypy issue
twishabansal dfe7768
fix mypy issue
twishabansal a805455
lint
twishabansal c5a0cf5
remove session variable
twishabansal eb28453
lint
twishabansal d620c25
added qualname
twishabansal 9e1da13
fix qualname
twishabansal 5aaf20a
nit
twishabansal 6d0780a
Merge branch 'main' into twisha-sync-wrapper
twishabansal 1f21b36
Merge branch 'main' into twisha-sync-wrapper
twishabansal 4939a18
fix comment
twishabansal d650e1c
fix error message
twishabansal f0455a0
Merge branch 'main' into twisha-sync-wrapper
twishabansal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
# 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 threading import Thread | ||
from typing import Any, Awaitable, Callable, Mapping, Optional, TypeVar, Union | ||
|
||
from aiohttp import ClientSession | ||
|
||
from .client import ToolboxClient | ||
from .sync_tool import ToolboxSyncTool | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
class ToolboxSyncClient: | ||
""" | ||
A synchronous client for interacting with a Toolbox service. | ||
|
||
Provides methods to discover and load tools defined by a remote Toolbox | ||
service endpoint, returning synchronous tool wrappers (`SyncToolboxTool`). | ||
It manages an underlying asynchronous `ToolboxClient`. | ||
""" | ||
|
||
__session: Optional[ClientSession] = None | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
__loop: Optional[asyncio.AbstractEventLoop] = None | ||
__thread: Optional[Thread] = None | ||
|
||
def __init__( | ||
self, | ||
url: str, | ||
): | ||
""" | ||
Initializes the SyncToolboxClient. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Args: | ||
url: The base URL for the Toolbox service API (e.g., "http://localhost:8000"). | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
# Running a loop in a background thread allows us to support async | ||
# methods from non-async environments. | ||
if ToolboxSyncClient.__loop is None: | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
loop = asyncio.new_event_loop() | ||
thread = Thread(target=loop.run_forever, daemon=True) | ||
thread.start() | ||
ToolboxSyncClient.__thread = thread | ||
ToolboxSyncClient.__loop = loop | ||
|
||
async def __start_session() -> None: | ||
# Use a default session if none is provided. This leverages connection | ||
# pooling for better performance by reusing a single session throughout | ||
# the application's lifetime. | ||
if ToolboxSyncClient.__session is None: | ||
ToolboxSyncClient.__session = ClientSession() | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
coro = __start_session() | ||
|
||
asyncio.run_coroutine_threadsafe(coro, ToolboxSyncClient.__loop).result() | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if not ToolboxSyncClient.__session: | ||
raise ValueError("Session cannot be None.") | ||
self.__async_client = ToolboxClient(url, ToolboxSyncClient.__session) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def __run_as_sync(self, coro: Awaitable[T]) -> T: | ||
"""Run an async coroutine synchronously""" | ||
if not self.__loop: | ||
raise Exception( | ||
"Cannot call synchronous methods before the background loop is initialized." | ||
) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return asyncio.run_coroutine_threadsafe(coro, self.__loop).result() | ||
|
||
async def __run_as_async(self, coro: Awaitable[T]) -> T: | ||
"""Run an async coroutine asynchronously""" | ||
|
||
# If a loop has not been provided, attempt to run in current thread. | ||
if not self.__loop: | ||
return await coro | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
# Otherwise, run in the background thread. | ||
return await asyncio.wrap_future( | ||
asyncio.run_coroutine_threadsafe(coro, self.__loop) | ||
) | ||
|
||
def load_tool( | ||
self, | ||
tool_name: str, | ||
auth_token_getters: dict[str, Callable[[], str]] = {}, | ||
bound_params: Mapping[str, Union[Callable[[], Any], Any]] = {}, | ||
) -> ToolboxSyncTool: | ||
""" | ||
Synchronously loads a tool from the server. | ||
|
||
Retrieves the schema for the specified tool and returns a callable, | ||
synchronous object (`SyncToolboxTool`) that can be used to invoke the | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tool remotely. | ||
|
||
Args: | ||
tool_name: Name of the tool to load. | ||
auth_token_getters: A mapping of authentication service names to | ||
callables that return the corresponding authentication token. | ||
bound_params: A mapping of parameter names to bind to specific values or | ||
callables that are called to produce values as needed. | ||
|
||
Returns: | ||
ToolboxSyncTool: A synchronous callable object representing the loaded tool. | ||
""" | ||
async_tool = self.__run_as_sync( | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.__async_client.load_tool(tool_name, auth_token_getters, bound_params) | ||
) | ||
|
||
if not self.__loop or not self.__thread: | ||
raise ValueError("Background loop or thread cannot be None.") | ||
return ToolboxSyncTool(async_tool, self.__loop, self.__thread) | ||
|
||
def load_toolset( | ||
self, | ||
toolset_name: str, | ||
auth_token_getters: dict[str, Callable[[], str]] = {}, | ||
bound_params: Mapping[str, Union[Callable[[], Any], Any]] = {}, | ||
) -> list[ToolboxSyncTool]: | ||
""" | ||
Synchronously fetches a toolset and loads all tools defined within it. | ||
|
||
Args: | ||
toolset_name: Name of the toolset to load tools. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
auth_token_getters: A mapping of authentication service names to | ||
callables that return the corresponding authentication token. | ||
bound_params: A mapping of parameter names to bind to specific values or | ||
callables that are called to produce values as needed. | ||
|
||
Returns: | ||
list[ToolboxSyncTool]: A list of synchronous callables, one for each | ||
tool defined in the toolset. | ||
""" | ||
async_tools = self.__run_as_sync( | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.__async_client.load_toolset( | ||
toolset_name, auth_token_getters, bound_params | ||
) | ||
) | ||
|
||
if not self.__loop or not self.__thread: | ||
raise ValueError("Background loop or thread cannot be None.") | ||
tools: list[ToolboxSyncTool] = [] | ||
for async_tool in async_tools: | ||
tools.append(ToolboxSyncTool(async_tool, self.__loop, self.__thread)) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return tools | ||
|
||
def close(self): | ||
""" | ||
Synchronously closes the client session if it was created internally by the client. | ||
""" | ||
coro = self.__session.close() | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.__run_as_sync(coro) | ||
|
||
def __enter__(self): | ||
"""Enter the runtime context related to this client instance.""" | ||
return self | ||
|
||
def __exit__(self, exc_type, exc_val, exc_tb): | ||
"""Exit the runtime context and close the client session.""" | ||
self.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
# 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 asyncio import AbstractEventLoop | ||
from threading import Thread | ||
from typing import Any, Awaitable, Callable, Mapping, TypeVar, Union | ||
|
||
from .tool import ToolboxTool | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
class ToolboxSyncTool: | ||
""" | ||
A synchronous wrapper around an asynchronous ToolboxTool instance. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
This class allows calling the underlying async tool's __call__ method | ||
synchronously. It also wraps methods like `add_auth_token_getters` and | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
`bind_parameters` to ensure they return new instances of this synchronous | ||
wrapper. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
|
||
def __init__( | ||
self, async_tool: ToolboxTool, loop: AbstractEventLoop, thread: Thread | ||
): | ||
""" | ||
Initializes the synchronous wrapper. | ||
|
||
Args: | ||
async_tool: An instance of the asynchronous ToolboxTool. | ||
""" | ||
if not isinstance(async_tool, ToolboxTool): | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
raise TypeError("async_tool must be an instance of ToolboxTool") | ||
|
||
self.__async_tool = async_tool | ||
self.__loop = loop | ||
self.__thread = thread | ||
|
||
# Delegate introspection attributes to the wrapped async tool | ||
self.__name__ = self.__async_tool.__name__ | ||
self.__doc__ = self.__async_tool.__doc__ | ||
self.__signature__ = self.__async_tool.__signature__ | ||
self.__annotations__ = self.__async_tool.__annotations__ | ||
# TODO: self.__qualname__ ?? (Consider if needed) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def __run_as_sync(self, coro: Awaitable[T]) -> T: | ||
"""Run an async coroutine synchronously""" | ||
if not self.__loop: | ||
raise Exception( | ||
"Cannot call synchronous methods before the background loop is initialized." | ||
) | ||
return asyncio.run_coroutine_threadsafe(coro, self.__loop).result() | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
async def __run_as_async(self, coro: Awaitable[T]) -> T: | ||
"""Run an async coroutine asynchronously""" | ||
|
||
# If a loop has not been provided, attempt to run in current thread. | ||
if not self.__loop: | ||
return await coro | ||
|
||
# Otherwise, run in the background thread. | ||
return await asyncio.wrap_future( | ||
asyncio.run_coroutine_threadsafe(coro, self.__loop) | ||
) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def __call__(self, *args: Any, **kwargs: Any) -> str: | ||
""" | ||
Synchronously calls the underlying remote tool. | ||
|
||
This method blocks until the asynchronous call completes and returns | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
the result. | ||
|
||
Args: | ||
*args: Positional arguments for the tool. | ||
**kwargs: Keyword arguments for the tool. | ||
|
||
Returns: | ||
The string result returned by the remote tool execution. | ||
|
||
Raises: | ||
Any exception raised by the underlying async tool's __call__ method | ||
or during asyncio execution. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
return self.__run_as_sync(self.__async_tool(**kwargs)) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def add_auth_token_getters( | ||
self, | ||
auth_token_getters: Mapping[str, Callable[[], str]], | ||
) -> "ToolboxSyncTool": | ||
""" | ||
Registers auth token getters and returns a new SyncToolboxTool instance. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Args: | ||
auth_token_getters: A mapping of authentication service names to | ||
callables that return the corresponding authentication token. | ||
|
||
Returns: | ||
A new SyncToolboxTool instance wrapping the updated async tool. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
new_async_tool = self.__async_tool.add_auth_token_getters(auth_token_getters) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return ToolboxSyncTool(new_async_tool, self.__loop, self.__thread) | ||
|
||
def bind_parameters( | ||
self, bound_params: Mapping[str, Union[Callable[[], Any], Any]] | ||
) -> "ToolboxSyncTool": | ||
""" | ||
Binds parameters and returns a new SyncToolboxTool instance. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Args: | ||
bound_params: A mapping of parameter names to values or callables that | ||
produce values. | ||
|
||
Returns: | ||
A new SyncToolboxTool instance wrapping the updated async tool. | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
new_async_tool = self.__async_tool.bind_parameters(bound_params) | ||
twishabansal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return ToolboxSyncTool(new_async_tool, self.__loop, self.__thread) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.