|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import asyncio |
| 16 | +from threading import Thread |
| 17 | +from typing import Any, Awaitable, Callable, Mapping, Optional, TypeVar, Union |
| 18 | + |
| 19 | +from aiohttp import ClientSession |
| 20 | + |
| 21 | +from .client import ToolboxClient |
| 22 | +from .sync_tool import ToolboxSyncTool |
| 23 | + |
| 24 | +T = TypeVar("T") |
| 25 | + |
| 26 | + |
| 27 | +class ToolboxSyncClient: |
| 28 | + """ |
| 29 | + An synchronous client for interacting with a Toolbox service. |
| 30 | +
|
| 31 | + Provides methods to discover and load tools defined by a remote Toolbox |
| 32 | + service endpoint. |
| 33 | + """ |
| 34 | + |
| 35 | + __loop: Optional[asyncio.AbstractEventLoop] = None |
| 36 | + __thread: Optional[Thread] = None |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + url: str, |
| 41 | + ): |
| 42 | + """ |
| 43 | + Initializes the ToolboxSyncClient. |
| 44 | +
|
| 45 | + Args: |
| 46 | + url: The base URL for the Toolbox service API (e.g., "http://localhost:5000"). |
| 47 | + """ |
| 48 | + # Running a loop in a background thread allows us to support async |
| 49 | + # methods from non-async environments. |
| 50 | + if self.__class__.__loop is None: |
| 51 | + loop = asyncio.new_event_loop() |
| 52 | + thread = Thread(target=loop.run_forever, daemon=True) |
| 53 | + thread.start() |
| 54 | + self.__class__.__thread = thread |
| 55 | + self.__class__.__loop = loop |
| 56 | + |
| 57 | + async def create_client(): |
| 58 | + return ToolboxClient(url) |
| 59 | + |
| 60 | + # Ignoring type since we're already checking the existence of a loop above. |
| 61 | + self.__async_client = asyncio.run_coroutine_threadsafe( |
| 62 | + create_client(), self.__class__.__loop # type: ignore |
| 63 | + ).result() |
| 64 | + |
| 65 | + def close(self): |
| 66 | + """ |
| 67 | + Synchronously closes the underlying client session. Doing so will cause |
| 68 | + any tools created by this Client to cease to function. |
| 69 | +
|
| 70 | + If the session was provided externally during initialization, the caller |
| 71 | + is responsible for its lifecycle, but calling close here will still |
| 72 | + attempt to close it. |
| 73 | + """ |
| 74 | + coro = self.__async_client.close() |
| 75 | + asyncio.run_coroutine_threadsafe(coro, self.__loop).result() |
| 76 | + |
| 77 | + def load_tool( |
| 78 | + self, |
| 79 | + name: str, |
| 80 | + auth_token_getters: dict[str, Callable[[], str]] = {}, |
| 81 | + bound_params: Mapping[str, Union[Callable[[], Any], Any]] = {}, |
| 82 | + ) -> ToolboxSyncTool: |
| 83 | + """ |
| 84 | + Synchronously loads a tool from the server. |
| 85 | +
|
| 86 | + Retrieves the schema for the specified tool from the Toolbox server and |
| 87 | + returns a callable object (`ToolboxSyncTool`) that can be used to invoke the |
| 88 | + tool remotely. |
| 89 | +
|
| 90 | + Args: |
| 91 | + name: The unique name or identifier of the tool to load. |
| 92 | + auth_token_getters: A mapping of authentication service names to |
| 93 | + callables that return the corresponding authentication token. |
| 94 | + bound_params: A mapping of parameter names to bind to specific values or |
| 95 | + callables that are called to produce values as needed. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + ToolboxSyncTool: A callable object representing the loaded tool, ready |
| 99 | + for execution. The specific arguments and behavior of the callable |
| 100 | + depend on the tool itself. |
| 101 | + """ |
| 102 | + coro = self.__async_client.load_tool(name, auth_token_getters, bound_params) |
| 103 | + |
| 104 | + # We have already created a new loop in the init method in case it does not already exist |
| 105 | + async_tool = asyncio.run_coroutine_threadsafe(coro, self.__loop).result() # type: ignore |
| 106 | + |
| 107 | + if not self.__loop or not self.__thread: |
| 108 | + raise ValueError("Background loop or thread cannot be None.") |
| 109 | + return ToolboxSyncTool(async_tool, self.__loop, self.__thread) |
| 110 | + |
| 111 | + def load_toolset( |
| 112 | + self, |
| 113 | + name: str, |
| 114 | + auth_token_getters: dict[str, Callable[[], str]] = {}, |
| 115 | + bound_params: Mapping[str, Union[Callable[[], Any], Any]] = {}, |
| 116 | + ) -> list[ToolboxSyncTool]: |
| 117 | + """ |
| 118 | + Synchronously fetches a toolset and loads all tools defined within it. |
| 119 | +
|
| 120 | + Args: |
| 121 | + name: Name of the toolset to load tools. |
| 122 | + auth_token_getters: A mapping of authentication service names to |
| 123 | + callables that return the corresponding authentication token. |
| 124 | + bound_params: A mapping of parameter names to bind to specific values or |
| 125 | + callables that are called to produce values as needed. |
| 126 | +
|
| 127 | + Returns: |
| 128 | + list[ToolboxSyncTool]: A list of callables, one for each tool defined |
| 129 | + in the toolset. |
| 130 | + """ |
| 131 | + coro = self.__async_client.load_toolset(name, auth_token_getters, bound_params) |
| 132 | + |
| 133 | + # We have already created a new loop in the init method in case it does not already exist |
| 134 | + async_tools = asyncio.run_coroutine_threadsafe(coro, self.__loop).result() # type: ignore |
| 135 | + |
| 136 | + if not self.__loop or not self.__thread: |
| 137 | + raise ValueError("Background loop or thread cannot be None.") |
| 138 | + return [ |
| 139 | + ToolboxSyncTool(async_tool, self.__loop, self.__thread) |
| 140 | + for async_tool in async_tools |
| 141 | + ] |
| 142 | + |
| 143 | + def __enter__(self): |
| 144 | + """Enter the runtime context related to this client instance.""" |
| 145 | + return self |
| 146 | + |
| 147 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 148 | + """Exit the runtime context and close the client session.""" |
| 149 | + self.close() |
0 commit comments