appendix-c

Appendix C. Implementing The PydanticFunctionTool

 

In Chapter 2, we introduced the PydanticFunctionTool and its usage pattern with our framework, as an alternative to our from-scratch SimpleFunctionTool. The main benefits of the PydanticFunctionTool are more robust JSON Schema generation for the associated function’s parameters, as well as more powerful validation through the pydantic library. In this appendix, we provide a walkthrough of the full implementation of the PydanticFunctionTool and its asynchronous version, AsyncPydanticFunctionTool.

The usage pattern for PydanticFunctionTool was first shown at the end of Chapter 2. Specifically, we need a pydantic.BaseModel subclass that represents the function’s parameters, and the function implementation that uses the parameters to perform its logic. For convenience, I’ve provided the sample usage again in the following code snippet.

from pydantic import BaseModel
from llm_agents_from_scratch.tools.pydantic_function import (
    PydanticFunctionTool
)
 
class MyFuncParams(BaseModel):  #A
    x: int
 
 
def my_func(params: MyFuncParams) -> int:  #B
    print(params.x)
 
tool = PydanticFunctionTool(my_func)  #C

C.1 Implementing PydanticFunctionTool

We’ll now build the PydanticFunctionTool wrapper class that enables the usage pattern we just showed.

C.2 The AsyncPydanticFunctionTool