in src/smolagents/tools.py [0:0]
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.
"""
tool_json_schema = get_json_schema(tool_function)["function"]
if "return" not in tool_json_schema:
raise TypeHintParsingException("Tool return type not found: make sure your function has a return type hint!")
class SimpleTool(Tool):
def __init__(self):
self.is_initialized = True
# Set the class attributes
SimpleTool.name = tool_json_schema["name"]
SimpleTool.description = tool_json_schema["description"]
SimpleTool.inputs = tool_json_schema["parameters"]["properties"]
SimpleTool.output_type = tool_json_schema["return"]["type"]
@wraps(tool_function)
def wrapped_function(*args, **kwargs):
return tool_function(*args, **kwargs)
# Bind the copied function to the forward method
SimpleTool.forward = staticmethod(wrapped_function)
# 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())
)
# - Set the signature of the forward method
SimpleTool.forward.__signature__ = new_sig
# Create and attach the source code of the dynamically created tool class and forward method
# - Get the source code of tool_function
tool_source = inspect.getsource(tool_function)
# - Remove the tool decorator and function definition line
tool_source_body = "\n".join(tool_source.split("\n")[2:])
# - Dedent
tool_source_body = textwrap.dedent(tool_source_body)
# - Create the forward method source, including def line and indentation
forward_method_source = f"def forward{str(new_sig)}:\n{textwrap.indent(tool_source_body, ' ')}"
# - Create the class source
class_source = (
textwrap.dedent(f"""