Skip to content

Pydantic Function Tool

Pydantic Function Tool.

PydanticFunction

Bases: Protocol

PydanticFunction Protocol.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
class PydanticFunction(Protocol):
    """PydanticFunction Protocol."""

    __name__: str
    __doc__: str | None

    def __call__(self, params: BaseModel, *args: Any, **kwargs: Any) -> Any:
        """Callable interface.

        Args:
            params (BaseModel): The function's params as a ~pydantic.BaseModel.
            *args (Any): Additional positional arguments.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            Any: The result of the function call.
        """
        ...  # pragma: no cover

__call__

__call__(params, *args, **kwargs)

Callable interface.

Parameters:

Name Type Description Default
params BaseModel

The function's params as a ~pydantic.BaseModel.

required
*args Any

Additional positional arguments.

()
**kwargs Any

Additional keyword arguments.

{}

Returns:

Name Type Description
Any Any

The result of the function call.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
def __call__(self, params: BaseModel, *args: Any, **kwargs: Any) -> Any:
    """Callable interface.

    Args:
        params (BaseModel): The function's params as a ~pydantic.BaseModel.
        *args (Any): Additional positional arguments.
        **kwargs (Any): Additional keyword arguments.

    Returns:
        Any: The result of the function call.
    """
    ...  # pragma: no cover

AsyncPydanticFunction

Bases: Protocol

Asynchronous PydanticFunction Protocol.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
class AsyncPydanticFunction(Protocol):
    """Asynchronous PydanticFunction Protocol."""

    __name__: str
    __doc__: str | None

    async def __call__(
        self,
        params: BaseModel,
        *args: Any,
        **kwargs: Any,
    ) -> Awaitable[Any]:
        """Asynchronous callable interface.

        Args:
            params (BaseModel): The function's params as a ~pydantic.BaseModel.
            *args (Any): Additional positional arguments.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            Awaitable[Any]: The result of the function call.
        """
        ...  # pragma: no cover

__call__ async

__call__(params, *args, **kwargs)

Asynchronous callable interface.

Parameters:

Name Type Description Default
params BaseModel

The function's params as a ~pydantic.BaseModel.

required
*args Any

Additional positional arguments.

()
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
Awaitable[Any]

Awaitable[Any]: The result of the function call.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
async def __call__(
    self,
    params: BaseModel,
    *args: Any,
    **kwargs: Any,
) -> Awaitable[Any]:
    """Asynchronous callable interface.

    Args:
        params (BaseModel): The function's params as a ~pydantic.BaseModel.
        *args (Any): Additional positional arguments.
        **kwargs (Any): Additional keyword arguments.

    Returns:
        Awaitable[Any]: The result of the function call.
    """
    ...  # pragma: no cover

PydanticFunctionTool

Bases: BaseTool

Pydantic function calling tool.

Turn a Python function that takes in a ~pydantic.BaseModel params object into a tool for an LLM.

Attributes:

Name Type Description
func

PydanticFunction to represent as a tool.

params_mdl

The params BaseModel.

desc

