Repository navigation
Expand file tree
/
Copy pathfallback_handler.py
More file actions
1694 lines (1367 loc) · 68.2 KB
/
Copy pathfallback_handler.py
File metadata and controls
1694 lines (1367 loc) · 68.2 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Fallback Handler Module for Neuron Architecture
Provides standardized error handling and fallback mechanisms
when agents fail or return low-confidence results.
"""
import logging
import time
import uuid
from typing import Dict, List, Any, Optional, Tuple, Union, Callable
from enum import Enum, auto
from dataclasses import dataclass, field
logger = logging.getLogger(__name__)
class FailureType(Enum):
"""Types of agent failures that can occur."""
TIMEOUT = auto() # Agent took too long to respond
EXCEPTION = auto() # Agent threw an exception
EMPTY_RESULT = auto() # Agent returned no result
LOW_CONFIDENCE = auto() # Agent returned result with low confidence
INVALID_FORMAT = auto() # Agent returned improperly formatted result
CONSISTENCY_ERROR = auto() # Agent result inconsistent with other agents/context
HALLUCINATION = auto() # Agent provided information not grounded in facts
AUTHORIZATION = auto() # Agent lacked permission for requested action
RESOURCE_LIMIT = auto() # Agent hit resource/rate limits
CONNECTION_ERROR = auto() # Agent couldn't connect to required service
OTHER = auto() # Unclassified failure
class FallbackStrategy(Enum):
"""Available strategies for handling agent failures."""
RETRY = auto() # Retry the same agent with same input
RETRY_WITH_BACKOFF = auto() # Retry with exponential backoff
RETRY_WITH_PARAMS = auto() # Retry with modified parameters
ALTERNATIVE_AGENT = auto() # Route to an alternative agent
DECOMPOSE_TASK = auto() # Break task into simpler sub-tasks
DEFAULT_VALUE = auto() # Return a safe default value
HUMAN_ESCALATION = auto() # Escalate to human operator
GRACEFUL_DEGRADATION = auto() # Continue with reduced functionality
ABORT = auto() # Abort the current operation
CACHED_RESULT = auto() # Use cached result from previous execution
USER_PROMPT = auto() # Ask user how to proceed
@dataclass
class FailureRecord:
"""Record of an agent failure occurrence."""
failure_id: str
agent_id: str
failure_type: FailureType
timestamp: float
input_data: Any
error_message: str
error_details: Dict[str, Any] = field(default_factory=dict)
context: Dict[str, Any] = field(default_factory=dict)
trace_id: Optional[str] = None
@dataclass
class FallbackResult:
"""Result of a fallback operation."""
success: bool
fallback_id: str
agent_id: str
original_failure: FailureRecord
strategy_used: FallbackStrategy
result_data: Any
confidence: float = 0.0
execution_time: float = 0.0
attempts: int = 1
metadata: Dict[str, Any] = field(default_factory=dict)
class FallbackHandler:
"""
Provides error handling and fallback mechanisms when agents fail
or return low-confidence results.
"""
def __init__(self, config: Dict[str, Any], circuit_router=None):
"""
Initialize the fallback handler with configuration parameters.
Args:
config: Configuration for fallback behavior
circuit_router: Optional reference to circuit router for rerouting
"""
# Configuration parameters
self.confidence_threshold = config.get("confidence_threshold", 0.7)
self.max_retry_attempts = config.get("max_retry_attempts", 3)
self.backoff_base = config.get("backoff_base", 2.0)
self.timeout_threshold = config.get("timeout_threshold", 30.0) # seconds
self.failure_history_limit = config.get("failure_history_limit", 1000)
# Default strategies for different failure types
self.default_strategies = config.get("default_strategies", {
FailureType.TIMEOUT.name: FallbackStrategy.RETRY_WITH_BACKOFF.name,
FailureType.EXCEPTION.name: FallbackStrategy.RETRY.name,
FailureType.EMPTY_RESULT.name: FallbackStrategy.ALTERNATIVE_AGENT.name,
FailureType.LOW_CONFIDENCE.name: FallbackStrategy.ALTERNATIVE_AGENT.name,
FailureType.INVALID_FORMAT.name: FallbackStrategy.RETRY_WITH_PARAMS.name,
FailureType.CONSISTENCY_ERROR.name: FallbackStrategy.DECOMPOSE_TASK.name,
FailureType.HALLUCINATION.name: FallbackStrategy.ALTERNATIVE_AGENT.name,
FailureType.AUTHORIZATION.name: FallbackStrategy.HUMAN_ESCALATION.name,
FailureType.RESOURCE_LIMIT.name: FallbackStrategy.RETRY_WITH_BACKOFF.name,
FailureType.CONNECTION_ERROR.name: FallbackStrategy.RETRY_WITH_BACKOFF.name,
FailureType.OTHER.name: FallbackStrategy.ALTERNATIVE_AGENT.name
})
# Convert string enum names to actual enum values
self.default_strategies = {
FailureType[k] if isinstance(k, str) else k:
FallbackStrategy[v] if isinstance(v, str) else v
for k, v in self.default_strategies.items()
}
# Alternative agent mappings
self.alternative_agents = config.get("alternative_agents", {})
# Custom handlers for specific failure types
self.custom_handlers = {}
# Circuit router reference for rerouting
self.circuit_router = circuit_router
# State
self.failure_history: List[FailureRecord] = []
self.fallback_history: List[FallbackResult] = []
self.agent_performance_stats: Dict[str, Dict[str, Any]] = {}
# Register trace logger if available
self.trace_logger = None
try:
from neuron.observability.trace_logger import TraceLogger
if "trace_logger" in config:
self.trace_logger = config["trace_logger"]
logger.info("Using provided TraceLogger for fallback tracking")
except ImportError:
logger.debug("TraceLogger not available for fallback tracking")
# Load simulation planner if available
self.simulation_planner = None
try:
from neuron.agents.simulation_planner import SimulationPlanner
if "simulation_planner" in config:
self.simulation_planner = config["simulation_planner"]
logger.info("Using provided SimulationPlanner for predictive fallbacks")
except ImportError:
logger.debug("SimulationPlanner not available for predictive fallbacks")
logger.info(f"Initialized FallbackHandler with confidence_threshold={self.confidence_threshold}, "
f"max_retry_attempts={self.max_retry_attempts}")
def handle_failure(self, agent_id: str, failure_type: Union[str, FailureType],
input_data: Any, error_message: str = "",
error_details: Optional[Dict[str, Any]] = None,
context: Optional[Dict[str, Any]] = None) -> FallbackResult:
"""
Handle an agent failure by applying appropriate fallback strategies.
Args:
agent_id: ID of the failed agent
failure_type: Type of failure that occurred
input_data: Input that was provided to the agent
error_message: Error message from the failure
error_details: Additional details about the error
context: Execution context when the failure occurred
Returns:
result: Result of the fallback operation
"""
# Convert string failure type to enum if needed
if isinstance(failure_type, str):
try:
failure_type = FailureType[failure_type.upper()]
except KeyError:
logger.warning(f"Unknown failure type: {failure_type}, using OTHER")
failure_type = FailureType.OTHER
# Create failure record
failure_record = FailureRecord(
failure_id=str(uuid.uuid4()),
agent_id=agent_id,
failure_type=failure_type,
timestamp=time.time(),
input_data=input_data,
error_message=error_message,
error_details=error_details or {},
context=context or {},
trace_id=context.get("trace_id") if context else None
)
# Add to history
self._add_to_failure_history(failure_record)
# Log the failure
self._log_failure(failure_record)
# Determine appropriate fallback strategy
strategy = self._determine_strategy(failure_record)
# Apply strategy
start_time = time.time()
result = self._apply_strategy(strategy, failure_record)
execution_time = time.time() - start_time
# Update result with execution time
result.execution_time = execution_time
# Add to fallback history
self._add_to_fallback_history(result)
# Log the fallback result
self._log_fallback_result(result)
# Update agent performance statistics
self._update_agent_stats(agent_id, failure_type, strategy, result.success)
return result
def register_custom_handler(self, failure_type: Union[str, FailureType],
handler: Callable[[FailureRecord], Any]) -> None:
"""
Register a custom handler function for a specific failure type.
Args:
failure_type: Type of failure to handle
handler: Function to call when this failure occurs
"""
# Convert string failure type to enum if needed
if isinstance(failure_type, str):
try:
failure_type = FailureType[failure_type.upper()]
except KeyError:
logger.warning(f"Unknown failure type: {failure_type}, using OTHER")
failure_type = FailureType.OTHER
self.custom_handlers[failure_type] = handler
logger.info(f"Registered custom handler for {failure_type.name}")
def register_alternative_agent(self, primary_agent_id: str,
alternative_agent_id: str,
for_failure_types: Optional[List[Union[str, FailureType]]] = None) -> None:
"""
Register an alternative agent to use when a primary agent fails.
Args:
primary_agent_id: ID of the primary agent
alternative_agent_id: ID of the alternative agent
for_failure_types: Optional list of failure types this alternative handles
"""
if primary_agent_id not in self.alternative_agents:
self.alternative_agents[primary_agent_id] = []
# Convert string failure types to enum if provided
if for_failure_types:
failure_types = []
for ft in for_failure_types:
if isinstance(ft, str):
try:
ft = FailureType[ft.upper()]
except KeyError:
logger.warning(f"Unknown failure type: {ft}, using OTHER")
ft = FailureType.OTHER
failure_types.append(ft)
else:
failure_types = None
# Add to alternatives with optional failure type specificity
self.alternative_agents[primary_agent_id].append({
"agent_id": alternative_agent_id,
"failure_types": failure_types
})
logger.info(f"Registered alternative agent {alternative_agent_id} for {primary_agent_id}")
def check_result_confidence(self, agent_id: str, result: Any,
context: Optional[Dict[str, Any]] = None) -> Union[Any, FallbackResult]:
"""
Check if an agent result has sufficient confidence, apply fallback if not.
Args:
agent_id: ID of the agent
result: Result from the agent
context: Execution context
Returns:
result: Original result if confident, fallback result if not
"""
# Extract confidence from result if available
confidence = 0.0
if isinstance(result, dict):
# Check for confidence in result dictionary
confidence = result.get("confidence", 0.0)
elif hasattr(result, "confidence"):
# Check for confidence attribute
confidence = result.confidence
elif context and "confidence" in context:
# Check for confidence in context
confidence = context["confidence"]
# If confidence is below threshold, handle as a low confidence failure
if confidence < self.confidence_threshold:
logger.debug(f"Low confidence result ({confidence:.3f} < {self.confidence_threshold}) from {agent_id}")
return self.handle_failure(
agent_id=agent_id,
failure_type=FailureType.LOW_CONFIDENCE,
input_data=result, # Input data is the result itself
error_message=f"Low confidence: {confidence:.3f} < {self.confidence_threshold}",
context=context or {}
)
# Otherwise, return the original result
return result
def predict_potential_failures(self, agent_id: str, input_data: Any,
context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""
Proactively predict potential failures before execution.
Args:
agent_id: ID of the agent
input_data: Input data to be sent to the agent
context: Execution context
Returns:
prediction: Dictionary of failure predictions
"""
# Default prediction
prediction = {
"potential_failures": [],
"failure_probability": 0.0,
"recommendation": None
}
# Use history to identify common failure patterns
agent_failures = [f for f in self.failure_history if f.agent_id == agent_id]
# If no history, return default prediction
if not agent_failures:
return prediction
# Calculate basic failure statistics
failure_count = len(agent_failures)
failure_types = {}
for failure in agent_failures:
failure_type = failure.failure_type
if failure_type not in failure_types:
failure_types[failure_type] = 0
failure_types[failure_type] += 1
# Calculate failure probabilities by type
total_failures = sum(failure_types.values())
failure_probabilities = {
ft: count / total_failures
for ft, count in failure_types.items()
}
# Sort by probability (highest first)
sorted_failures = sorted(
failure_probabilities.items(),
key=lambda x: x[1],
reverse=True
)
# Use simulation planner if available for more detailed prediction
if self.simulation_planner:
try:
# Create an action representing the agent execution
action = {
"type": "agent_execution",
"agent_id": agent_id,
"input_data": input_data,
"context": context
}
# Simulate the action
simulation = self.simulation_planner.simulate_action(
action=action,
current_state=context or {},
agent_id="fallback_handler"
)
# Extract risks that look like failures
if simulation.risks:
for risk in simulation.risks:
risk_prob = risk.get("probability", 0)
risk_severity = risk.get("severity", 0)
risk_desc = risk.get("description", "")
# Map risk to failure type if possible
failure_type = None
for ft in FailureType:
if ft.name.lower() in risk_desc.lower():
failure_type = ft
break
if failure_type:
prediction["potential_failures"].append({
"failure_type": failure_type.name,
"probability": risk_prob,
"severity": risk_severity,
"description": risk_desc
})
# Update overall failure probability
prediction["failure_probability"] = 1.0 - simulation.confidence
# Add fallback recommendation
if prediction["failure_probability"] > 0.5:
# Get the strategy for the most likely failure
if prediction["potential_failures"]:
most_likely = prediction["potential_failures"][0]
failure_type = FailureType[most_likely["failure_type"]]
strategy = self.default_strategies.get(failure_type, FallbackStrategy.ALTERNATIVE_AGENT)
prediction["recommendation"] = {
"strategy": strategy.name,
"reason": f"High probability of {failure_type.name} failure"
}
except Exception as e:
logger.warning(f"Error in simulation-based failure prediction: {e}")
# If no simulation or simulation failed, use history-based prediction
if not prediction["potential_failures"] and sorted_failures:
for failure_type, probability in sorted_failures[:3]: # Top 3 failure types
prediction["potential_failures"].append({
"failure_type": failure_type.name,
"probability": probability,
"severity": 0.7, # Default severity
"description": f"Historical {failure_type.name} failure pattern"
})
prediction["failure_probability"] = sum(
f["probability"] for f in prediction["potential_failures"]
) / len(prediction["potential_failures"]) if prediction["potential_failures"] else 0.0
# Add fallback recommendation
if prediction["failure_probability"] > 0.3:
most_likely = prediction["potential_failures"][0]
failure_type = FailureType[most_likely["failure_type"]]
strategy = self.default_strategies.get(failure_type, FallbackStrategy.ALTERNATIVE_AGENT)
prediction["recommendation"] = {
"strategy": strategy.name,
"reason": f"Historical pattern of {failure_type.name} failures"
}
return prediction
def get_failure_history(self, agent_id: Optional[str] = None,
failure_type: Optional[Union[str, FailureType]] = None,
time_range: Optional[Tuple[float, float]] = None) -> List[FailureRecord]:
"""
Get history of failures, optionally filtered.
Args:
agent_id: Optional agent ID to filter by
failure_type: Optional failure type to filter by
time_range: Optional (start_time, end_time) tuple
Returns:
history: List of matching failure records
"""
# Convert string failure type to enum if needed
if isinstance(failure_type, str):
try:
failure_type = FailureType[failure_type.upper()]
except KeyError:
logger.warning(f"Unknown failure type: {failure_type}, using OTHER")
failure_type = FailureType.OTHER
# Apply filters
filtered_history = self.failure_history
if agent_id:
filtered_history = [f for f in filtered_history if f.agent_id == agent_id]
if failure_type:
filtered_history = [f for f in filtered_history if f.failure_type == failure_type]
if time_range:
start_time, end_time = time_range
filtered_history = [
f for f in filtered_history
if start_time <= f.timestamp <= end_time
]
return filtered_history
def get_agent_failure_rate(self, agent_id: str,
time_window: Optional[float] = None) -> Dict[str, Any]:
"""
Calculate failure rate statistics for an agent.
Args:
agent_id: ID of the agent
time_window: Optional time window in seconds (default: all time)
Returns:
stats: Dictionary of failure statistics
"""
# Get agent failures
failures = self.get_failure_history(agent_id=agent_id)
# Filter by time window if provided
if time_window:
current_time = time.time()
failures = [f for f in failures if current_time - f.timestamp <= time_window]
# Get agent performance stats
agent_stats = self.agent_performance_stats.get(agent_id, {})
total_executions = agent_stats.get("total_executions", 0)
# Calculate failure rate
failure_count = len(failures)
if total_executions == 0:
failure_rate = 0.0
else:
failure_rate = failure_count / total_executions
# Count by failure type
failure_counts = {}
for failure in failures:
failure_type = failure.failure_type.name
if failure_type not in failure_counts:
failure_counts[failure_type] = 0
failure_counts[failure_type] += 1
# Calculate success rate of fallbacks
fallbacks = [fb for fb in self.fallback_history
if fb.original_failure.agent_id == agent_id]
successful_fallbacks = [fb for fb in fallbacks if fb.success]
if not fallbacks:
fallback_success_rate = 0.0
else:
fallback_success_rate = len(successful_fallbacks) / len(fallbacks)
# Calculate strategy effectiveness
strategy_stats = {}
for fb in fallbacks:
strategy = fb.strategy_used.name
if strategy not in strategy_stats:
strategy_stats[strategy] = {"total": 0, "success": 0}
strategy_stats[strategy]["total"] += 1
if fb.success:
strategy_stats[strategy]["success"] += 1
# Calculate success rates for each strategy
for strategy, stats in strategy_stats.items():
if stats["total"] > 0:
stats["success_rate"] = stats["success"] / stats["total"]
else:
stats["success_rate"] = 0.0
return {
"agent_id": agent_id,
"total_executions": total_executions,
"failure_count": failure_count,
"failure_rate": failure_rate,
"failure_counts_by_type": failure_counts,
"fallback_success_rate": fallback_success_rate,
"strategy_stats": strategy_stats,
"time_window": time_window
}
def clear_history(self) -> None:
"""Clear failure and fallback history."""
self.failure_history = []
self.fallback_history = []
logger.info("Cleared failure and fallback history")
def _add_to_failure_history(self, failure: FailureRecord) -> None:
"""
Add a failure record to history, pruning if needed.
Args:
failure: Failure record to add
"""
self.failure_history.append(failure)
# Prune if over limit
if len(self.failure_history) > self.failure_history_limit:
self.failure_history = self.failure_history[-self.failure_history_limit:]
def _add_to_fallback_history(self, result: FallbackResult) -> None:
"""
Add a fallback result to history, pruning if needed.
Args:
result: Fallback result to add
"""
self.fallback_history.append(result)
# Prune if over limit
if len(self.fallback_history) > self.failure_history_limit:
self.fallback_history = self.fallback_history[-self.failure_history_limit:]
def _log_failure(self, failure: FailureRecord) -> None:
"""
Log a failure to the logger and trace logger if available.
Args:
failure: Failure record to log
"""
# Log to standard logger
error_summary = f"{failure.error_message[:50]}..." if len(failure.error_message) > 50 else failure.error_message
logger.warning(f"Agent failure: {failure.agent_id} - {failure.failure_type.name} - {error_summary}")
# Log to trace logger if available
if self.trace_logger:
self.trace_logger.log_event(
event_type="agent_failure",
component_id=failure.agent_id,
data={
"failure_id": failure.failure_id,
"failure_type": failure.failure_type.name,
"error_message": failure.error_message,
"error_details": failure.error_details,
"context": failure.context
}
)
def _log_fallback_result(self, result: FallbackResult) -> None:
"""
Log a fallback result to the logger and trace logger if available.
Args:
result: Fallback result to log
"""
# Log to standard logger
status = "succeeded" if result.success else "failed"
logger.info(f"Fallback {status}: {result.agent_id} - {result.strategy_used.name} - attempts: {result.attempts}")
# Log to trace logger if available
if self.trace_logger:
self.trace_logger.log_event(
event_type="fallback_result",
component_id="fallback_handler",
data={
"fallback_id": result.fallback_id,
"agent_id": result.agent_id,
"strategy": result.strategy_used.name,
"success": result.success,
"attempts": result.attempts,
"execution_time": result.execution_time,
"confidence": result.confidence,
"original_failure_type": result.original_failure.failure_type.name
}
)
def _update_agent_stats(self, agent_id: str, failure_type: FailureType,
strategy: FallbackStrategy, success: bool) -> None:
"""
Update agent performance statistics.
Args:
agent_id: ID of the agent
failure_type: Type of the failure
strategy: Fallback strategy used
success: Whether the fallback was successful
"""
# Initialize agent stats if not exist
if agent_id not in self.agent_performance_stats:
self.agent_performance_stats[agent_id] = {
"total_executions": 0,
"total_failures": 0,
"failure_types": {},
"fallback_strategies": {},
"fallback_successes": 0,
"fallback_failures": 0
}
# Update stats
stats = self.agent_performance_stats[agent_id]
# Count failure
stats["total_failures"] += 1
# Count by failure type
failure_type_name = failure_type.name
if failure_type_name not in stats["failure_types"]:
stats["failure_types"][failure_type_name] = 0
stats["failure_types"][failure_type_name] += 1
# Count by strategy
strategy_name = strategy.name
if strategy_name not in stats["fallback_strategies"]:
stats["fallback_strategies"][strategy_name] = {
"total": 0,
"success": 0,
"failure": 0
}
strategy_stats = stats["fallback_strategies"][strategy_name]
strategy_stats["total"] += 1
if success:
strategy_stats["success"] += 1
stats["fallback_successes"] += 1
else:
strategy_stats["failure"] += 1
stats["fallback_failures"] += 1
def _determine_strategy(self, failure: FailureRecord) -> FallbackStrategy:
"""
Determine the best fallback strategy for a failure.
Args:
failure: Failure record to determine strategy for
Returns:
strategy: Selected fallback strategy
"""
# Check for custom handler
if failure.failure_type in self.custom_handlers:
return FallbackStrategy.RETRY_WITH_PARAMS # Will use custom handler
# Check if there's a specific strategy for this failure type
if failure.failure_type in self.default_strategies:
return self.default_strategies[failure.failure_type]
# Default to alternative agent
return FallbackStrategy.ALTERNATIVE_AGENT
def _apply_strategy(self, strategy: FallbackStrategy,
failure: FailureRecord) -> FallbackResult:
"""
Apply the selected fallback strategy to handle a failure.
Args:
strategy: Strategy to apply
failure: Failure record to handle
Returns:
result: Result of applying the strategy
"""
agent_id = failure.agent_id
input_data = failure.input_data
context = failure.context
# Create base result
result = FallbackResult(
success=False,
fallback_id=str(uuid.uuid4()),
agent_id=agent_id,
original_failure=failure,
strategy_used=strategy,
result_data=None,
confidence=0.0,
attempts=1
)
# Apply selected strategy
try:
if strategy == FallbackStrategy.RETRY:
result = self._apply_retry(failure, result)
elif strategy == FallbackStrategy.RETRY_WITH_BACKOFF:
result = self._apply_retry_with_backoff(failure, result)
elif strategy == FallbackStrategy.RETRY_WITH_PARAMS:
result = self._apply_retry_with_params(failure, result)
elif strategy == FallbackStrategy.ALTERNATIVE_AGENT:
result = self._apply_alternative_agent(failure, result)
elif strategy == FallbackStrategy.DECOMPOSE_TASK:
result = self._apply_decompose_task(failure, result)
elif strategy == FallbackStrategy.DEFAULT_VALUE:
result = self._apply_default_value(failure, result)
elif strategy == FallbackStrategy.HUMAN_ESCALATION:
result = self._apply_human_escalation(failure, result)
elif strategy == FallbackStrategy.GRACEFUL_DEGRADATION:
result = self._apply_graceful_degradation(failure, result)
elif strategy == FallbackStrategy.ABORT:
result = self._apply_abort(failure, result)
elif strategy == FallbackStrategy.CACHED_RESULT:
result = self._apply_cached_result(failure, result)
elif strategy == FallbackStrategy.USER_PROMPT:
result = self._apply_user_prompt(failure, result)
else:
logger.warning(f"Unknown fallback strategy: {strategy.name}, using retry")
result = self._apply_retry(failure, result)
except Exception as e:
logger.error(f"Error applying fallback strategy {strategy.name}: {e}")
result.success = False
result.result_data = None
result.metadata["error"] = str(e)
return result
def _apply_retry(self, failure: FailureRecord, result: FallbackResult) -> FallbackResult:
"""
Apply the RETRY strategy: retry the same agent with the same input.
Args:
failure: The failure record
result: The fallback result to update
Returns:
updated_result: Updated fallback result
"""
agent_id = failure.agent_id
input_data = failure.input_data
context = failure.context
logger.debug(f"Applying RETRY strategy for {agent_id}")
# Execute the agent again
try:
# This would use the actual agent execution logic
# For now, mock a successful result
# In practice, this would call something like:
# result_data = self.circuit_router.execute_agent(agent_id, input_data, context)
# Mock result for demonstration
result_data = {"success": True, "data": "Retry result", "confidence": 0.8}
result.success = True
result.result_data = result_data
result.confidence = result_data.get("confidence", 0.8)
except Exception as e:
result.success = False
result.result_data = None
result.metadata["retry_error"] = str(e)
return result
def _apply_retry_with_backoff(self, failure: FailureRecord, result: FallbackResult) -> FallbackResult:
"""
Apply the RETRY_WITH_BACKOFF strategy: retry with exponential backoff.
Args:
failure: The failure record
result: The fallback result to update
Returns:
updated_result: Updated fallback result
"""
agent_id = failure.agent_id
input_data = failure.input_data
context = failure.context
logger.debug(f"Applying RETRY_WITH_BACKOFF strategy for {agent_id}")
# Try multiple times with exponential backoff
for attempt in range(1, self.max_retry_attempts + 1):
result.attempts = attempt
try:
# Calculate backoff delay
delay = self.backoff_base ** (attempt - 1)
logger.debug(f"Retry attempt {attempt}/{self.max_retry_attempts} with {delay:.2f}s delay")
# Sleep for backoff delay
time.sleep(delay)
# Execute the agent again
# For now, mock a successful result
# In practice, this would call something like:
# result_data = self.circuit_router.execute_agent(agent_id, input_data, context)
# Mock result for demonstration - succeed on later attempts
if attempt >= self.max_retry_attempts - 1:
result_data = {"success": True, "data": f"Retry result (attempt {attempt})", "confidence": 0.8}
result.success = True
result.result_data = result_data
result.confidence = result_data.get("confidence", 0.8)
result.metadata["successful_attempt"] = attempt
break
else:
# Simulate continued failure
raise Exception(f"Simulated failure on attempt {attempt}")
except Exception as e:
result.success = False
result.result_data = None
result.metadata[f"retry_error_{attempt}"] = str(e)
# Continue to next attempt
return result
def _apply_retry_with_params(self, failure: FailureRecord, result: FallbackResult) -> FallbackResult:
"""
Apply the RETRY_WITH_PARAMS strategy: retry with modified parameters.
Args:
failure: The failure record
result: The fallback result to update
Returns:
updated_result: Updated fallback result
"""
agent_id = failure.agent_id
input_data = failure.input_data
context = failure.context
logger.debug(f"Applying RETRY_WITH_PARAMS strategy for {agent_id}")
# Check for custom handler first
if failure.failure_type in self.custom_handlers:
handler = self.custom_handlers[failure.failure_type]
try:
# Call custom handler
handler_result = handler(failure)
# Update result
result.success = True
result.result_data = handler_result
result.confidence = 0.8 # Default confidence for custom handlers
result.metadata["custom_handler"] = "used"
return result
except Exception as e:
logger.error(f"Error in custom handler for {failure.failure_type.name}: {e}")
# Fall through to default implementation
# Determine parameter modifications
modified_input = input_data
modified_context = context.copy() if context else {}
# Apply modifications based on failure type
if failure.failure_type == FailureType.TIMEOUT:
# Increase timeout
modified_context["timeout"] = modified_context.get("timeout", 30) * 1.5
elif failure.failure_type == FailureType.LOW_CONFIDENCE:
# Add hint for better confidence
if isinstance(modified_input, dict):
modified_input = modified_input.copy()
modified_input["require_high_confidence"] = True
modified_context["min_confidence"] = self.confidence_threshold
elif failure.failure_type == FailureType.INVALID_FORMAT:
# Add format guidance
if isinstance(modified_input, dict):
modified_input = modified_input.copy()
modified_input["strict_format"] = True
modified_context["validate_format"] = True
# Execute with modified parameters
try:
# For now, mock a successful result
# In practice, this would call something like:
# result_data = self.circuit_router.execute_agent(agent_id, modified_input, modified_context)
# Mock result for demonstration
result_data = {
"success": True,
"data": "Result with modified parameters",
"confidence": 0.85
}
result.success = True
result.result_data = result_data
result.confidence = result_data.get("confidence", 0.85)
result.metadata["parameter_modifications"] = {
"input_modified": input_data != modified_input,
"context_modified": context != modified_context
}
except Exception as e:
result.success = False
result.result_data = None
result.metadata["retry_error"] = str(e)
return result
def _apply_alternative_agent(self, failure: FailureRecord, result: FallbackResult) -> FallbackResult:
"""
Apply the ALTERNATIVE_AGENT strategy: route to an alternative agent.
Args:
failure: The failure record
result: The fallback result to update