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

langgraph-architecture — скилл для Claude Code: выбор архитектуры

Скилл langgraph-architecture для Claude Code помогает выбрать структуру LangGraph-приложения, схему состояния и подход к хранению данных. Сравнивает LangGraph с альтернативами и помогает проектировать системы агентов.

Apache-2.0 283 установок ★ 89 обновлён 2026-09-15

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

Что делает langgraph-architecture

Скилл разбирает, когда LangGraph оправдан, а когда задачу проще решить прямым вызовом API, линейным конвейером или обычным function calling. Он помогает выбрать TypedDict или Pydantic, подобрать reducer и решить, хранить ли данные в состоянии или вынести их в Store.

Внутри есть схемы для выбора между одним графом и подграфами, условными переходами и Command, разными паттернами мультиагентной архитектуры, режимами потоковой передачи и обработчиками прерываний. Также описаны checkpointer’ы: InMemorySaver теряет данные после перезапуска, поэтому для сохранения между запусками он не подходит.

Рекомендации привязаны к конкретным сценариям, а не к одному универсальному устройству графа. Скилл рассчитан на проектирование LangGraph-приложений; для одиночного вызова LLM он советует рассмотреть прямой API.

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

  • выбрать LangGraph или более простой способ вызова модели
  • определить схему состояния и подходящий reducer
  • решить, когда разбивать граф на подграфы
  • подобрать хранилище контрольных точек
  • спроектировать маршрутизацию и передачу управления между агентами

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

  • Сравни LangGraph с прямым вызовом API для этого сценария и объясни выбор.
  • Предложи схему состояния LangGraph для диалога с проверкой данных.
  • Помоги выбрать паттерн мультиагентной архитектуры и стратегию сохранения состояния.

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

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill langgraph-architecture -a claude-code

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

~/.claude/skills/langgraph-architecture/SKILL.md

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

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

Вопросы о langgraph-architecture

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

Выполните npx skills add existential-birds/beagle --skill langgraph-architecture -a claude-code. Файл скилла: ~/.claude/skills/langgraph-architecture/SKILL.md.

Что делает langgraph-architecture?

Скилл помогает принимать архитектурные решения для LangGraph: выбирать схему состояния, структуру графа, сохранение данных и потоковую передачу.

Какой checkpointer выбрать для разработки?

В рекомендациях для разработки указан SqliteSaver: он хранит данные локально в одном файле. InMemorySaver предназначен для тестов и теряет данные после перезапуска.

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

SKILL.md · Apache-2.0
---
name: langgraph-architecture
description: Guides architectural decisions for LangGraph applications. Use when deciding between LangGraph vs alternatives, choosing state management strategies, designing multi-agent systems, or selecting persistence and streaming approaches.
---

# LangGraph Architecture Decisions

## When to Use LangGraph

### Use LangGraph When You Need:

- **Stateful conversations** - Multi-turn interactions with memory
- **Human-in-the-loop** - Approval gates, corrections, interventions
- **Complex control flow** - Loops, branches, conditional routing
- **Multi-agent coordination** - Multiple LLMs working together
- **Persistence** - Resume from checkpoints, time travel debugging
- **Streaming** - Real-time token streaming, progress updates
- **Reliability** - Retries, error recovery, durability guarantees

### Consider Alternatives When:

| Scenario | Alternative | Why |
|----------|-------------|-----|
| Single LLM call | Direct API call | Overhead not justified |
| Linear pipeline | LangChain LCEL | Simpler abstraction |
| Stateless tool use | Function calling | No persistence needed |
| Simple RAG | LangChain retrievers | Built-in patterns |
| Batch processing | Async tasks | Different execution model |

## State Schema Decisions

### TypedDict vs Pydantic

| TypedDict | Pydantic |
|-----------|----------|
| Lightweight, faster | Runtime validation |
| Dict-like access | Attribute access |
| No validation overhead | Type coercion |
| Simpler serialization | Complex nested models |

**Recommendation**: Use TypedDict for most cases. Use Pydantic when you need validation or complex nested structures.

### Reducer Selection

