К основному содержанию
скилл CX Codex

langgraph-error-handling — скилл для Claude Code: ошибки LangGraph

Скилл langgraph-error-handling для Claude Code помогает настраивать обработку ошибок в LangGraph. Подключается, когда нужно добавить повторы, восстановление через LLM или передачу решения человеку.

MIT ★ 106 обновлён 2026-11-11

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add soba-labs/langchain-agent-skills --skill langgraph-error-handling -a claude-code
Открыть на GitHub

Что делает langgraph-error-handling

Скилл помогает выбрать способ обработки ошибки в LangGraph и добавить его в граф: повтор для временного сбоя, возврат к узлу через Command или передачу на проверку человеку через interrupt() и возобновление. Для ошибок ToolNode он показывает варианты обработки, а для параллельных шагов объясняет транзакционное поведение: сбой одной ветки отменяет обновление состояния всего шага.

Внутри есть скрипты для классификации исключений и генерации заготовок узлов, а также примеры циклов повтора и согласования на Python и JS. Для потока с interrupt() граф нужно скомпилировать с checkpointer, а при возобновлении использовать прежний thread_id. В JS для маршрутизации через Command нужны ends в addNode; у повторов и циклов восстановления должны быть явные пределы.

Какие задачи решает

  • добавить RetryPolicy для временных ошибок API или базы данных
  • направить LLM к повторному вызову инструмента после исправления аргументов
  • приостановить граф до подтверждения человека и затем возобновить его
  • обработать ошибки ToolNode для восстановления модели
  • разобрать сбой параллельной ветки в транзакционном шаге

Примеры запросов агенту

  • Добавь RetryPolicy к узлу call_api для временных сбоев.
  • Настрой цикл, в котором LLM исправляет аргументы инструмента через Command.
  • Добавь подтверждение человеком через interrupt() и возобновление графа.

Как установить langgraph-error-handling

1Через Skills CLI (Vercel)

npx skills add soba-labs/langchain-agent-skills --skill langgraph-error-handling -a claude-code

2Вручную: положить файлы

~/.claude/skills/langgraph-error-handling/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/langgraph-error-handling/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о langgraph-error-handling

Как установить langgraph-error-handling в Claude Code?

Выполни npx skills add soba-labs/langchain-agent-skills --skill langgraph-error-handling -a claude-code. Файл скилла находится по пути ~/.claude/skills/langgraph-error-handling/SKILL.md.

Что делает langgraph-error-handling?

Помогает настроить повторы временных ошибок, восстановление через маршрутизацию Command и согласование с человеком через interrupt(). Также разбирает ошибки ToolNode и сбои параллельных шагов.

Что нужно для работы langgraph-error-handling с interrupt()?

Граф нужно скомпилировать с checkpointer. При возобновлении передавай тот же thread_id.

Исходный текст

SKILL.md · MIT
---
name: langgraph-error-handling
description: Implement LangGraph error handling with current v1 patterns. Use when users need to classify failures, add RetryPolicy for transient issues, build LLM recovery loops with Command routing, add human-in-the-loop with interrupt()/resume, handle ToolNode errors, or choose a safe strategy between retry, recovery, and escalation.
---

# LangGraph Error Handling

## Use This Skill For
- Adding `RetryPolicy` to flaky nodes (API, DB, model/tool calls)
- Designing LLM recovery loops (`Command` + error state + retry counters)
- Adding human approval/escalation with `interrupt()` and resume
- Handling prebuilt `ToolNode` failures
- Debugging transactional failure behavior in parallel supersteps

## Strategy Selection

Use this order:

1. Transient/infrastructure issue (`429`, timeout, `5xx`, temporary DB lock) -> `RetryPolicy`
2. Recoverable by model/tool args correction -> store error in state and route back with `Command`
3. Needs user approval or missing info -> `interrupt()` + resume
4. Unknown/programming bug -> let it bubble up and debug

| Error Type | Owner | Primary Mechanism |
|---|---|---|
| Transient | System | `RetryPolicy` |
| LLM-recoverable | LLM | State update + `Command(goto=...)` |
| User-fixable | Human | `interrupt()` + `Command(resume=...)` |
| Unexpected | Developer | Raise/log/debug |