Description of the PydanticFunction.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
class PydanticFunctionTool(BaseTool):
    """Pydantic function calling tool.

    Turn a Python function that takes in a ~pydantic.BaseModel params object
    into a tool for an LLM.

    Attributes:
        func: PydanticFunction to represent as a tool.
        params_mdl: The params BaseModel.
        desc: Description of the PydanticFunction.
    """

    def __init__(
        self,
        func: PydanticFunction,
        desc: str | None = None,
    ):
        """Initialize a PydanticFunctionTool.

        Args:
            func (PydanticFunction): The Pydantic function to expose as a tool
                to the LLM.
            desc (str | None, optional): Description of the function.
                Defaults to None.
        """
        self.func = func
        self._desc = desc
        self.params_mdl = _validate_pydantic_function(func)

    @property
    def name(self) -> str:
        """Name of function tool."""
        return self.func.__name__

    @property
    def description(self) -> str:
        """Description of what this function tool does."""
        return (
            self._desc or self.func.__doc__ or f"Tool for {self.func.__name__}"
        )

    @property
    def parameters_json_schema(self) -> dict[str, Any]:
        """JSON schema for tool parameters."""
        return self.params_mdl.model_json_schema()

    def __call__(
        self,
        tool_call: ToolCall,
        *args: Any,
        **kwargs: Any,
    ) -> ToolCallResult:
        """Execute the function tool with a ToolCall.

        Args:
            tool_call (ToolCall): The ToolCall to execute.
            *args (Any): Additional positional arguments.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            ToolCallResult: The result of the tool call execution.
        """
        try:
            params = self.params_mdl.model_validate(tool_call.arguments)
            # execute the function
            res = self.func(params)
            content = str(res)
            error = False
        except Exception as e:
            error_details = {
                "error_type": e.__class__.__name__,
                "message": f"Internal error while executing tool: {str(e)}",
            }
            content = json.dumps(error_details)
            error = True

        return ToolCallResult(
            tool_call_id=tool_call.id_,
            content=content,
            error=error,
        )

name property

name

Name of function tool.

description property

description

Description of what this function tool does.

parameters_json_schema property

parameters_json_schema

JSON schema for tool parameters.

__init__

__init__(func, desc=None)

Initialize a PydanticFunctionTool.

Parameters:

Name Type Description Default
func PydanticFunction

The Pydantic function to expose as a tool to the LLM.

required
desc str | None

Description of the function. Defaults to None.

None
Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
def __init__(
    self,
    func: PydanticFunction,
    desc: str | None = None,
):
    """Initialize a PydanticFunctionTool.

    Args:
        func (PydanticFunction): The Pydantic function to expose as a tool
            to the LLM.
        desc (str | None, optional): Description of the function.
            Defaults to None.
    """
    self.func = func
    self._desc = desc
    self.params_mdl = _validate_pydantic_function(func)

__call__

__call__(tool_call, *args, **kwargs)

Execute the function tool with a ToolCall.

Parameters:

Name Type Description Default
tool_call ToolCall

The ToolCall to execute.

required
*args Any

Additional positional arguments.

()
**kwargs Any

Additional keyword arguments.

{}

Returns:

Name Type Description
ToolCallResult ToolCallResult

The result of the tool call execution.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
def __call__(
    self,
    tool_call: ToolCall,
    *args: Any,
    **kwargs: Any,
) -> ToolCallResult:
    """Execute the function tool with a ToolCall.

    Args:
        tool_call (ToolCall): The ToolCall to execute.
        *args (Any): Additional positional arguments.
        **kwargs (Any): Additional keyword arguments.

    Returns:
        ToolCallResult: The result of the tool call execution.
    """
    try:
        params = self.params_mdl.model_validate(tool_call.arguments)
        # execute the function
        res = self.func(params)
        content = str(res)
        error = False
    except Exception as e:
        error_details = {
            "error_type": e.__class__.__name__,
            "message": f"Internal error while executing tool: {str(e)}",
        }
        content = json.dumps(error_details)
        error = True

    return ToolCallResult(
        tool_call_id=tool_call.id_,
        content=content,
        error=error,
    )

AsyncPydanticFunctionTool

Bases: AsyncBaseTool

Async Pydantic function calling tool.

Turn an async Python function that takes in a ~pydantic.BaseModel params object into a tool for an LLM.

Attributes:

Name Type Description
func

AsyncPydanticFunction to represent as a tool.

params_mdl

The params BaseModel.

desc

