|
| 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 | +from typing import List, Optional, override |
| 16 | + |
| 17 | +import toolbox_core as toolbox |
| 18 | + |
| 19 | +from ..agents.readonly_context import ReadonlyContext |
| 20 | +from .base_tool import BaseTool |
| 21 | +from .base_toolset import BaseToolset |
| 22 | +from .function_tool import FunctionTool |
| 23 | + |
| 24 | + |
| 25 | +class ToolboxToolset(BaseToolset): |
| 26 | + """A class that provides access to toolbox toolsets. |
| 27 | +
|
| 28 | + Example: |
| 29 | + ```python |
| 30 | + toolbox_toolset = ToolboxToolset("http://127.0.0.1:5000", |
| 31 | + toolset_name="my-toolset") |
| 32 | + ) |
| 33 | + ``` |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, |
| 38 | + server_url: str, |
| 39 | + toolset_name: Optional[str] = None, |
| 40 | + tool_names: Optional[List[str]] = None, |
| 41 | + ): |
| 42 | + """Args: |
| 43 | +
|
| 44 | + server_url: The URL of the toolbox server. |
| 45 | + toolset_name: The name of the toolbox toolset to load. |
| 46 | + tool_names: The names of the tools to load. |
| 47 | + The resulting ToolboxToolset will contain both tools loaded by tool_names |
| 48 | + and toolset_name. |
| 49 | + """ |
| 50 | + if not tool_names and not toolset_name: |
| 51 | + raise ValueError("tool_names and toolset_name cannot both be None") |
| 52 | + super().__init__() |
| 53 | + self._server_url = server_url |
| 54 | + self._toolbox_client = toolbox.ToolboxSyncClient(server_url) |
| 55 | + self._toolset_name = toolset_name |
| 56 | + self._tool_names = tool_names |
| 57 | + |
| 58 | + @override |
| 59 | + async def get_tools( |
| 60 | + self, readonly_context: Optional[ReadonlyContext] = None |
| 61 | + ) -> list[BaseTool]: |
| 62 | + tools = [] |
| 63 | + if self._toolset_name: |
| 64 | + tools.extend([ |
| 65 | + FunctionTool(tool) |
| 66 | + for tool in self._toolbox_client.load_toolset(self._toolset_name) |
| 67 | + ]) |
| 68 | + if self._tool_names: |
| 69 | + tools.extend([ |
| 70 | + FunctionTool(self._toolbox_client.load_tool(tool_name)) |
| 71 | + for tool_name in self._tool_names |
| 72 | + ]) |
| 73 | + return tools |
| 74 | + |
| 75 | + @override |
| 76 | + async def close(self): |
| 77 | + self._toolbox_client.close() |
0 commit comments