from typing import Dict, Callable, Any
from functools import wraps
import inspect
class ToolRegistry:
def __init__(self):
self.tools: Dict[str, Dict[str, Any]] = {}
def register_tool(self, name: str, description: str, parameters: Dict[str, Any]):
"""Decorator to register a tool"""
def decorator(func: Callable):
# Extract function signature
sig = inspect.signature(func)
tool_info = {
"name": name,
"description": description,
"parameters": parameters,
"function": func,
"signature": str(sig)
}
self.tools[name] = tool_info
@wraps(func)
def wrapper(*args, **kwargs):
# Add logging, validation, etc.
try:
result = func(*args, **kwargs)
return {"success": True, "result": result}
except Exception as e:
return {"success": False, "error": str(e)}
return wrapper
return decorator
def get_tool(self, name: str) -> Dict[str, Any]:
"""Get tool information"""
return self.tools.get(name)
def list_tools(self) -> List[Dict[str, Any]]:
"""List all available tools"""
return [
{
"name": tool_info["name"],
"description": tool_info["description"],
"parameters": tool_info["parameters"]
}
for tool_info in self.tools.values()
]
def execute_tool(self, name: str, **kwargs) -> Dict[str, Any]:
"""Execute a tool with given parameters"""
if name not in self.tools:
return {"success": False, "error": f"Tool '{name}' not found"}
tool = self.tools[name]
try:
result = tool["function"](**kwargs)
return {"success": True, "result": result}
except Exception as e:
return {"success": False, "error": str(e)}
# Usage example
registry = ToolRegistry()
@registry.register_tool(
name="calculate_tip",
description="Calculate tip amount for a bill",
parameters={
"type": "object",
"properties": {
"bill_amount": {"type": "number", "description": "Total bill amount"},
"tip_percentage": {"type": "number", "default": 15, "description": "Tip percentage"}
},
"required": ["bill_amount"]
}
)
def calculate_tip(bill_amount: float, tip_percentage: float = 15) -> Dict[str, float]:
"""Calculate tip and total amount"""
tip_amount = bill_amount * (tip_percentage / 100)
total_amount = bill_amount + tip_amount
return {
"bill_amount": bill_amount,
"tip_percentage": tip_percentage,
"tip_amount": tip_amount,
"total_amount": total_amount
}
# Agent can now use this tool
result = registry.execute_tool("calculate_tip", bill_amount=50.0, tip_percentage=20)