Create tool from a given function. A classmethod that helps to create a tool from a function. Args: func: The function from which to create a tool coroutine: The async function from which to create a tool name: The name of the tool. Defaults to t
(
cls,
func: Optional[Callable] = None,
coroutine: Optional[Callable[..., Awaitable[Any]]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
return_direct: bool = False,
args_schema: Optional[Type[BaseModel]] = None,
infer_schema: bool = True,
**kwargs: Any,
)
| 306 | |
| 307 | @classmethod |
| 308 | def from_function( |
| 309 | cls, |
| 310 | func: Optional[Callable] = None, |
| 311 | coroutine: Optional[Callable[..., Awaitable[Any]]] = None, |
| 312 | name: Optional[str] = None, |
| 313 | description: Optional[str] = None, |
| 314 | return_direct: bool = False, |
| 315 | args_schema: Optional[Type[BaseModel]] = None, |
| 316 | infer_schema: bool = True, |
| 317 | **kwargs: Any, |
| 318 | ) -> StructuredTool: |
| 319 | """Create tool from a given function. |
| 320 | |
| 321 | A classmethod that helps to create a tool from a function. |
| 322 | |
| 323 | Args: |
| 324 | func: The function from which to create a tool |
| 325 | coroutine: The async function from which to create a tool |
| 326 | name: The name of the tool. Defaults to the function name |
| 327 | description: The description of the tool. Defaults to the function docstring |
| 328 | return_direct: Whether to return the result directly or as a callback |
| 329 | args_schema: The schema of the tool's input arguments |
| 330 | infer_schema: Whether to infer the schema from the function's signature |
| 331 | **kwargs: Additional arguments to pass to the tool |
| 332 | |
| 333 | Returns: |
| 334 | The tool |
| 335 | |
| 336 | Examples: |
| 337 | |
| 338 | .. code-block:: python |
| 339 | |
| 340 | def add(a: int, b: int) -> int: |
| 341 | \"\"\"Add two numbers\"\"\" |
| 342 | return a + b |
| 343 | tool = StructuredTool.from_function(add) |
| 344 | tool.run(1, 2) # 3 |
| 345 | """ |
| 346 | |
| 347 | if func is not None: |
| 348 | source_function = func |
| 349 | elif coroutine is not None: |
| 350 | source_function = coroutine |
| 351 | else: |
| 352 | raise ValueError("Function and/or coroutine must be provided") |
| 353 | name = name or source_function.__name__ |
| 354 | description = description or source_function.__doc__ |
| 355 | if description is None: |
| 356 | raise ValueError( |
| 357 | "Function must have a docstring if description not provided." |
| 358 | ) |
| 359 | |
| 360 | # Description example: |
| 361 | # search_api(query: str) - Searches the API for the query. |
| 362 | sig = signature(source_function) |
| 363 | description = f"{name}{sig} - {description.strip()}" |
| 364 | _args_schema = args_schema |
| 365 | if _args_schema is None and infer_schema: |
nothing calls this directly
no test coverage detected