|
| 1 | +from collections.abc import Callable |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from typing_extensions import Self |
| 6 | + |
| 7 | +from ragbits.core.utils.function_schema import convert_function_to_function_schema, get_context_variable_name |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class OutputCallResult: |
| 12 | + """ |
| 13 | + Filtered results |
| 14 | + """ |
| 15 | + |
| 16 | + id: str |
| 17 | + """Unique identifier of the given output""" |
| 18 | + output_type: str |
| 19 | + """Type of the given output""" |
| 20 | + result: Any |
| 21 | + """Filtered result""" |
| 22 | + |
| 23 | + |
| 24 | +@dataclass |
| 25 | +class OutputFunction: |
| 26 | + """ |
| 27 | + Output function that can be handled by agent |
| 28 | + """ |
| 29 | + |
| 30 | + name: str |
| 31 | + """The name of the output function.""" |
| 32 | + description: str | None |
| 33 | + """Optional description of what the output function does.""" |
| 34 | + parameters: dict[str, Any] |
| 35 | + """Dictionary containing the parameters JSON schema.""" |
| 36 | + on_tool_call: Callable |
| 37 | + """The actual callable function to execute when the tool is called.""" |
| 38 | + context_var_name: str | None = None |
| 39 | + """The name of the context variable that this tool accepts.""" |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def from_callable(cls, callable: Callable) -> Self: |
| 43 | + """ |
| 44 | + Create a OutputFunction instance from a callable function. |
| 45 | +
|
| 46 | + Args: |
| 47 | + callable: The function to convert into a OutputFunction |
| 48 | +
|
| 49 | + Returns: |
| 50 | + A new OutputFunction instance representing the callable function. |
| 51 | + """ |
| 52 | + schema = convert_function_to_function_schema(callable) |
| 53 | + |
| 54 | + return cls( |
| 55 | + name=schema["function"]["name"], |
| 56 | + description=schema["function"]["description"], |
| 57 | + parameters=schema["function"]["parameters"], |
| 58 | + on_tool_call=callable, |
| 59 | + context_var_name=get_context_variable_name(callable), |
| 60 | + ) |
| 61 | + |
| 62 | + def to_function_schema(self) -> dict[str, Any]: |
| 63 | + """ |
| 64 | + Convert the Tool to a standardized function schema format. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + Function schema dictionary with 'type' and 'function' keys. |
| 68 | + """ |
| 69 | + return { |
| 70 | + "type": "function", |
| 71 | + "function": { |
| 72 | + "name": self.name, |
| 73 | + "description": self.description, |
| 74 | + "parameters": self.parameters, |
| 75 | + }, |
| 76 | + } |
0 commit comments