File size: 8,659 Bytes
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
Function calling tool — calling user-defined functions.

Allows agents to call registered Python functions.
Supports automatic schema extraction from type hints and docstrings.
"""

import inspect
from collections.abc import Callable
from typing import Any, Self, get_type_hints

from .base import BaseTool, ToolResult


def _python_type_to_json_schema(python_type: Any) -> dict[str, Any]:
    """Convert a Python type to a JSON Schema type."""
    type_mapping = {
        str: {"type": "string"},
        int: {"type": "integer"},
        float: {"type": "number"},
        bool: {"type": "boolean"},
        list: {"type": "array"},
        dict: {"type": "object"},
        type(None): {"type": "null"},
    }

    # Handle Optional, Union and other typing constructs
    origin = getattr(python_type, "__origin__", None)
    if origin is not None:
        # List[X], dict[X, Y], etc.
        if origin is list:
            args = getattr(python_type, "__args__", ())
            if args:
                return {"type": "array", "items": _python_type_to_json_schema(args[0])}
            return {"type": "array"}
        if origin is dict:
            return {"type": "object"}
        # Union, Optional
        return {"type": "string"}  # fallback

    return type_mapping.get(python_type, {"type": "string"})


def _extract_parameters_schema(func: Callable) -> dict[str, Any]:
    """Extract the JSON Schema of parameters from a function."""
    try:
        hints = get_type_hints(func)
    except (NameError, AttributeError, TypeError):
        hints = {}

    sig = inspect.signature(func)
    properties = {}
    required = []

    for param_name, param in sig.parameters.items():
        if param_name in ("self", "cls"):
            continue

        param_type = hints.get(param_name, str)
        if param_type is inspect.Parameter.empty:
            param_type = str

        prop = _python_type_to_json_schema(param_type)

        # Try to extract description from docstring
        # (simple heuristic: look for param_name: description)
        properties[param_name] = prop

        if param.default is inspect.Parameter.empty:
            required.append(param_name)

    schema = {
        "type": "object",
        "properties": properties,
    }
    if required:
        schema["required"] = required

    return schema


class FunctionWrapper(BaseTool):
    """
    Wrapper for a Python function as a BaseTool.

    Automatically extracts the name, description, and parameter schema from the function.
    """

    def __init__(
        self,
        func: Callable,
        tool_name: str | None = None,
        tool_description: str | None = None,
    ):
        """
        Create a wrapper for the function.

        Args:
            func: Python function.
            tool_name: Tool name (defaults to the function name).
            tool_description: Description (defaults to the docstring).

        """
        self._func = func
        self._name = tool_name or getattr(func, "__name__", "unnamed")
        self._description = tool_description or getattr(func, "__doc__", None) or f"Function {self._name}"
        self._parameters_schema = _extract_parameters_schema(func)

    @property
    def name(self) -> str:
        return self._name

    @property
    def description(self) -> str:
        return self._description

    @property
    def parameters_schema(self) -> dict[str, Any]:
        return self._parameters_schema

    def execute(self, **kwargs: Any) -> ToolResult:
        """Execute the function with the given arguments."""
        try:
            result = self._func(**kwargs)
            output = str(result) if result is not None else "(no output)"
            return ToolResult(
                tool_name=self.name,
                success=True,
                output=output,
            )
        except (TypeError, ValueError, KeyError, AttributeError) as e:
            return ToolResult(
                tool_name=self.name,
                success=False,
                error=f"Execution error: {e}",
            )


class FunctionTool(BaseTool):
    """
    Manager of user-defined functions as a tool.

    Allows registering multiple functions and calling them by name.
    This is a meta-tool that manages a collection of functions.

    Example:
        tool = FunctionTool()

        @tool.register
        def calculate(expression: str) -> str:
            \"\"\"Evaluate a mathematical expression.\"\"\"
            return str(eval(expression))

        @tool.register
        def uppercase(text: str) -> str:
            \"\"\"Convert text to upper case.\"\"\"
            return text.upper()

        # Call a specific function
        result = tool.execute(function="calculate", expression="2 + 2")

    """

    def __init__(self):
        """Create an empty FunctionTool."""
        self._functions: dict[str, Callable] = {}
        self._wrappers: dict[str, FunctionWrapper] = {}

    @property
    def name(self) -> str:
        return "function_calling"

    @property
    def description(self) -> str:
        func_list = ", ".join(self._functions.keys()) if self._functions else "none"
        return f"Call a registered function. Available functions: {func_list}"

    @property
    def parameters_schema(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "function": {
                    "type": "string",
                    "description": "Name of the function to call",
                    "enum": list(self._functions.keys()) if self._functions else [],
                },
            },
            "required": ["function"],
            "additionalProperties": True,  # Allow function-specific args
        }

    def register(
        self,
        func: Callable | None = None,
        *,
        name: str | None = None,
        description: str | None = None,
    ) -> Callable:
        """
        Register a function. Can be used as a decorator.

        Args:
            func: Function to register.
            name: Function name (defaults to func.__name__).
            description: Description (defaults to the docstring).

        Returns:
            The original function.

        Example:
            @tool.register
            def my_function(arg: str) -> str:
                return arg

            @tool.register(name="custom_name")
            def another(x: int) -> int:
                return x * 2

        """

        def decorator(f: Callable) -> Callable:
            func_name = name or getattr(f, "__name__", "unnamed")
            self._functions[func_name] = f
            self._wrappers[func_name] = FunctionWrapper(
                func=f,
                tool_name=func_name,
                tool_description=description or f.__doc__,
            )
            return f

        if func is not None:
            return decorator(func)
        return decorator

    def add_function(
        self,
        func: Callable,
        name: str | None = None,
        description: str | None = None,
    ) -> Self:
        """
        Add a function (non-decorator way).

        Args:
            func: Function to add.
            name: Function name.
            description: Function description.

        Returns:
            self for method chaining.

        """
        self.register(func, name=name, description=description)
        return self

    def get_function(self, name: str) -> Callable | None:
        """Get a function by name."""
        return self._functions.get(name)

    def list_functions(self) -> list[str]:
        """Get the list of registered function names."""
        return list(self._functions.keys())

    def execute(self, function: str = "", **kwargs: Any) -> ToolResult:
        """
        Execute a registered function.

        Args:
            function: Name of the function to call.
            **kwargs: Function arguments.

        Returns:
            ToolResult with the result.

        """
        if not function:
            return ToolResult(
                tool_name=self.name,
                success=False,
                error="No function name provided",
            )

        wrapper = self._wrappers.get(function)
        if wrapper is None:
            available = ", ".join(self._functions.keys()) or "none"
            return ToolResult(
                tool_name=self.name,
                success=False,
                error=f"Function '{function}' not found. Available: {available}",
            )

        # Call via wrapper (which is already a BaseTool)
        return wrapper.execute(**kwargs)