Skip to content

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 41 commits into from
Apr 3, 2025
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
3e6336f
create sync tool
twishabansal Apr 3, 2025
b6442b4
create sync client
twishabansal Apr 3, 2025
2095970
add sync client and its tests
twishabansal Apr 3, 2025
190ae98
lint
twishabansal Apr 3, 2025
fe45341
small fix
twishabansal Apr 3, 2025
fad580a
docs fix
twishabansal Apr 3, 2025
7737c84
lint
twishabansal Apr 3, 2025
5a866b9
Export sync as well as async client
twishabansal Apr 3, 2025
e3272ae
remove mixed implementations
twishabansal Apr 3, 2025
1231006
Merge branch 'main' into twisha-sync-wrapper
twishabansal Apr 3, 2025
9b8776f
fix toolbox sync client and tool name
twishabansal Apr 3, 2025
5d5338d
fix default port
twishabansal Apr 3, 2025
c7603f2
PR comments resolve
twishabansal Apr 3, 2025
50217d3
Merge remote-tracking branch 'origin/twisha-sync-wrapper' into twisha…
twishabansal Apr 3, 2025
9c0d0db
small fix
twishabansal Apr 3, 2025
954d7d2
Apply suggestions from code review
twishabansal Apr 3, 2025
239143f
fix docstrings
twishabansal Apr 3, 2025
0e370f3
Merge remote-tracking branch 'origin/twisha-sync-wrapper' into twisha…
twishabansal Apr 3, 2025
351dd11
lint
twishabansal Apr 3, 2025
aea643b
Merge branch 'main' into twisha-sync-wrapper
twishabansal Apr 3, 2025
27aa9d8
small fix
twishabansal Apr 3, 2025
9ace575
resolve comment
twishabansal Apr 3, 2025
360b4be
fix
twishabansal Apr 3, 2025
68c82d2
Merge remote-tracking branch 'origin/twisha-sync-wrapper' into twisha…
twishabansal Apr 3, 2025
033c85d
remove run_as_sync and run_as_async methods
twishabansal Apr 3, 2025
cacec35
lint
twishabansal Apr 3, 2025
9bab4c0
lint
twishabansal Apr 3, 2025
d81a790
change from function attributes to properties
twishabansal Apr 3, 2025
dd4ebd9
fix mypy issue
twishabansal Apr 3, 2025
dfe7768
fix mypy issue
twishabansal Apr 3, 2025
a805455
lint
twishabansal Apr 3, 2025
c5a0cf5
remove session variable
twishabansal Apr 3, 2025
eb28453
lint
twishabansal Apr 3, 2025
d620c25
added qualname
twishabansal Apr 3, 2025
9e1da13
fix qualname
twishabansal Apr 3, 2025
5aaf20a
nit
twishabansal Apr 3, 2025
6d0780a
Merge branch 'main' into twisha-sync-wrapper
twishabansal Apr 3, 2025
1f21b36
Merge branch 'main' into twisha-sync-wrapper
twishabansal Apr 3, 2025
4939a18
fix comment
twishabansal Apr 3, 2025
d650e1c
fix error message
twishabansal Apr 3, 2025
f0455a0
Merge branch 'main' into twisha-sync-wrapper
twishabansal Apr 3, 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
114 changes: 46 additions & 68 deletions packages/toolbox-core/src/toolbox_core/sync_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,12 @@

class ToolboxSyncClient:
"""
A synchronous client for interacting with a Toolbox service.
An 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`.
service endpoint.
"""

__session: Optional[ClientSession] = None
__loop: Optional[asyncio.AbstractEventLoop] = None
__thread: Optional[Thread] = None

Expand All @@ -42,125 +40,105 @@ def __init__(
url: str,
):
"""
Initializes the SyncToolboxClient.
Initializes the ToolboxClient.

Args:
url: The base URL for the Toolbox service API (e.g., "http://localhost:8000").
url: The base URL for the Toolbox service API (e.g., "http://localhost:5000").
"""
# Running a loop in a background thread allows us to support async
# methods from non-async environments.
if ToolboxSyncClient.__loop is None:
if self.__class__.__loop is None:
loop = asyncio.new_event_loop()
thread = Thread(target=loop.run_forever, daemon=True)
thread.start()
ToolboxSyncClient.__thread = thread
ToolboxSyncClient.__loop = loop
self.__class__.__thread = thread
self.__class__.__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()
async def create_client():
return ToolboxClient(url)

coro = __start_session()
# Ignoring type since we're already checking the existing of a loop above.
self.__async_client = asyncio.run_coroutine_threadsafe(
create_client(), ToolboxSyncClient.__loop # type: ignore
).result()

asyncio.run_coroutine_threadsafe(coro, ToolboxSyncClient.__loop).result()

if not ToolboxSyncClient.__session:
raise ValueError("Session cannot be None.")
self.__async_client = ToolboxClient(url, ToolboxSyncClient.__session)

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()

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
def close(self):
"""
Synchronously closes the underlying client session. Doing so will cause
any tools created by this Client to cease to function.

# Otherwise, run in the background thread.
return await asyncio.wrap_future(
asyncio.run_coroutine_threadsafe(coro, self.__loop)
)
If the session was provided externally during initialization, the caller
is responsible for its lifecycle, but calling close here will still
attempt to close it.
"""
coro = self.__async_client.close()
asyncio.run_coroutine_threadsafe(coro, self.__loop).result()