For full taxonomy, load [references/error-types.md](references/error-types.md).

## Minimal Patterns

### 1) Retry Transient Failures

```python
from langgraph.types import RetryPolicy

builder.add_node(
    "call_api",
    call_api,
    retry_policy=RetryPolicy(max_attempts=3, initial_interval=1.0),
)
```

```ts
builder.addNode("callApi", callApi, {
  retryPolicy: { maxAttempts: 3, initialInterval: 1.0 },
});
```

Notes:
- Python and JS default retry behavior differs by exception type.
- Prefer targeted `retry_on`/`retryOn` for non-transient domains.

### 2) LLM Recovery Loop

Use `MessagesState` in Python for message state.

```python
from typing import Literal
from typing_extensions import NotRequired
from langgraph.graph import MessagesState
from langgraph.types import Command

class State(MessagesState):
    error: NotRequired[str]
    retry_count: NotRequired[int]

def agent(state: State) -> Command[Literal["tool", "__end__"]]:
    if state.get("retry_count", 0) >= 3:
        return Command(goto="__end__")
    if state.get("error"):
        return Command(goto="tool")
    return Command(goto="tool")
```

```ts
import { StateGraph, Command, END } from "@langchain/langgraph";

// If a node returns Command in JS, add `ends` on addNode.
builder.addNode("agent", agentNode, { ends: ["tool", END] });
```

### 3) Human-In-The-Loop Escalation

```python
from langgraph.types import interrupt, Command

def human_review(state):
    approved = interrupt({
        "question": "Proceed?",
        "payload": state["pending_action"],
    })
    return Command(goto="execute" if approved else "cancel")

# resume
graph.invoke(Command(resume=True), config={"configurable": {"thread_id": "t-1"}})
```

```ts
import { Command, interrupt } from "@langchain/langgraph";

const approved = interrupt({ question: "Proceed?" });
// later
await graph.invoke(new Command({ resume: true }), {
  configurable: { thread_id: "t-1" },
});
```

Requirements:
- Compile with a checkpointer for interrupt flows.
- Reuse the same `thread_id` on resume.

For deep HITL patterns, load [references/human-escalation.md](references/human-escalation.md).

## ToolNode Error Handling

```python
from langgraph.prebuilt import ToolNode

tool_node = ToolNode(tools, handle_tool_errors=True)
tool_node = ToolNode(tools, handle_tool_errors="Please try again.")
tool_node = ToolNode(tools, handle_tool_errors=(ValueError, TypeError))
```

Use custom handlers when you need deterministic error shaping for model recovery.
For broader tool-recovery design, load [references/llm-recovery.md](references/llm-recovery.md).

## Critical Behavior (Do Not Skip)

1. **Supersteps are transactional**: one failing parallel branch fails the whole superstep state update.
2. **RetryPolicy retries failing branches**, not successful siblings.
3. **`interrupt()` re-runs the node on resume**: side effects before interrupt must be idempotent, or moved after interrupt / separate node.
4. **JS `Command` routing requires `ends` metadata** on `addNode(...)`.
5. **Use explicit retry limits** (`max_attempts`, plus state counters for recovery loops).

## Local Assets In This Skill

### Scripts
- `scripts/classify_error.py`: classify exception category and recommended handling
- `scripts/wrap_with_retry.py`: generate boilerplate node wrappers with retry/recovery/escalation options

Run from repo root:

```bash
uv run skills/langgraph-error-handling/scripts/classify_error.py TimeoutError --verbose
uv run skills/langgraph-error-handling/scripts/wrap_with_retry.py call_llm --with-llm-recovery
```

### Examples
- `assets/examples/retry-example/`: retry + recovery loop (Python and JS)
- `assets/examples/human-loop-example/`: interrupt/resume approval flow (Python and JS)

## Load References On Demand

- `references/error-types.md`: error taxonomy and classification rules
- `references/retry-strategies.md`: retry tuning, backoff, circuit-breaker-style patterns
- `references/llm-recovery.md`: recovery-loop and ToolNode strategies
- `references/human-escalation.md`: human approval, interrupts, and escalation patterns

## Common Failure Modes

