Skip to content

tools

Class info

Re-exported classes

Class Module Description
LLMCallableTool llmling.tools.base LLMCallableTool(callable: collections.abc.Callable[P, TReturnType], name: str, description: str = '', import_path: str
ToolError llmling.tools.exceptions Base exception for tool-related errors.
ToolExecutionError llmling.tools.exceptions Error during tool execution.
ToolRegistry llmling.tools.registry Registry for functions that can be called by LLMs.

🛈 DocStrings

Tool system for LLMling.

LLMCallableTool dataclass

Source code in src/llmling/tools/base.py
@dataclass
class LLMCallableTool[**P, TReturnType]:
    supported_mime_types: ClassVar[list[str]] = ["text/plain"]
    callable: Callable[P, TReturnType]
    name: str
    description: str = ""
    import_path: str | None = None
    schema_override: schemez.OpenAIFunctionDefinition | None = None
    hints: ToolHints | None = None

    @classmethod
    def from_callable(
        cls,
        fn: Callable[P, TReturnType] | str,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
        hints: ToolHints | None = None,
    ) -> Self:
        """Create a tool from a callable or import path."""
        if isinstance(fn, str):
            import_path = fn
            from llmling.utils import importing

            callable_obj = importing.import_callable(fn)
            name = getattr(callable_obj, "__name__", "unknown")
            import_path = fn
        else:
            callable_obj = fn
            module = fn.__module__
            if hasattr(fn, "__qualname__"):  # Regular function
                name = getattr(fn, "__name__", fn.__class__.__name__)
                import_path = f"{module}.{fn.__qualname__}"
            else:  # Instance with __call__ method
                name = fn.__class__.__name__
                import_path = f"{module}.{fn.__class__.__qualname__}"

        return cls(
            callable=callable_obj,
            name=name_override or name,
            description=description_override or inspect.getdoc(callable_obj) or "",
            import_path=import_path,
            schema_override=schema_override,
            hints=hints,
        )

    @classmethod
    def from_crewai_tool(
        cls,
        tool: Any,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
    ) -> Self:
        """Allows importing crewai / langchain tools."""
        try:
            from crewai.tools import BaseTool as CrewAiBaseTool
        except ImportError as e:
            msg = "crewai package not found. Please install it with 'pip install crewai'"
            raise ImportError(msg) from e

        if not isinstance(tool, CrewAiBaseTool):
            msg = f"Expected CrewAI BaseTool, got {type(tool)}"
            raise TypeError(msg)

        return cls.from_callable(
            tool._run,
            name_override=name_override or tool.__class__.__name__.removesuffix("Tool"),
            description_override=description_override or tool.description,
            schema_override=schema_override,
        )

    @classmethod
    def from_langchain_tool(
        cls,
        tool: Any,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
    ) -> Self:
        """Create a tool from a LangChain tool."""
        try:
            from langchain_core.tools import BaseTool as LangChainBaseTool
        except ImportError as e:
            msg = "langchain-core package not found."
            raise ImportError(msg) from e

        if not isinstance(tool, LangChainBaseTool):
            msg = f"Expected LangChain BaseTool, got {type(tool)}"
            raise TypeError(msg)

        return cls.from_callable(
            tool.invoke,
            name_override=name_override or tool.name,
            description_override=description_override or tool.description,
            schema_override=schema_override,
        )

    @classmethod
    def from_autogen_tool(
        cls,
        tool: Any,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
    ) -> Self:
        """Create a tool from a AutoGen tool."""
        try:
            from autogen_core import CancellationToken
            from autogen_core.tools import BaseTool
        except ImportError as e:
            msg = "autogent_core package not found."
            raise ImportError(msg) from e

        if not isinstance(tool, BaseTool):
            msg = f"Expected AutoGent BaseTool, got {type(tool)}"
            raise TypeError(msg)
        token = CancellationToken()

        input_model = tool.__class__.__orig_bases__[0].__args__[0]

        name = name_override or tool.name or tool.__class__.__name__.removesuffix("Tool")
        description = (
            description_override or tool.description or inspect.getdoc(tool.__class__) or ""
        )

        async def wrapper(**kwargs: Any) -> Any:
            # Convert kwargs to the expected input model
            model = input_model(**kwargs)
            return await tool.run(model, cancellation_token=token)

        return cls.from_callable(
            wrapper,  # type: ignore
            name_override=name,
            description_override=description,
            schema_override=schema_override,
        )

    async def execute(self, *args: P.args, **kwargs: P.kwargs) -> TReturnType:
        """Execute the wrapped callable."""
        if inspect.iscoroutinefunction(self.callable):
            return await self.callable(*args, **kwargs)
        return self.callable(*args, **kwargs)

    def get_schema(self) -> schemez.OpenAIFunctionTool:
        """Get OpenAI function schema."""
        schema = schemez.create_schema(self.callable).model_dump_openai()
        schema["function"]["name"] = self.name
        schema["function"]["description"] = self.description
        if self.schema_override:
            schema["function"] = self.schema_override
        return schema

execute async

execute(*args: P.args, **kwargs: P.kwargs) -> TReturnType

Execute the wrapped callable.

Source code in src/llmling/tools/base.py
async def execute(self, *args: P.args, **kwargs: P.kwargs) -> TReturnType:
    """Execute the wrapped callable."""
    if inspect.iscoroutinefunction(self.callable):
        return await self.callable(*args, **kwargs)
    return self.callable(*args, **kwargs)

from_autogen_tool classmethod

from_autogen_tool(
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None
) -> Self

Create a tool from a AutoGen tool.

Source code in src/llmling/tools/base.py
@classmethod
def from_autogen_tool(
    cls,
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
) -> Self:
    """Create a tool from a AutoGen tool."""
    try:
        from autogen_core import CancellationToken
        from autogen_core.tools import BaseTool
    except ImportError as e:
        msg = "autogent_core package not found."
        raise ImportError(msg) from e

    if not isinstance(tool, BaseTool):
        msg = f"Expected AutoGent BaseTool, got {type(tool)}"
        raise TypeError(msg)
    token = CancellationToken()

    input_model = tool.__class__.__orig_bases__[0].__args__[0]

    name = name_override or tool.name or tool.__class__.__name__.removesuffix("Tool")
    description = (
        description_override or tool.description or inspect.getdoc(tool.__class__) or ""
    )

    async def wrapper(**kwargs: Any) -> Any:
        # Convert kwargs to the expected input model
        model = input_model(**kwargs)
        return await tool.run(model, cancellation_token=token)

    return cls.from_callable(
        wrapper,  # type: ignore
        name_override=name,
        description_override=description,
        schema_override=schema_override,
    )

from_callable classmethod

from_callable(
    fn: Callable[P, TReturnType] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None,
    hints: ToolHints | None = None
) -> Self

Create a tool from a callable or import path.

Source code in src/llmling/tools/base.py
@classmethod
def from_callable(
    cls,
    fn: Callable[P, TReturnType] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
    hints: ToolHints | None = None,
) -> Self:
    """Create a tool from a callable or import path."""
    if isinstance(fn, str):
        import_path = fn
        from llmling.utils import importing

        callable_obj = importing.import_callable(fn)
        name = getattr(callable_obj, "__name__", "unknown")
        import_path = fn
    else:
        callable_obj = fn
        module = fn.__module__
        if hasattr(fn, "__qualname__"):  # Regular function
            name = getattr(fn, "__name__", fn.__class__.__name__)
            import_path = f"{module}.{fn.__qualname__}"
        else:  # Instance with __call__ method
            name = fn.__class__.__name__
            import_path = f"{module}.{fn.__class__.__qualname__}"

    return cls(
        callable=callable_obj,
        name=name_override or name,
        description=description_override or inspect.getdoc(callable_obj) or "",
        import_path=import_path,
        schema_override=schema_override,
        hints=hints,
    )

from_crewai_tool classmethod

from_crewai_tool(
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None
) -> Self

Allows importing crewai / langchain tools.

Source code in src/llmling/tools/base.py
@classmethod
def from_crewai_tool(
    cls,
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
) -> Self:
    """Allows importing crewai / langchain tools."""
    try:
        from crewai.tools import BaseTool as CrewAiBaseTool
    except ImportError as e:
        msg = "crewai package not found. Please install it with 'pip install crewai'"
        raise ImportError(msg) from e

    if not isinstance(tool, CrewAiBaseTool):
        msg = f"Expected CrewAI BaseTool, got {type(tool)}"
        raise TypeError(msg)

    return cls.from_callable(
        tool._run,
        name_override=name_override or tool.__class__.__name__.removesuffix("Tool"),
        description_override=description_override or tool.description,
        schema_override=schema_override,
    )

from_langchain_tool classmethod

from_langchain_tool(
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None
) -> Self

Create a tool from a LangChain tool.

Source code in src/llmling/tools/base.py
@classmethod
def from_langchain_tool(
    cls,
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
) -> Self:
    """Create a tool from a LangChain tool."""
    try:
        from langchain_core.tools import BaseTool as LangChainBaseTool
    except ImportError as e:
        msg = "langchain-core package not found."
        raise ImportError(msg) from e

    if not isinstance(tool, LangChainBaseTool):
        msg = f"Expected LangChain BaseTool, got {type(tool)}"
        raise TypeError(msg)

    return cls.from_callable(
        tool.invoke,
        name_override=name_override or tool.name,
        description_override=description_override or tool.description,
        schema_override=schema_override,
    )

get_schema

get_schema() -> OpenAIFunctionTool

Get OpenAI function schema.

Source code in src/llmling/tools/base.py
def get_schema(self) -> schemez.OpenAIFunctionTool:
    """Get OpenAI function schema."""
    schema = schemez.create_schema(self.callable).model_dump_openai()
    schema["function"]["name"] = self.name
    schema["function"]["description"] = self.description
    if self.schema_override:
        schema["function"] = self.schema_override
    return schema

ToolError

Bases: LLMLingError

Base exception for tool-related errors.

Source code in src/llmling/tools/exceptions.py
class ToolError(LLMLingError):
    """Base exception for tool-related errors."""

ToolExecutionError

Bases: ToolError

Error during tool execution.

Source code in src/llmling/tools/exceptions.py
class ToolExecutionError(ToolError):
    """Error during tool execution."""

ToolRegistry

Bases: BaseRegistry[str, LLMCallableTool]

Registry for functions that can be called by LLMs.

Source code in src/llmling/tools/registry.py
class ToolRegistry(BaseRegistry[str, LLMCallableTool]):
    """Registry for functions that can be called by LLMs."""

    @property
    def _error_class(self) -> type[ToolError]:
        """Error class to use for this registry."""
        return ToolError

    def _validate_item(self, item: Any) -> LLMCallableTool:  # noqa: PLR0911
        """Validate and transform item into a LLMCallableTool."""
        from llmling.config.models import ToolConfig

        match item:
            case LLMCallableTool():
                return item
            case ToolConfig():  # Handle Pydantic models
                try:
                    obj_class = importing.import_class(item.import_path)

                    # Check for crewai tools
                    if importlib.util.find_spec("crewai"):
                        from crewai.tools import BaseTool as CrewAiBaseTool

                        if issubclass(obj_class, CrewAiBaseTool):
                            return LLMCallableTool.from_crewai_tool(
                                obj_class(
                                    name=obj_class.__name__,
                                    description=obj_class.description,
                                ),
                                name_override=item.name,
                                description_override=item.description,
                            )

                    # Check for langchain tools
                    if importlib.util.find_spec("langchain_core"):
                        from langchain_core.tools import BaseTool as LangChainBaseTool

                        if issubclass(obj_class, LangChainBaseTool):
                            return LLMCallableTool.from_langchain_tool(
                                obj_class(),
                                name_override=item.name,
                                description_override=item.description,
                            )
                    # Either it wasn't a class or wasn't a crewai tool - treat as callable
                    return LLMCallableTool.from_callable(
                        item.import_path,
                        name_override=item.name,
                        description_override=item.description,
                    )
                except Exception:  # noqa: BLE001
                    fn = importing.import_callable(item.import_path)
                    return LLMCallableTool.from_callable(fn)
            case dict() if "import_path" in item:  # Config dict
                return LLMCallableTool.from_callable(
                    item["import_path"],
                    name_override=item.get("name"),
                    description_override=item.get("description"),
                )
            case str():  # Import path
                return LLMCallableTool.from_callable(item)
            # Add new support for callables
            case _ if callable(item):
                return LLMCallableTool.from_callable(item)
            case _:
                # Check for crewai tool instances
                if importlib.util.find_spec("crewai"):
                    from crewai.tools import BaseTool as CrewAiBaseTool

                    if isinstance(item, CrewAiBaseTool):
                        return LLMCallableTool.from_crewai_tool(item)

                # Check for langchain tool instances
                if importlib.util.find_spec("langchain_core"):
                    from langchain_core.tools import BaseTool as LangChainBaseTool

                    if isinstance(item, LangChainBaseTool):
                        return LLMCallableTool.from_langchain_tool(item)

                msg = f"Invalid tool type: {type(item)}"
                raise ToolError(msg)

    def add_container(
        self,
        obj: type | ModuleType | Any,
        *,
        prefix: str = "",
        include_imported: bool = False,
    ) -> None:
        """Register all public callable members from a Python object.

        Args:
            obj: Any Python object to inspect (module, class, instance)
            prefix: Optional prefix for registered function names
            include_imported: Whether to include imported/inherited callables
        """
        for name, func in importing.get_pyobject_members(
            obj,
            include_imported=include_imported,
        ):
            self.register(f"{prefix}{name}", func)
            logger.debug("Registered callable %s as %s", name, f"{prefix}{name}")

    def get_schemas(self) -> list[schemez.OpenAIFunctionTool]:
        """Get schemas for all registered functions.

        Returns:
            List of OpenAI function schemas
        """
        return [tool.get_schema() for tool in self._items.values()]

    async def execute(self, _name: str, **params: Any) -> Any:
        """Execute a registered function.

        Args:
            _name: Name of the function to execute
            **params: Parameters to pass to the function

        Returns:
            Function result

        Raises:
            ToolNotFoundError: If function not found
            ToolError: If execution fails
        """
        try:
            tool = self.get(_name)
        except KeyError as exc:
            msg = f"Function {_name} not found"
            raise ToolNotFoundError(msg) from exc

        # Let the original exception propagate
        return await tool.execute(**params)

add_container

add_container(
    obj: type | ModuleType | Any, *, prefix: str = "", include_imported: bool = False
) -> None

Register all public callable members from a Python object.

Parameters:

Name Type Description Default
obj type | ModuleType | Any

Any Python object to inspect (module, class, instance)

required
prefix str

Optional prefix for registered function names

''
include_imported bool

Whether to include imported/inherited callables

False
Source code in src/llmling/tools/registry.py
def add_container(
    self,
    obj: type | ModuleType | Any,
    *,
    prefix: str = "",
    include_imported: bool = False,
) -> None:
    """Register all public callable members from a Python object.

    Args:
        obj: Any Python object to inspect (module, class, instance)
        prefix: Optional prefix for registered function names
        include_imported: Whether to include imported/inherited callables
    """
    for name, func in importing.get_pyobject_members(
        obj,
        include_imported=include_imported,
    ):
        self.register(f"{prefix}{name}", func)
        logger.debug("Registered callable %s as %s", name, f"{prefix}{name}")

execute async

execute(_name: str, **params: Any) -> Any

Execute a registered function.

Parameters:

Name Type Description Default
_name str

Name of the function to execute

required
**params Any

Parameters to pass to the function

{}

Returns:

Type Description
Any

Function result

Raises:

Type Description
ToolNotFoundError

If function not found

ToolError

If execution fails

Source code in src/llmling/tools/registry.py
async def execute(self, _name: str, **params: Any) -> Any:
    """Execute a registered function.

    Args:
        _name: Name of the function to execute
        **params: Parameters to pass to the function

    Returns:
        Function result

    Raises:
        ToolNotFoundError: If function not found
        ToolError: If execution fails
    """
    try:
        tool = self.get(_name)
    except KeyError as exc:
        msg = f"Function {_name} not found"
        raise ToolNotFoundError(msg) from exc

    # Let the original exception propagate
    return await tool.execute(**params)

get_schemas

get_schemas() -> list[OpenAIFunctionTool]

Get schemas for all registered functions.

Returns:

Type Description
list[OpenAIFunctionTool]

List of OpenAI function schemas

Source code in src/llmling/tools/registry.py
def get_schemas(self) -> list[schemez.OpenAIFunctionTool]:
    """Get schemas for all registered functions.

    Returns:
        List of OpenAI function schemas
    """
    return [tool.get_schema() for tool in self._items.values()]