|
| 1 | +from langchain_core.tools import tool |
| 2 | + |
| 3 | +# Custom tools |
| 4 | +@tool |
| 5 | +def add(x: int, y: int) -> int: |
| 6 | + """Adds two numbers.""" |
| 7 | + return x + y |
| 8 | + |
| 9 | +@tool |
| 10 | +def subtract(x: int, y: int) -> int: |
| 11 | + """Subtracts two numbers.""" |
| 12 | + return x - y |
| 13 | + |
| 14 | +@tool |
| 15 | +def multiply(x: int, y: int) -> int: |
| 16 | + """Multiplies two numbers.""" |
| 17 | + return x * y |
| 18 | + |
| 19 | +@tool |
| 20 | +def divide(x: int, y: int) -> float: |
| 21 | + """Divides two numbers.""" |
| 22 | + return x / y |
| 23 | + |
| 24 | +@tool |
| 25 | +def power(x: int, y: int) -> int: |
| 26 | + """Raises x to the power of y.""" |
| 27 | + return x ** y |
| 28 | + |
| 29 | +def calculate_factorial(n: int) -> int: |
| 30 | + """Calculates the factorial of n.""" |
| 31 | + if n < 0: |
| 32 | + raise ValueError("Factorial is not defined for negative numbers.") |
| 33 | + if n == 0 or n == 1: |
| 34 | + return 1 |
| 35 | + return n * calculate_factorial(n - 1) |
| 36 | +@tool |
| 37 | +def factorial(x: int) -> int: |
| 38 | + """Calculates the factorial of x.""" |
| 39 | + return calculate_factorial(x) |
| 40 | + |
| 41 | +class MathToolkit: |
| 42 | + """A toolkit for performing various mathematical operations.""" |
| 43 | + |
| 44 | + def __init__(self): |
| 45 | + self.tools = [add, subtract, multiply, divide, power, factorial] |
| 46 | + |
| 47 | + def get_tools(self): |
| 48 | + """Returns the available tools.""" |
| 49 | + return self.tools |
| 50 | + |
| 51 | + def execute_tool(self, tool_name: str, *args): |
| 52 | + """Executes a tool by its name with the given arguments.""" |
| 53 | + for tool in self.tools: |
| 54 | + if tool.name == tool_name: |
| 55 | + input_keys = tool.args |
| 56 | + if len(input_keys) != len(args): |
| 57 | + raise ValueError(f"{tool_name} expects {len(input_keys)} arguments, got {len(args)}.") |
| 58 | + input_dict = dict(zip(input_keys, args)) |
| 59 | + return tool.invoke(input_dict) |
| 60 | + raise ValueError(f"Tool {tool_name} not found in toolkit.") |
| 61 | + |
| 62 | +toolkit = MathToolkit() |
| 63 | +tools = toolkit.get_tools() |
| 64 | + |
| 65 | +for tool in tools: |
| 66 | + print(tool.name,"-->",tool.description) |
| 67 | + |
| 68 | +print("Addition result:", toolkit.execute_tool("add", 5, 3)) |
| 69 | +print("Subtraction result:", toolkit.execute_tool("subtract", 5, 3)) |
| 70 | +print("Multiplication result:", toolkit.execute_tool("multiply", 5, 3)) |
| 71 | +print("Division result:", toolkit.execute_tool("divide", 5, 3)) |
| 72 | +print("Power result:", toolkit.execute_tool("power", 5, 3)) |
| 73 | +print("Factorial result:", toolkit.execute_tool("factorial", 5)) |
| 74 | + |
| 75 | + |
| 76 | + |
0 commit comments