16
16
17
17
from abc import ABC
18
18
from abc import abstractmethod
19
+ import copy
20
+ from typing import final
19
21
from typing import List
20
22
from typing import Optional
21
23
from typing import Protocol
@@ -58,9 +60,19 @@ class BaseToolset(ABC):
58
60
"""
59
61
60
62
def __init__ (
61
- self , * , tool_filter : Optional [Union [ToolPredicate , List [str ]]] = None
63
+ self ,
64
+ * ,
65
+ tool_filter : Optional [Union [ToolPredicate , List [str ]]] = None ,
66
+ tool_name_prefix : Optional [str ] = None ,
62
67
):
68
+ """Initialize the toolset.
69
+
70
+ Args:
71
+ tool_filter: Filter to apply to tools.
72
+ tool_name_prefix: The prefix to prepend to the names of the tools returned by the toolset.
73
+ """
63
74
self .tool_filter = tool_filter
75
+ self .tool_name_prefix = tool_name_prefix
64
76
65
77
@abstractmethod
66
78
async def get_tools (
@@ -77,6 +89,59 @@ async def get_tools(
77
89
list[BaseTool]: A list of tools available under the specified context.
78
90
"""
79
91
92
+ @final
93
+ async def get_tools_with_prefix (
94
+ self ,
95
+ readonly_context : Optional [ReadonlyContext ] = None ,
96
+ ) -> list [BaseTool ]:
97
+ """Return all tools with optional prefix applied to tool names.
98
+
99
+ This method calls get_tools() and applies prefixing if tool_name_prefix is provided.
100
+
101
+ Args:
102
+ readonly_context (ReadonlyContext, optional): Context used to filter tools
103
+ available to the agent. If None, all tools in the toolset are returned.
104
+
105
+ Returns:
106
+ list[BaseTool]: A list of tools with prefixed names if tool_name_prefix is provided.
107
+ """
108
+ tools = await self .get_tools (readonly_context )
109
+
110
+ if not self .tool_name_prefix :
111
+ return tools
112
+
113
+ prefix = self .tool_name_prefix
114
+
115
+ # Create copies of tools to avoid modifying original instances
116
+ prefixed_tools = []
117
+ for tool in tools :
118
+ # Create a shallow copy of the tool
119
+ tool_copy = copy .copy (tool )
120
+
121
+ # Apply prefix to the copied tool
122
+ prefixed_name = f"{ prefix } _{ tool .name } "
123
+ tool_copy .name = prefixed_name
124
+
125
+ # Also update the function declaration name if the tool has one
126
+ # Use default parameters to capture the current values in the closure
127
+ def _create_prefixed_declaration (
128
+ original_get_declaration = tool ._get_declaration ,
129
+ prefixed_name = prefixed_name ,
130
+ ):
131
+ def _get_prefixed_declaration ():
132
+ declaration = original_get_declaration ()
133
+ if declaration is not None :
134
+ declaration .name = prefixed_name
135
+ return declaration
136
+ return None
137
+
138
+ return _get_prefixed_declaration
139
+
140
+ tool_copy ._get_declaration = _create_prefixed_declaration ()
141
+ prefixed_tools .append (tool_copy )
142
+
143
+ return prefixed_tools
144
+
80
145
async def close (self ) -> None :
81
146
"""Performs cleanup and releases resources held by the toolset.
82
147
0 commit comments