File size: 10,545 Bytes
070daf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""
Optimized Tool Executor - Parallel execution, auto-retry, and output validation
"""

import asyncio
import logging
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Callable

from agent.core.level2_config import level2_config
from agent.core.semantic_cache import semantic_cache
from agent.core.observability import observability, ExecutionEvent

logger = logging.getLogger(__name__)


@dataclass
class ToolCall:
    """A tool call to execute"""
    id: str
    name: str
    params: Dict[str, Any]
    estimated_duration: float = 30.0
    expected_output: str = ""


@dataclass
class ToolResult:
    """Result of a tool execution"""
    tool_id: str
    tool_name: str
    output: Any
    success: bool
    execution_time: float
    from_cache: bool = False
    retry_count: int = 0


class OptimizedToolExecutor:
    """
    Executes tools with:
    - Parallel execution when safe
    - Pre-execution validation
    - Dynamic timeout adjustment
    - Automatic retries with backoff
    - Tool result caching
    - Output validation & refinement
    """
    
    def __init__(self):
        self.config = level2_config
        self.cache = semantic_cache
        self.observability = observability
    
    def build_dependency_graph(self, tools: List[ToolCall]) -> Dict[str, List[str]]:
        """Build dependency graph for tool execution"""
        # For now, assume no dependencies (all can run in parallel)
        # In future, could analyze params to detect dependencies
        return {tool.id: [] for tool in tools}
    
    def find_parallelizable_tools(self, graph: Dict[str, List[str]]) -> List[List[str]]:
        """Find batches of tools that can execute in parallel"""
        # Simple approach: all tools in one batch
        # More sophisticated: topological sort
        return [list(graph.keys())]
    
    async def execute_tool_with_guarantee(
        self,
        tool: ToolCall,
        execute_fn: Callable[[str, Dict[str, Any]], Any],
        context: Dict[str, Any] = None
    ) -> ToolResult:
        """Execute with automatic retries and timeout adaptation"""
        
        max_retries = self.config.max_tool_retries if self.config.enable_auto_retry else 1
        base_timeout = tool.estimated_duration * 1.5
        
        # Check cache first
        if self.config.enable_semantic_cache:
            cache_key = f"{tool.name}:{str(tool.params)}"
            cached = await self.cache.check(cache_key)
            if cached:
                logger.info(f"Cache hit for tool {tool.name}")
                return ToolResult(
                    tool_id=tool.id,
                    tool_name=tool.name,
                    output=cached.result,
                    success=True,
                    execution_time=0.0,
                    from_cache=True,
                    retry_count=0
                )
        
        for attempt in range(max_retries):
            timeout = base_timeout * (1.5 ** attempt)  # Exponential backoff
            
            start_time = asyncio.get_event_loop().time()
            
            try:
                # Track execution start
                self.observability.track_execution(ExecutionEvent(
                    event_type="tool_execution_start",
                    data={
                        "tool": tool.name,
                        "attempt": attempt + 1,
                        "timeout": timeout,
                        "params": tool.params
                    }
                ))
                
                # Execute with timeout
                result = await asyncio.wait_for(
                    execute_fn(tool.name, tool.params),
                    timeout=timeout
                )
                
                execution_time = asyncio.get_event_loop().time() - start_time
                
                # Track execution complete
                self.observability.track_execution(ExecutionEvent(
                    event_type="tool_execution_complete",
                    data={
                        "tool": tool.name,
                        "success": True,
                        "duration": execution_time,
                        "output_size": len(str(result)),
                        "cached": False
                    }
                ))
                
                # Cache successful result
                if self.config.enable_semantic_cache:
                    await self.cache.store(
                        query=f"{tool.name}:{str(tool.params)}",
                        result=result,
                        metadata={
                            "tool": tool.name,
                            "execution_time": execution_time
                        }
                    )
                
                return ToolResult(
                    tool_id=tool.id,
                    tool_name=tool.name,
                    output=result,
                    success=True,
                    execution_time=execution_time,
                    from_cache=False,
                    retry_count=attempt
                )
                
            except asyncio.TimeoutError:
                logger.warning(f"Tool {tool.name} timeout on attempt {attempt + 1}")
                
                if attempt < max_retries - 1:
                    self.observability.track_execution(ExecutionEvent(
                        event_type="tool_execution_retry",
                        data={
                            "tool": tool.name,
                            "reason": "timeout",
                            "attempt": attempt + 1,
                            "next_timeout": base_timeout * (1.5 ** (attempt + 1))
                        }
                    ))
                    continue
                else:
                    # Final attempt failed
                    execution_time = asyncio.get_event_loop().time() - start_time
                    
                    self.observability.track_execution(ExecutionEvent(
                        event_type="tool_execution_complete",
                        data={
                            "tool": tool.name,
                            "success": False,
                            "duration": execution_time,
                            "error": "timeout"
                        }
                    ))
                    
                    return ToolResult(
                        tool_id=tool.id,
                        tool_name=tool.name,
                        output=f"Timeout after {max_retries} attempts",
                        success=False,
                        execution_time=execution_time,
                        from_cache=False,
                        retry_count=attempt
                    )
            
            except Exception as e:
                logger.error(f"Tool {tool.name} error on attempt {attempt + 1}: {e}")
                
                if attempt < max_retries - 1:
                    await asyncio.sleep(1 * (attempt + 1))  # Backoff delay
                    continue
                else:
                    execution_time = asyncio.get_event_loop().time() - start_time
                    
                    self.observability.track_execution(ExecutionEvent(
                        event_type="tool_execution_complete",
                        data={
                            "tool": tool.name,
                            "success": False,
                            "duration": execution_time,
                            "error": str(e)
                        }
                    ))
                    
                    return ToolResult(
                        tool_id=tool.id,
                        tool_name=tool.name,
                        output=f"Error: {str(e)}",
                        success=False,
                        execution_time=execution_time,
                        from_cache=False,
                        retry_count=attempt
                    )
        
        # Should never reach here
        return ToolResult(
            tool_id=tool.id,
            tool_name=tool.name,
            output="Unknown error",
            success=False,
            execution_time=0.0,
            from_cache=False,
            retry_count=max_retries
        )
    
    async def execute_with_optimization(
        self,
        tools: List[ToolCall],
        execute_fn: Callable[[str, Dict[str, Any]], Any],
        context: Dict[str, Any] = None
    ) -> Dict[str, ToolResult]:
        """Execute multiple tools with intelligent batching"""
        
        if not tools:
            return {}
        
        # Build execution graph
        graph = self.build_dependency_graph(tools)
        
        # Find parallelizable batches
        batches = self.find_parallelizable_tools(graph)
        
        # Track optimization
        self.observability.track_execution(ExecutionEvent(
            event_type="execution_optimization",
            data={
                "total_tools": len(tools),
                "parallelizable": len(tools),  # All are parallelizable for now
                "batches": len(batches)
            }
        ))
        
        results = {}
        
        # Execute batches
        for batch in batches:
            # Execute batch in parallel
            batch_tools = [t for t in tools if t.id in batch]
            
            batch_results = await asyncio.gather(*[
                self.execute_tool_with_guarantee(tool, execute_fn, context)
                for tool in batch_tools
            ])
            
            for result in batch_results:
                results[result.tool_id] = result
        
        return results
    
    def validate_output_quality(
        self,
        result: ToolResult,
        expected_output: str
    ) -> bool:
        """Validate if output meets quality expectations"""
        if not result.success:
            return False
        
        # Simple validation: check if output is not empty
        if not result.output:
            return False
        
        # Check if output contains error indicators
        output_str = str(result.output).lower()
        error_indicators = ["error", "exception", "failed", "timeout"]
        
        for indicator in error_indicators:
            if indicator in output_str and len(output_str) < 200:
                # Short error message
                return False
        
        return True


# Global executor
tool_executor = OptimizedToolExecutor()