Description of the PydanticFunction.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
class AsyncPydanticFunctionTool(AsyncBaseTool):
    """Async Pydantic function calling tool.

    Turn an async Python function that takes in a ~pydantic.BaseModel params
    object into a tool for an LLM.

    Attributes:
        func: AsyncPydanticFunction to represent as a tool.
        params_mdl: The params BaseModel.
        desc: Description of the PydanticFunction.
    """

    def __init__(
        self,
        func: AsyncPydanticFunction,
        desc: str | None = None,
    ):
        """Initialize an AsyncPydanticFunctionTool.

        Args:
            func (AsyncPydanticFunction): The async Pydantic function to expose
                as a tool to the LLM.
            desc (str | None, optional): Description of the function.
                Defaults to None.
        """
        self.func = func
        self._desc = desc
        self.params_mdl = _validate_pydantic_function(func)

    @property
    def name(self) -> str:
        """Name of function tool."""
        return self.func.__name__

    @property
    def description(self) -> str:
        """Description of what this function tool does."""
        return (
            self._desc or self.func.__doc__ or f"Tool for {self.func.__name__}"
        )

    @property
    def parameters_json_schema(self) -> dict[str, Any]:
        """JSON schema for tool parameters."""
        return self.params_mdl.model_json_schema()

    async def __call__(
        self,
        tool_call: ToolCall,
        *args: Any,
        **kwargs: Any,
    ) -> ToolCallResult:
        """Execute the function tool with a ToolCall.

        Args:
            tool_call (ToolCall): The ToolCall to execute.
            *args (Any): Additional positional arguments.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            ToolCallResult: The result of the tool call execution.
        """
        try:
            params = self.params_mdl.model_validate(tool_call.arguments)
            # execute the function
            res = await self.func(params)
            content = str(res)
            error = False
        except Exception as e:
            error_details = {
                "error_type": e.__class__.__name__,
                "message": f"Internal error while executing tool: {str(e)}",
            }
            content = json.dumps(error_details)
            error = True

        return ToolCallResult(
            tool_call_id=tool_call.id_,
            content=content,
            error=error,
        )

name property

name

Name of function tool.

description property

description

Description of what this function tool does.

parameters_json_schema property

parameters_json_schema

JSON schema for tool parameters.

__init__

__init__(func, desc=None)

Initialize an AsyncPydanticFunctionTool.

Parameters:

Name Type Description Default
func AsyncPydanticFunction

The async Pydantic function to expose as a tool to the LLM.

required
desc str | None

Description of the function. Defaults to None.

None
Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
def __init__(
    self,
    func: AsyncPydanticFunction,
    desc: str | None = None,
):
    """Initialize an AsyncPydanticFunctionTool.

    Args:
        func (AsyncPydanticFunction): The async Pydantic function to expose
            as a tool to the LLM.
        desc (str | None, optional): Description of the function.
            Defaults to None.
    """
    self.func = func
    self._desc = desc
    self.params_mdl = _validate_pydantic_function(func)

__call__ async

__call__(tool_call, *args, **kwargs)

Execute the function tool with a ToolCall.

Parameters:

Name Type Description Default
tool_call ToolCall

The ToolCall to execute.

required
*args Any

Additional positional arguments.

()
**kwargs Any

Additional keyword arguments.

{}

Returns:

Name Type Description
ToolCallResult ToolCallResult

The result of the tool call execution.

Source code in src/llm_agents_from_scratch/tools/pydantic_function.py
async def __call__(
    self,
    tool_call: ToolCall,
    *args: Any,
    **kwargs: Any,
) -> ToolCallResult:
    """Execute the function tool with a ToolCall.

    Args:
        tool_call (ToolCall): The ToolCall to execute.
        *args (Any): Additional positional arguments.
        **kwargs (Any): Additional keyword arguments.

    Returns:
        ToolCallResult: The result of the tool call execution.
    """
    try:
        params = self.params_mdl.model_validate(tool_call.arguments)
        # execute the function
        res = await self.func(params)
        content = str(res)
        error = False
    except Exception as e:
        error_details = {
            "error_type": e.__class__.__name__,
            "message": f"Internal error while executing tool: {str(e)}",
        }
        content = json.dumps(error_details)
        error = True

    return ToolCallResult(
        tool_call_id=tool_call.id_,
        content=content,
        error=error,
    )