Create a New Tool
This guide will walk you through creating a new FunctionTool
to compute the nth Fibonacci number.
Import the Required Modules
Begin by importing the necessary modules to create the tool. Create a new Python file titled main.py
and add the following import statements:
from npiai import FunctionTool, function
Define the Tool Class
Next, define the MyTool
class that inherits from FunctionTool
. In the class constructor, specify the tool's name and description.
from npiai import FunctionTool, function
class MyTool(FunctionTool):
def __init__(self):
super().__init__(
name='my_tool',
description='test tool',
)
Implement the Fibonacci Function
Add the fibonacci
function to the MyTool
class. This function calculates the nth Fibonacci number recursively.
from npiai import FunctionTool, function
class MyTool(FunctionTool):
def __init__(self):
super().__init__(
name='my_tool',
description='test tool',
)
def fibonacci(self, n):
if n == 0:
return 0
if n == 1:
return 1
return self.fibonacci(n - 1) + self.fibonacci(n - 2)
Add Type Hints and Docstrings
Type hints and docstrings are essential for NPi to generate function schemas. Add type hints to the fibonacci
function's parameters, and include a docstring describing the function's purpose and arguments:
from npiai import FunctionTool, function
class MyTool(FunctionTool):
def __init__(self):
super().__init__(
name='my_tool',
description='test tool',
)
def fibonacci(self, n: int) -> int:
"""
Get the nth Fibonacci number.
Args:
n: The index of the Fibonacci number in the sequence.
"""
if n == 0:
return 0
if n == 1:
return 1
return self.fibonacci(n - 1) + self.fibonacci(n - 2)
Annotated the Function with @function
Annotate the fibonacci
function with the @function
decorator to indicate that it is a LLM-callable function within the tool.
from npiai import FunctionTool, function
class MyTool(FunctionTool):
def __init__(self):
super().__init__(
name='my_tool',
description='test tool',
)
@function
def fibonacci(self, n: int) -> int:
"""
Get the nth Fibonacci number.
Args:
n: The index of the Fibonacci number in the sequence.
"""
if n == 0:
return 0
if n == 1:
return 1
return self.fibonacci(n - 1) + self.fibonacci(n - 2)
Run the Tool
Finally, we can now run the tool in function mode
or agent mode
to interact with it. Refer to the Function Mode and Agent Mode section for detailed instructions.
async def main():
async with MyTool() as my_tool:
# do something with my_tool.tools
print(my_tool.tools)
if __name__ == '__main__':
import asyncio
asyncio.run(main())
Note that the above example uses the context manager (opens in a new tab) to automatically starts and ends the tool. You can also manually start and stop the tool using the start()
and stop()
methods:
async def main():
my_tool = MyTool()
await my_tool.start()
# do something with my_tool.tools
print(my_tool.tools)
await my_tool.end()
if __name__ == '__main__':
import asyncio
asyncio.run(main())