def load_tool(
self,
tool_name: str,
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
Retrieves the schema for the specified tool from the Toolbox server and
returns a callable object (`ToolboxSyncTool`) that can be used to invoke the
tool remotely.

Args:
tool_name: Name of the tool to load.
name: The unique name or identifier 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.
ToolboxSyncTool: A callable object representing the loaded tool, ready
for execution. The specific arguments and behavior of the callable
depend on the tool itself.
"""
async_tool = self.__run_as_sync(
self.__async_client.load_tool(tool_name, auth_token_getters, bound_params)
)
coro = self.__async_client.load_tool(name, auth_token_getters, bound_params)

# We have already created a new loop in the init method in case it does not already exist
async_tool = asyncio.run_coroutine_threadsafe(coro, self.__loop).result() # type: ignore

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,
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.
name: Name of the toolset to load tools.
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.
list[ToolboxSyncTool]: A list of callables, one for each tool defined
in the toolset.
"""
async_tools = self.__run_as_sync(
self.__async_client.load_toolset(
toolset_name, auth_token_getters, bound_params
)
)
coro = self.__async_client.load_toolset(name, auth_token_getters, bound_params)

# We have already created a new loop in the init method in case it does not already exist
async_tools = asyncio.run_coroutine_threadsafe(coro, self.__loop).result() # type: ignore

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))
return tools

def close(self):
"""
Synchronously closes the client session if it was created internally by the client.
"""
coro = self.__session.close()
self.__run_as_sync(coro)
return [
ToolboxSyncTool(async_tool, self.__loop, self.__thread)
for async_tool in async_tools
]

def __enter__(self):
"""Enter the runtime context related to this client instance."""
Expand Down
87 changes: 46 additions & 41 deletions packages/toolbox-core/src/toolbox_core/sync_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@

import asyncio
from asyncio import AbstractEventLoop
from inspect import Signature
from threading import Thread
from typing import Any, Awaitable, Callable, Mapping, TypeVar, Union
from typing import Any, Callable, Mapping, TypeVar, Union

from .tool import ToolboxTool

Expand All @@ -24,106 +25,110 @@

class ToolboxSyncTool:
"""
A synchronous wrapper around an asynchronous ToolboxTool instance.
A callable proxy object representing a specific tool on a remote Toolbox server.

This class allows calling the underlying async tool's __call__ method
synchronously. It also wraps methods like `add_auth_token_getters` and
`bind_parameters` to ensure they return new instances of this synchronous
wrapper.
Instances of this class behave like synchronous functions. When called, they
send a request to the corresponding tool's endpoint on the Toolbox server with
the provided arguments.

It utilizes Python's introspection features (`__name__`, `__doc__`,
`__signature__`, `__annotations__`) so that standard tools like `help()`
and `inspect` work as expected.
"""

def __init__(
self, async_tool: ToolboxTool, loop: AbstractEventLoop, thread: Thread
):
"""
Initializes the synchronous wrapper.
Initializes a callable that will trigger the tool invocation through the
Toolbox server.

Args:
async_tool: An instance of the asynchronous ToolboxTool.
loop: The event loop used to run asynchronous tasks.
thread: The thread to run blocking operations in.
"""

if not isinstance(async_tool, ToolboxTool):
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)

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()
@property
def __name__(self) -> str:
return self.__async_tool.__name__

async def __run_as_async(self, coro: Awaitable[T]) -> T:
"""Run an async coroutine asynchronously"""
@property
def __doc__(self) -> Union[str, None]: # type: ignore[override]
# Standard Python object attributes like __doc__ are technically "writable".
# But not defining a setter function makes this a read-only property.
# Mypy flags this issue in the type checks.
return self.__async_tool.__doc__

# If a loop has not been provided, attempt to run in current thread.
if not self.__loop:
return await coro
@property
def __signature__(self) -> Signature:
return self.__async_tool.__signature__

# Otherwise, run in the background thread.
return await asyncio.wrap_future(
asyncio.run_coroutine_threadsafe(coro, self.__loop)
)
@property
def __annotations__(self) -> dict[str, Any]: # type: ignore[override]
# Standard Python object attributes like __doc__ are technically "writable".
# But not defining a setter function makes this a read-only property.
# Mypy flags this issue in the type checks.
return self.__async_tool.__annotations__

def __call__(self, *args: Any, **kwargs: Any) -> str:
"""
Synchronously calls the underlying remote tool.
Synchronously calls the remote tool with the provided arguments.

This method blocks until the asynchronous call completes and returns
the result.
Validates arguments against the tool's signature, then sends them
as a JSON payload in a POST request to the tool's invoke URL.

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.
"""
return self.__run_as_sync(self.__async_tool(**kwargs))
coro = self.__async_tool(*args, **kwargs)
return asyncio.run_coroutine_threadsafe(coro, self.__loop).result()

def add_auth_token_getters(
self,
auth_token_getters: Mapping[str, Callable[[], str]],
) -> "ToolboxSyncTool":
"""
Registers auth token getters and returns a new SyncToolboxTool instance.
Registers an auth token getter function that is used for AuthServices when tools
are invoked.

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.
A new ToolboxSyncTool instance with the specified authentication token
getters registered.
"""

new_async_tool = self.__async_tool.add_auth_token_getters(auth_token_getters)
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.
Binds parameters to values or callables that produce values.

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.
A new ToolboxSyncTool instance with the specified parameters bound.
"""

new_async_tool = self.__async_tool.bind_parameters(bound_params)
return ToolboxSyncTool(new_async_tool, self.__loop, self.__thread)
1 change: 1 addition & 0 deletions packages/toolbox-core/tests/test_sync_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# 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 pytest

from toolbox_core.sync_client import ToolboxSyncClient
Expand Down