| Use Case | Reducer | Example |
|----------|---------|---------|
| Chat messages | `add_messages` | Handles IDs, RemoveMessage |
| Simple append | `operator.add` | `Annotated[list, operator.add]` |
| Keep latest | None (LastValue) | `field: str` |
| Custom merge | Lambda | `Annotated[list, lambda a, b: ...]` |
| Overwrite list | `Overwrite` | Bypass reducer |

### State Size Considerations

```python
# SMALL STATE (< 1MB) - Put in state
class State(TypedDict):
    messages: Annotated[list, add_messages]
    context: str

# LARGE DATA - Use Store
class State(TypedDict):
    messages: Annotated[list, add_messages]
    document_ref: str  # Reference to store

def node(state, *, store: BaseStore):
    doc = store.get(namespace, state["document_ref"])
    # Process without bloating checkpoints
```

## Graph Structure Decisions

### Single Graph vs Subgraphs

**Single Graph** when:
- All nodes share the same state schema
- Simple linear or branching flow
- < 10 nodes

**Subgraphs** when:
- Different state schemas needed
- Reusable components across graphs
- Team separation of concerns
- Complex hierarchical workflows

### Conditional Edges vs Command

| Conditional Edges | Command |
|------------------|---------|
| Routing based on state | Routing + state update |
| Separate router function | Decision in node |
| Clearer visualization | More flexible |
| Standard patterns | Dynamic destinations |

```python
# Conditional Edge - when routing is the focus
def router(state) -> Literal["a", "b"]:
    return "a" if condition else "b"
builder.add_conditional_edges("node", router)

# Command - when combining routing with updates
def node(state) -> Command:
    return Command(goto="next", update={"step": state["step"] + 1})
```

### Static vs Dynamic Routing

**Static Edges** (`add_edge`):
- Fixed flow known at build time
- Clearer graph visualization
- Easier to reason about

**Dynamic Routing** (`add_conditional_edges`, `Command`, `Send`):
- Runtime decisions based on state
- Agent-driven navigation
- Fan-out patterns

## Persistence Strategy

### Checkpointer Selection

| Checkpointer | Use Case | Characteristics |
|--------------|----------|-----------------|
| `InMemorySaver` | Testing only | Lost on restart |
| `SqliteSaver` | Development | Single file, local |
| `PostgresSaver` | Production | Scalable, concurrent |
| Custom | Special needs | Implement BaseCheckpointSaver |

### Checkpointing Scope

```python
# Full persistence (default)
graph = builder.compile(checkpointer=checkpointer)

# Subgraph options
subgraph = sub_builder.compile(
    checkpointer=None,   # Inherit from parent
    checkpointer=True,   # Independent checkpointing
    checkpointer=False,  # No checkpointing (runs atomically)
)
```

### When to Disable Checkpointing

- Short-lived subgraphs that should be atomic
- Subgraphs with incompatible state schemas
- Performance-critical paths without need for resume

## Multi-Agent Architecture

### Supervisor Pattern

Best for:
- Clear hierarchy
- Centralized decision making
- Different agent specializations

```
          ┌─────────────┐
          │  Supervisor │
          └──────┬──────┘
    ┌────────┬───┴───┬────────┐
    ▼        ▼       ▼        ▼
┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
│Agent1│ │Agent2│ │Agent3│ │Agent4│
└──────┘ └──────┘ └──────┘ └──────┘
```

### Peer-to-Peer Pattern

Best for:
- Collaborative agents
- No clear hierarchy
- Flexible communication

```
┌──────┐     ┌──────┐
│Agent1│◄───►│Agent2│
└──┬───┘     └───┬──┘
   │             │
   ▼             ▼
┌──────┐     ┌──────┐
│Agent3│◄───►│Agent4│
└──────┘     └──────┘
```

### Handoff Pattern

Best for:
- Sequential specialization
- Clear stage transitions
- Different capabilities per stage

```
┌────────┐    ┌────────┐    ┌────────┐
│Research│───►│Planning│───►│Execute │
└────────┘    └────────┘    └────────┘
```