| Symptom | Root Cause | Fix |
|---|---|---|
| `interrupt()` fails at runtime | no checkpointer | compile with checkpointer |
| Resume starts new run | different `thread_id` | reuse same `thread_id` |
| JS Command route not taken | missing `ends` | add `ends` to `addNode` |
| Infinite loop | no termination counter/condition | add retry counter + terminal branch |
| Retry never triggers | exception excluded by retry filter | set explicit `retry_on`/`retryOn` |

© soba-labs · MIT · soba-labs/langchain-agent-skills

Похожие скиллы

Все скиллы по теме «ИИ и ML» →
python-error-handling Seth Hobson Скилл python-error-handling для Claude Code помогает проектировать проверку входных данных и обработку исключений в Python. Срабатывает при работе с API, пакетными задачами и стратегиями ошибок. CX Codex +1 14 116установок error-handling affaan-m Скилл error-handling задаёт единые правила обработки ошибок в TypeScript, Python и Go: типизированные исключения, ретраи, circuit breaker, тексты для пользователя. CX Codex +1 6 600установок iii-error-handling iii-hq Скилл iii-error-handling для Claude Code распознаёт коды ошибок iii-движка и SDK, различает сетевые сбои и отказы в доступе. Определяет, безопасно ли повторять вызов при работе с удалёнными функциями. CX Codex +1 5 000установок error-handling-patterns curiositech Скилл error-handling-patterns для Claude Code проектирует обработку ошибок в TypeScript и Python: помогает выбрать между исключениями и Result-типами и построить recovery-флоу. CX Codex +1 140установок error-handling-recovery zebbern Правило error-handling-recovery для Claude Code обрабатывает потерю WebGL-контекста, пересоздаёт ресурсы и показывает запасной интерфейс в Three.js-сценах. CX Codex +1 ★ 4 719звёзд репо dataverse-python-error-handling официальный github Правило dataverse-python-error-handling подсказывает, как обрабатывать ошибки Dataverse SDK for Python: разбирать коды ответа и решать, когда повторять запрос. CX Codex +1 ★ 41 430звёзд репо

Из того же набора9

langsmith-trace-analyzer Скилл langsmith-trace-analyzer для Claude Code скачивает и разбирает трассы LangSmith. Он включается при отладке агентов и оценке результатов по логам запусков. CX Codex +1 ★ 106звёзд репо langsmith-deployment Помогает разворачивать и обслуживать агентные серверы в LangSmith Deployment. Подключается при настройке langgraph.json, создании ревизий или разборе проблем с запуском. CX Codex +1 ★ 106звёзд репо langgraph-testing-evaluation Скилл langgraph-testing-evaluation для Claude Code проверяет и оценивает агентов LangGraph и LangChain. Он подключается к задачам с тестами узлов, оценкой траекторий и сравнением версий агента. CX Codex +1 ★ 106звёзд репо langgraph-state-management Скилл langgraph-state-management для Claude Code помогает проектировать состояние приложений LangGraph и разбирать проблемы с его обновлением. Включается при работе со схемами, редьюсерами и сохранением состояния. CX Codex +1 ★ 106звёзд репо langgraph-project-setup Скилл langgraph-project-setup для Claude Code помогает создать и настроить проект LangGraph. Он включается при настройке структуры, langgraph.json, переменных среды и зависимостей. CX Codex +1 ★ 106звёзд репо langgraph-agent-patterns Скилл langgraph-agent-patterns для Claude Code помогает собирать схемы координации агентов в приложениях на LangGraph. Он включается при выборе паттерна или отладке взаимодействия агентов. CX Codex +1 ★ 106звёзд репо deepagents-setup-configuration Скилл deepagents-setup-configuration для Claude Code создаёт и проверяет проекты Deep Agents на Python или JavaScript. Помогает настроить субагентов, память и подтверждение действий человеком. CX Codex +1 ★ 106звёзд репо deepagents-planning-todos Скилл deepagents-planning-todos для Claude Code помогает планировать задачи в Deep Agents через список дел write_todos. Он включается, когда нужно разбить работу на этапы, следить за прогрессом или выяснить, почему пункт не завершается. CX Codex +1 ★ 106звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой