From 0952b40cc1ad35eea8737799c0d519f6da3ac716 Mon Sep 17 00:00:00 2001 From: oss-agent-gevtt1b3 Date: Mon, 30 Nov 2026 06:15:16 +0000 Subject: [PATCH] fix(tools): support @tool on class methods Skip self when generating JSON schemas and bind method tools to their instance via a descriptor. Add a regression test covering method tools. Co-Authored-By: Claude Fable 5 --- src/smolagents/_function_type_hints_utils.py | 4 ++ src/smolagents/tools.py | 49 ++++++++++++++------ tests/test_tools.py | 24 ++++++++++ 3 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/smolagents/_function_type_hints_utils.py b/src/smolagents/_function_type_hints_utils.py index e8102ead..82345815 100644 --- a/src/smolagents/_function_type_hints_utils.py +++ b/src/smolagents/_function_type_hints_utils.py @@ -294,10 +294,14 @@ def _convert_type_hints_to_json_schema(func: Callable, error_on_missing_type_hin properties = {} for param_name, param_type in type_hints.items(): + if param_name == "self": + continue properties[param_name] = _parse_type_hint(param_type) required = [] for param_name, param in signature.parameters.items(): + if param_name == "self": + continue if param.annotation == inspect.Parameter.empty and error_on_missing_type_hints: raise TypeHintParsingException(f"Argument {param.name} is missing a type hint in function {func.__name__}") if param_name not in properties: diff --git a/src/smolagents/tools.py b/src/smolagents/tools.py index 931acfec..273c2017 100644 --- a/src/smolagents/tools.py +++ b/src/smolagents/tools.py @@ -1058,16 +1058,7 @@ class ToolCollection: yield cls(tools) -def tool(tool_function: Callable) -> Tool: - """ - Convert a function into an instance of a dynamically created Tool subclass. - - Args: - tool_function (`Callable`): Function to convert into a Tool subclass. - Should have type hints for each input and a type hint for the output. - Should also have a docstring including the description of the function - and an 'Args:' part where each argument is described. - """ +def _create_tool_from_function(tool_function: Callable) -> Tool: tool_json_schema = get_json_schema(tool_function)["function"] if "return" not in tool_json_schema: if len(tool_json_schema["parameters"]["properties"]) == 0: @@ -1102,10 +1093,11 @@ def tool(tool_function: Callable) -> Tool: # Get the signature parameters of the tool function sig = inspect.signature(tool_function) - # - Add "self" as first parameter to tool_function signature - new_sig = sig.replace( - parameters=[inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD)] + list(sig.parameters.values()) - ) + # - Add "self" as first parameter to tool_function signature if it is not already present + parameters = list(sig.parameters.values()) + if not parameters or parameters[0].name != "self": + parameters = [inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD)] + parameters + new_sig = sig.replace(parameters=parameters) # - Set the signature of the forward method SimpleTool.forward.__signature__ = new_sig @@ -1168,6 +1160,35 @@ def tool(tool_function: Callable) -> Tool: return simple_tool +class _MethodToolDescriptor: + """Descriptor that binds a tool created from a method to the instance.""" + + def __init__(self, tool_function: Callable): + self.tool_function = tool_function + + def __get__(self, instance, owner=None): + if instance is None: + return self + bound_function = types.MethodType(self.tool_function, instance) + return _create_tool_from_function(bound_function) + + +def tool(tool_function: Callable) -> Tool: + """ + Convert a function into an instance of a dynamically created Tool subclass. + + Args: + tool_function (`Callable`): Function to convert into a Tool subclass. + Should have type hints for each input and a type hint for the output. + Should also have a docstring including the description of the function + and an 'Args:' part where each argument is described. + """ + sig = inspect.signature(tool_function) + if sig.parameters and next(iter(sig.parameters.values())).name == "self": + return _MethodToolDescriptor(tool_function) + return _create_tool_from_function(tool_function) + + class PipelineTool(Tool): """ A [`Tool`] tailored towards Transformer models. On top of the class attributes of the base class [`Tool`], you will diff --git a/tests/test_tools.py b/tests/test_tools.py index 8e31cf6d..1cd2f452 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -657,6 +657,30 @@ class TestTool: assert isinstance(union_type_return_tool_function, Tool) assert union_type_return_tool_function.output_type == "any" + def test_tool_decorator_on_method(self): + class Calculator: + def __init__(self, base: int): + self.base = base + + @tool + def add(self, x: int) -> int: + """ + Add a number to the base. + + Args: + x: The number to add. + """ + return self.base + x + + calculator = Calculator(10) + method_tool = calculator.add + + assert isinstance(method_tool, Tool) + assert "self" not in method_tool.inputs + assert list(method_tool.inputs.keys()) == ["x"] + assert method_tool(x=5) == 15 + assert method_tool(x=20) == 30 + class TestToolDecorator: def test_tool_decorator_source_extraction_with_multiple_decorators(self): -- 2.47.3