Implements intelligent retry strategies for failing sub-agents: error classification (transient/permanent/unknown), backoff policies (exponential, jittered), circuit breaker patterns, and fallback recovery. Activates on agent failure scenarios.
Ships in claude-skills-collection. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Dès qu'un sous-agent peut échouer et que l'échec ne doit pas remonter brutalement. Cas typiques : pipelines de production avec erreurs transitoires (rate limit, timeout, 503), architectures multi-modèles avec quota par provider, traitements longs nécessitant des checkpoints.
| Classe | Signaux | Action |
|---|---|---|
TRANSIENT | 429, 503, timeout, connexion reset | Retry avec backoff |
PERMANENT | 400 schéma invalide, content policy, token limit | Fallback ou escalade — jamais de retry |
UNKNOWN | Toute autre exception | Retry prudent (max 1–2 fois) |
TRANSIENT_SIGNALS = ["rate limit", "429", "503", "timeout", "connection", "temporarily"]
PERMANENT_SIGNALS = ["token limit", "content policy", "invalid schema", "401", "403", "400"]
def classify_error(error: Exception) -> str:
s = str(error).lower()
if any(x in s for x in TRANSIENT_SIGNALS): return "transient"
if any(x in s for x in PERMANENT_SIGNALS): return "permanent"
return "unknown"
| Stratégie | Formule délai | Usage |
|---|---|---|
immediate | 0 s | 429 avec Retry-After: 1 |
fixed | base_delay | service interne fiable |
exponential | base × 2^attempt | API externe instable |
jittered | exponential × random(0.5–1.5) | défaut recommandé — évite thundering herd |
def compute_delay(attempt: int, base: float = 1.0, jitter: bool = True) -> float:
delay = base * (2 ** attempt) # 1s, 2s, 4s, 8s...
if jitter:
delay *= 0.5 + random.random() # ±50% de bruit
return min(delay, 60.0) # plafond à 60 s
CLOSED ──N failures──► OPEN ──recovery_timeout──► HALF-OPEN
▲ │
└─────────────────── succès ────────────────────────┘
class CircuitBreaker:
# failure_threshold=5, recovery_timeout=30s
def can_attempt(self) -> bool:
if self.state == "OPEN":
if time.time() - self.last_failure > self.recovery_timeout:
self.state = "HALF_OPEN"
return True
return False # rejeter sans appel réseau
return True
Paramètres conseillés par défaut : failure_threshold=5, recovery_timeout=30s.
Un retry identique sur un input identique produit le même échec. Dès la 2e tentative :
"Réponds en JSON strict, rien d'autre"def modify_task(args: dict, attempt: int) -> dict:
m = args.copy()
if attempt == 1 and "prompt" in m:
m["prompt"] = m["prompt"][:int(len(m["prompt"]) * 0.6)]
if attempt == 2:
m["prompt"] = "Réponse JSON uniquement: " + m["prompt"][:300]
return m
Définir la chaîne une seule fois dans la config :
MODEL_FALLBACK_CHAIN = [
"claude-opus-4-5", # modèle principal
"claude-sonnet-4-5", # fallback intermédiaire
"claude-haiku-3-5", # fallback léger
]
Basculer vers le suivant à chaque échec consécutif. Journaliser le changement de modèle.
TOOL_FALLBACKS = {
"search_web": ["fetch_url", "search_academic"],
"fetch_url": ["search_web"],
"db_primary": ["db_replica"],
"api_weather_1": ["api_weather_2"],
}
Si l'outil search_web échoue 2 fois → essayer fetch_url. Si le tool de fallback est indisponible aussi → remonter une erreur métier claire.
Indicateur : erreur de token limit ou réponse tronquée/incohérente.
# Découper une liste de 100 items en chunks de 20
def decompose(items: list, chunk_size: int = 20) -> list[list]:
return [items[i:i+chunk_size] for i in range(0, len(items), chunk_size)]
# Relancer chaque chunk indépendamment, agréger les résultats
results = await asyncio.gather(*[process_chunk(c) for c in decompose(items)])
Persister l'état après chaque étape critique :
# Redis / fichier / base de données
checkpoint = {"step": "step_3", "processed_ids": [1, 2, 3], "ts": time.time()}
redis_client.set(f"checkpoint:{job_id}", json.dumps(checkpoint), ex=3600)
# Au redémarrage : reprendre depuis le checkpoint
ckpt = redis_client.get(f"checkpoint:{job_id}")
if ckpt:
state = json.loads(ckpt)
start_from = state["step"]
Toute tâche qui épuise ses retries ET ses fallbacks → DLQ. Ne jamais l'abandonner silencieusement.
def send_to_dlq(task: dict, error: Exception, attempts: int):
record = {
"task": task,
"error": str(error),
"attempts": attempts,
"ts": datetime.utcnow().isoformat(),
}
# SQS: sqs.send_message(QueueUrl=DLQ_URL, MessageBody=json.dumps(record))
# Redis: redis_client.rpush("dlq:agents", json.dumps(record))
# Fichier: append to dlq.jsonl
logger.error("[DLQ] %s", json.dumps(record))
from collections import Counter
def failure_report(failure_log: list[dict]) -> dict:
by_class = Counter(f["class"] for f in failure_log)
by_model = Counter(f["model"] for f in failure_log)
by_tool = Counter(f["tool"] for f in failure_log)
return {"total": len(failure_log), "by_class": dict(by_class),
"by_model": dict(by_model), "by_tool": dict(by_tool)}
Réviser les politiques si transient/permanent ratio > 3 : 1 → le backoff base est probablement trop court.
| Critère | LangGraph | CrewAI | Custom Python |
|---|---|---|---|
| Retry natif | Partiel (node) | Non | Total contrôle |
| Circuit breaker | Non | Non | Manuel |
| Model fallback | Non | Non | Manuel |
| DLQ | Non | Non | Manuel |
| Modification de tâche | Non | Non | Manuel |
Recommandation : implémenter RetryStrategist en couche transversale, appelée par l'orchestrateur, indépendamment du framework agent.
recovery_timeout.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/claude-skills-collection:agent-retry-strategistfrom claude-skills-collection
npx claudepluginhub vantaflow/claude-skills-collection --plugin claude-skills-collection348 skills in this plugin
/agent-a2a-protocol-guideGuide du protocole Agent-to-Agent (A2A) de Google pour l'interopérabilité entre agents IA — découverte, communication et collaboration inter-agents, avec exemples de code, critères de décision et pièges à éviter. Se déclenche avec "A2A", "agent-to-agent", "protocole A2A", "Google A2A", "interopérabilité agents". Also triggers on "agent-to-agent protocol", "agent interoperability", "connect two agents"./agent-agent-observabilityInstrumentation technique d'un agent IA — tracing distribué des appels LLM et outils, spans, métriques custom, corrélation de logs et dashboards de supervision. Pour les alertes et garde-fous de production, voir agent-monitoring-setup. Se déclenche avec "observabilité agent", "tracing agent", "LangSmith", "Langfuse", "OpenTelemetry agent", "spans LLM", "corréler les logs agent". Also triggers on "trace my agent", "LLM tracing", "agent spans"./agent-api-caller-subagentSous-agent spécialisé dans les appels API REST/GraphQL avec retry, auth et transformation de données. Se déclenche avec "sous-agent API", "API caller agent", "agent qui appelle une API", "REST agent", "HTTP agent", "API integration subagent", "external API agent". Also triggers on "subagent that calls an API", "API calling agent", "agent HTTP requests".Other plugins' skills for the same job