## Streaming Strategy

### Stream Mode Selection

| Mode | Use Case | Data |
|------|----------|------|
| `updates` | UI updates | Node outputs only |
| `values` | State inspection | Full state each step |
| `messages` | Chat UX | LLM tokens |
| `custom` | Progress/logs | Your data via StreamWriter |
| `debug` | Debugging | Tasks + checkpoints |

### Subgraph Streaming

```python
# Stream from subgraphs
async for chunk in graph.astream(
    input,
    stream_mode="updates",
    subgraphs=True  # Include subgraph events
):
    namespace, data = chunk  # namespace indicates depth
```

## Human-in-the-Loop Design

### Interrupt Placement

| Strategy | Use Case |
|----------|----------|
| `interrupt_before` | Approval before action |
| `interrupt_after` | Review after completion |
| `interrupt()` in node | Dynamic, contextual pauses |

### Resume Patterns

```python
# Simple resume (same thread)
graph.invoke(None, config)

# Resume with value
graph.invoke(Command(resume="approved"), config)

# Resume specific interrupt
graph.invoke(Command(resume={interrupt_id: value}), config)

# Modify state and resume
graph.update_state(config, {"field": "new_value"})
graph.invoke(None, config)
```

## Gates (sequenced)

Complete **in order** before treating a LangGraph design as locked in. Each step has an objective **pass condition** (artifact or explicit “none”), not an honor-system “we considered it.”

