File size: 8,785 Bytes
8a682b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""
Use case for executing tools.
"""

from typing import Dict, Any, Optional, List
from uuid import UUID
import logging
import time

from src.core.entities.tool import Tool, ToolType
from src.core.interfaces.tool_repository import ToolRepository
from src.core.interfaces.tool_executor import ToolExecutor
from src.core.interfaces.logging_service import LoggingService
from src.shared.exceptions import DomainException, ValidationException


class ExecuteToolUseCase:
    """
    Use case for executing tools.
    
    This use case handles tool execution, validation,
    and result processing.
    """
    
    def __init__(
        self,
        tool_repository: ToolRepository,
        tool_executor: ToolExecutor,
        logging_service: LoggingService
    ):
        self.tool_repository = tool_repository
        self.tool_executor = tool_executor
        self.logging_service = logging_service
        self.logger = logging.getLogger(__name__)
    
    async def execute_tool(
        self,
        tool_id: UUID,
        parameters: Dict[str, Any],
        context: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Execute a tool with given parameters.
        
        Args:
            tool_id: ID of the tool to execute
            parameters: Tool execution parameters
            context: Optional execution context
            
        Returns:
            Dictionary containing the execution result
        """
        start_time = time.time()
        
        try:
            # Validate input
            if not parameters:
                raise ValidationException("Tool parameters cannot be empty")
            
            # Find tool
            tool = await self.tool_repository.find_by_id(tool_id)
            if not tool:
                raise DomainException(f"Tool {tool_id} not found")
            
            # Validate tool is available
            if not tool.is_available:
                raise DomainException(f"Tool {tool_id} is not available")
            
            # Execute tool
            result = await self.tool_executor.execute(tool, parameters, context)
            
            execution_time = time.time() - start_time
            
            # Log execution
            await self.logging_service.log_info(
                "tool_executed",
                f"Executed tool {tool_id} successfully",
                {
                    "tool_id": str(tool_id),
                    "tool_name": tool.name,
                    "execution_time": execution_time,
                    "success": result.get("success", False)
                }
            )
            
            return {
                "success": True,
                "tool_id": str(tool_id),
                "tool_name": tool.name,
                "result": result.get("result"),
                "execution_time": execution_time,
                "metadata": result.get("metadata", {})
            }
            
        except Exception as e:
            execution_time = time.time() - start_time
            self.logger.error(f"Tool execution failed: {str(e)}")
            
            await self.logging_service.log_error(
                "tool_execution_failed",
                str(e),
                {
                    "tool_id": str(tool_id),
                    "execution_time": execution_time
                }
            )
            
            return {
                "success": False,
                "error": str(e),
                "execution_time": execution_time
            }
    
    async def execute_tool_by_name(
        self,
        tool_name: str,
        parameters: Dict[str, Any],
        context: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Execute a tool by name.
        
        Args:
            tool_name: Name of the tool to execute
            parameters: Tool execution parameters
            context: Optional execution context
            
        Returns:
            Dictionary containing the execution result
        """
        try:
            # Find tool by name
            tool = await self.tool_repository.find_by_name(tool_name)
            if not tool:
                raise DomainException(f"Tool '{tool_name}' not found")
            
            # Execute using the found tool
            return await self.execute_tool(tool.id, parameters, context)
            
        except Exception as e:
            self.logger.error(f"Failed to execute tool by name '{tool_name}': {str(e)}")
            return {"success": False, "error": str(e)}
    
    async def validate_tool_parameters(
        self,
        tool_id: UUID,
        parameters: Dict[str, Any]
    ) -> Dict[str, Any]:
        """
        Validate tool parameters before execution.
        
        Args:
            tool_id: ID of the tool to validate
            parameters: Parameters to validate
            
        Returns:
            Dictionary containing validation result
        """
        try:
            # Find tool
            tool = await self.tool_repository.find_by_id(tool_id)
            if not tool:
                return {"success": False, "error": f"Tool {tool_id} not found"}
            
            # Validate parameters
            validation_result = await self.tool_executor.validate_parameters(tool, parameters)
            
            return {
                "success": True,
                "valid": validation_result.get("valid", False),
                "errors": validation_result.get("errors", []),
                "warnings": validation_result.get("warnings", [])
            }
            
        except Exception as e:
            self.logger.error(f"Parameter validation failed: {str(e)}")
            return {"success": False, "error": str(e)}
    
    async def get_tool_info(self, tool_id: UUID) -> Dict[str, Any]:
        """
        Get tool information.
        
        Args:
            tool_id: ID of the tool to retrieve
            
        Returns:
            Dictionary containing tool information
        """
        try:
            tool = await self.tool_repository.find_by_id(tool_id)
            if not tool:
                return {"success": False, "error": f"Tool {tool_id} not found"}
            
            return {
                "success": True,
                "tool": {
                    "id": str(tool.id),
                    "name": tool.name,
                    "description": tool.description,
                    "tool_type": tool.tool_type.value,
                    "is_available": tool.is_available,
                    "parameters_schema": tool.parameters_schema,
                    "created_at": tool.created_at.isoformat() if tool.created_at else None,
                    "updated_at": tool.updated_at.isoformat() if tool.updated_at else None
                }
            }
            
        except Exception as e:
            self.logger.error(f"Failed to get tool info {tool_id}: {str(e)}")
            return {"success": False, "error": str(e)}
    
    async def list_available_tools(self, tool_type: Optional[ToolType] = None) -> Dict[str, Any]:
        """
        List available tools, optionally filtered by type.
        
        Args:
            tool_type: Optional tool type filter
            
        Returns:
            Dictionary containing the list of tools
        """
        try:
            if tool_type:
                tools = await self.tool_repository.find_by_type(tool_type)
            else:
                tools = await self.tool_repository.find_available()
            
            tool_list = []
            for tool in tools:
                tool_list.append({
                    "id": str(tool.id),
                    "name": tool.name,
                    "description": tool.description,
                    "tool_type": tool.tool_type.value,
                    "is_available": tool.is_available
                })
            
            return {
                "success": True,
                "tools": tool_list,
                "count": len(tool_list)
            }
            
        except Exception as e:
            self.logger.error(f"Failed to list tools: {str(e)}")
            return {"success": False, "error": str(e)}
    
    async def get_tool_statistics(self) -> Dict[str, Any]:
        """
        Get tool repository statistics.
        
        Returns:
            Dictionary containing tool statistics
        """
        try:
            stats = await self.tool_repository.get_statistics()
            return {"success": True, "statistics": stats}
            
        except Exception as e:
            self.logger.error(f"Failed to get tool statistics: {str(e)}")
            return {"success": False, "error": str(e)}