Spaces:
Build error
Build error
File size: 2,960 Bytes
e20bd8e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import logging
from typing import Dict, Any, Callable
from tools.langgraph_node import get_langgraph_node
logger = logging.getLogger(__name__)
class ToolWrapper:
"""Wrapper for standardizing tool interactions and logging"""
def __init__(self, tool_name: str, tool_function: Callable):
self.tool_name = tool_name
self.tool_function = tool_function
self.langgraph = get_langgraph_node()
# Register tool with LangGraph
self._register_tool()
def _register_tool(self):
"""Register tool with LangGraph node"""
try:
tool_config = {
'name': self.tool_name,
'function': self.tool_function.__name__,
'description': self.tool_function.__doc__ or 'No description available'
}
self.langgraph.register_tool(self.tool_name, tool_config)
except Exception as e:
logger.error(f"Error registering tool {self.tool_name}: {str(e)}")
def execute(self, agent_id: str, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""Execute tool and log usage"""
try:
# Execute tool function
output_data = self.tool_function(**input_data)
# Log tool usage
self.langgraph.log_tool_usage(
agent_id=agent_id,
tool_name=self.tool_name,
input_data=input_data,
output_data=output_data
)
return output_data
except Exception as e:
logger.error(f"Error executing tool {self.tool_name}: {str(e)}")
raise
class ToolRegistry:
"""Registry for managing tool wrappers"""
def __init__(self):
self.tools = {}
self.langgraph = get_langgraph_node()
def register_tool(self, tool_name: str, tool_function: Callable):
"""Register a new tool with wrapper"""
try:
wrapper = ToolWrapper(tool_name, tool_function)
self.tools[tool_name] = wrapper
logger.info(f"Registered tool: {tool_name}")
except Exception as e:
logger.error(f"Error registering tool {tool_name}: {str(e)}")
raise
def get_tool(self, tool_name: str) -> ToolWrapper:
"""Get tool wrapper by name"""
if tool_name not in self.tools:
raise ValueError(f"Tool {tool_name} not found")
return self.tools[tool_name]
def execute_tool(self, agent_id: str, tool_name: str, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""Execute a tool by name"""
tool = self.get_tool(tool_name)
return tool.execute(agent_id, input_data)
_instance = None
def get_tool_registry():
"""Get or create singleton instance of ToolRegistry"""
global _instance
if _instance is None:
_instance = ToolRegistry()
return _instance |