1. **Alternatives** — **Pass:** For the workload, either (a) at least one row from [Consider Alternatives When](#consider-alternatives-when) was evaluated and rejected with a one-line reason, or (b) the use case clearly matches [Use LangGraph When You Need](#use-langgraph-when-you-need) and does not fit a “consider alternative” row.
2. **State contract** — **Pass:** Every state field has an assigned reducer (or default/LastValue) documented in the same place as the schema; large payloads are references or Store-backed, not inlined blobs (see [State Size Considerations](#state-size-considerations)).
3. **Checkpointer** — **Pass:** The saver type is chosen for the target environment per [Checkpointer Selection](#checkpointer-selection) (e.g. production is not `InMemorySaver` unless explicitly test-only).
4. **Loops and flaky nodes** — **Pass:** `recursion_limit` (or equivalent) is set for any graph that can cycle; per-node `RetryPolicy` or a documented “no retries” choice exists for external calls (see [Retry Configuration](#retry-configuration)).

## Error Handling Strategy

### Retry Configuration

```python
# Per-node retry
RetryPolicy(
    initial_interval=0.5,
    backoff_factor=2.0,
    max_interval=60.0,
    max_attempts=3,
    retry_on=lambda e: isinstance(e, (APIError, TimeoutError))
)

# Multiple policies (first match wins)
builder.add_node("node", fn, retry_policy=[
    RetryPolicy(retry_on=RateLimitError, max_attempts=5),
    RetryPolicy(retry_on=Exception, max_attempts=2),
])
```

### Fallback Patterns

```python
def node_with_fallback(state):
    try:
        return primary_operation(state)
    except PrimaryError:
        return fallback_operation(state)

# Or use conditional edges for complex fallback routing
def route_on_error(state) -> Literal["retry", "fallback", "__end__"]:
    if state.get("error") and state["attempts"] < 3:
        return "retry"
    elif state.get("error"):
        return "fallback"
    return END
```

## Scaling Considerations

### Horizontal Scaling

- Use PostgresSaver for shared state
- Consider LangGraph Platform for managed infrastructure
- Use stores for large data outside checkpoints

### Performance Optimization

1. **Minimize state size** - Use references for large data
2. **Parallel nodes** - Fan out when possible
3. **Cache expensive operations** - Use CachePolicy
4. **Async everywhere** - Use ainvoke, astream

### Resource Limits

```python
# Set recursion limit
config = {"recursion_limit": 50}
graph.invoke(input, config)

# Track remaining steps in state
class State(TypedDict):
    remaining_steps: RemainingSteps

def check_budget(state):
    if state["remaining_steps"] < 5:
        return "wrap_up"
    return "continue"
```

## Decision Checklist

After [Gates (sequenced)](#gates-sequenced), before implementing:

1. [ ] Is LangGraph the right tool? (vs simpler alternatives)
2. [ ] State schema defined with appropriate reducers?
3. [ ] Persistence strategy chosen? (dev vs prod checkpointer)
4. [ ] Streaming needs identified?
5. [ ] Human-in-the-loop points defined?
6. [ ] Error handling and retry strategy?
7. [ ] Multi-agent coordination pattern? (if applicable)
8. [ ] Resource limits configured?

© existential-birds · Apache-2.0 · existential-birds/beagle

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

Все скиллы по теме «ИИ и ML» →
langgraph-human-in-the-loop langchain-ai Скилл langgraph-human-in-the-loop для Claude Code и других платформ: строит графы LangGraph с паузами, ждущими человеческого ввода, одобрения или валидации. CX Codex +1 18 300установок langgraph sickn33 Строит явные графы LangGraph вместо неявных цепочек вызовов. Организует stateful-агентов с ветвлениями и паузами на решение человека. CX Codex +1 1 300установок langgraph-fundamentals langchain-ai Скилл langgraph-fundamentals для написания кода LangGraph на любой платформе. Охватывает StateGraph, схемы состояния, ноды, рёбра, Command, Send, invoke, потоковую передачу и обработку ошибок. CX Codex +1 19 300установок options-analytics-agent-langgraph reason-machines Скилл options-analytics-agent-langgraph для Claude Code и Codex. Собирает агента на LangGraph для анализа опционов: интегрирует данные Polygon.io, кэширует результаты в ChromaDB, сохраняет историю диалога в SQLite. CX Codex +1 2 100установок ns-langgraph-agents nextstage-brasil Скилл ns-langgraph-agents для Claude Code, Codex, Cursor и других платформ, который ведёт разработку LangGraph.js agent-api от начального развёртывания до синхронизации graph-spec. CX Codex +1 171установок langgraph-testing-evaluation soba-labs Скилл langgraph-testing-evaluation для Claude Code проверяет и оценивает агентов LangGraph и LangChain. Он подключается к задачам с тестами узлов, оценкой траекторий и сравнением версий агента. CX Codex +1 ★ 106звёзд репо

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

Весь набор →
fastapi-code-review Скилл fastapi-code-review проверяет сервисы на FastAPI: выявляет синхронные блокировки в асинхронных роутах, пропущенные Depends() и ошибки в Pydantic-моделях. CX Codex +1 391установок react-flow-implementation Скилл react-flow-implementation направляет агента при создании диаграмм и визуальных редакторов на базе @xyflow/react. Помогает избежать типичных ошибок с рендером узлов и связей. CX Codex +1 382установок shadcn-ui Учит агента строить UI-компоненты по паттернам shadcn/ui — CVA-варианты, составные компоненты, data-slot-атрибуты. CX Codex +1 358установок react-flow-code-review Скилл react-flow-code-review для Claude Code и Codex проверяет код на @xyflow/react по чек-листу: антипаттерны, лишние ре-рендеры, типы. Фиксирует тормоза графа и пересоздание нод. CX Codex +1 329установок swiftui-code-review Скилл swiftui-code-review для Claude Code проверяет SwiftUI-код: композицию представлений, состояние, производительность и доступность. Разбирает файлы с @State, @Binding, @Observable и UI-кодом. CX Codex +1 277установок tutorial-docs Скилл tutorial-docs для Claude Code задаёт структуру обучающих руководств по методологии Diataxis. Агент подключает его при написании вводных уроков и пошаговых руководств для новичков. CX Codex +1 273установок bubbletea-code-review Скилл bubbletea-code-review для Claude Code проверяет Go-код BubbleTea-проектов: архитектуру Elm, цикл Update и стили Lipgloss. CX Codex +1 270установок zustand-state Скилл zustand-state для Claude Code помогает создавать хранилища Zustand, выбирать данные селекторами, сохранять их в localStorage и подключать devtools. CX Codex +1 261установок

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

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