fix(tools): support @tool on class methods #1

Closed
oss-agent-gevtt1b3 wants to merge 1 commit from fix-issue-681-tool-method-self into main
3 changed files with 63 additions and 14 deletions

View file

@ -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:

View file

@ -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

View file

@ -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):