|
| 1 | +import inspect |
| 2 | +from typing import Any, Callable, Optional, Union |
| 3 | + |
| 4 | +from pydantic import BaseModel, PrivateAttr |
| 5 | + |
| 6 | + |
| 7 | +class SkillType(BaseModel): |
| 8 | + """Skill that takes a function usable by pandasai""" |
| 9 | + |
| 10 | + func: Callable[..., Any] |
| 11 | + description: Optional[str] = None |
| 12 | + name: Optional[str] = None |
| 13 | + _signature: Optional[str] = PrivateAttr() |
| 14 | + |
| 15 | + def __init__( |
| 16 | + self, |
| 17 | + func: Callable[..., Any], |
| 18 | + description: Optional[str] = None, |
| 19 | + name: Optional[str] = None, |
| 20 | + **kwargs: Any, |
| 21 | + ) -> None: |
| 22 | + """ |
| 23 | + Initializes the skill. |
| 24 | +
|
| 25 | + Args: |
| 26 | + func: The function from which to create a skill |
| 27 | + description: The description of the skill. |
| 28 | + Defaults to the function docstring. |
| 29 | + name: The name of the function. Mandatory when `func` is a lambda. |
| 30 | + Defaults to the function's name. |
| 31 | + **kwargs: additional params |
| 32 | + """ |
| 33 | + |
| 34 | + name = name or func.__name__ |
| 35 | + description = description or func.__doc__ |
| 36 | + if description is None: |
| 37 | + # if description is None then the function doesn't have a docstring |
| 38 | + # and the user didn't provide any description |
| 39 | + raise ValueError( |
| 40 | + f"Function must have a docstring if no description is provided for skill {name}." |
| 41 | + ) |
| 42 | + signature = f"def {name}{inspect.signature(func)}:" |
| 43 | + |
| 44 | + super(SkillType, self).__init__( |
| 45 | + func=func, description=description, name=name, **kwargs |
| 46 | + ) |
| 47 | + self._signature = signature |
| 48 | + |
| 49 | + def __call__(self, *args, **kwargs) -> Any: |
| 50 | + """Calls the skill function""" |
| 51 | + return self.func(*args, **kwargs) |
| 52 | + |
| 53 | + @classmethod |
| 54 | + def from_function(cls, func: Callable, **kwargs: Any) -> "SkillType": |
| 55 | + """ |
| 56 | + Creates a skill object from a function |
| 57 | +
|
| 58 | + Args: |
| 59 | + func: The function from which to create a skill |
| 60 | +
|
| 61 | + Returns: |
| 62 | + the `Skill` object |
| 63 | +
|
| 64 | + """ |
| 65 | + return cls(func=func, **kwargs) |
| 66 | + |
| 67 | + def stringify(self): |
| 68 | + return inspect.getsource(self.func) |
| 69 | + |
| 70 | + def __str__(self): |
| 71 | + return ( |
| 72 | + f'<function>\n{self._signature}\n """{self.description}"""\n</function>' |
| 73 | + ) |
| 74 | + |
| 75 | + |
| 76 | +def skill(*args: Union[str, Callable]) -> Callable: |
| 77 | + """Decorator to create a skill out of functions and automatically add it to the global skills manager. |
| 78 | + Can be used without arguments. The function must have a docstring. |
| 79 | +
|
| 80 | + Args: |
| 81 | + *args: The arguments to the skill |
| 82 | +
|
| 83 | + Examples: |
| 84 | + .. code-block:: python |
| 85 | +
|
| 86 | + @skill |
| 87 | + def compute_flight_prices(offers: pd.DataFrame) -> List[float]: |
| 88 | + \"\"\"Computes the flight prices\"\"\" |
| 89 | + return |
| 90 | +
|
| 91 | + @skill("custom_name") |
| 92 | + def compute_flight_prices(offers: pd.Dataframe) -> List[float]: |
| 93 | + \"\"\"Computes the flight prices\"\"\" |
| 94 | + return |
| 95 | + """ |
| 96 | + |
| 97 | + def _make_skill_with_name(skill_name: str) -> Callable: |
| 98 | + def _make_skill(skill_fn: Callable) -> SkillType: |
| 99 | + skill_obj = SkillType( |
| 100 | + name=skill_name, # func.__name__ if None |
| 101 | + # when this decorator is used, the function MUST have a docstring |
| 102 | + description=skill_fn.__doc__, |
| 103 | + func=skill_fn, |
| 104 | + ) |
| 105 | + |
| 106 | + # Automatically add the skill to the global skills manager |
| 107 | + try: |
| 108 | + from pandasai.ee.skills.manager import SkillsManager |
| 109 | + |
| 110 | + SkillsManager.add_skills(skill_obj) |
| 111 | + except ImportError: |
| 112 | + # If SkillsManager is not available, just return the skill |
| 113 | + pass |
| 114 | + |
| 115 | + return skill_obj |
| 116 | + |
| 117 | + return _make_skill |
| 118 | + |
| 119 | + if len(args) == 1 and isinstance(args[0], str): |
| 120 | + # Example: @skill("skillName") |
| 121 | + return _make_skill_with_name(args[0]) |
| 122 | + elif len(args) == 1 and callable(args[0]): |
| 123 | + # Example: @skill |
| 124 | + return _make_skill_with_name(args[0].__name__)(args[0]) |
| 125 | + elif not args: |
| 126 | + # Covers the case in which a function is decorated with "@skill()" |
| 127 | + # with the intended behavior of "@skill" |
| 128 | + def _func_wrapper(fn: Callable) -> SkillType: |
| 129 | + return _make_skill_with_name(fn.__name__)(fn) |
| 130 | + |
| 131 | + return _func_wrapper |
| 132 | + else: |
| 133 | + raise ValueError( |
| 134 | + f"Too many arguments for skill decorator. Received: {len(args)}" |
| 135 | + ) |
| 136 | + |
| 137 | + |
| 138 | +__all__ = ["skill", "SkillType"] |
0 commit comments