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

deepagents-implementation — скилл для Claude Code: сборка агентов

Скилл deepagents-implementation для Claude Code даёт рецепты сборки агентов на Deep Agents: фабрика create_deep_agent, файловые бэкенды, субагенты и стриминг LangGraph.

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

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

Что делает deepagents-implementation

Скилл разбирает сборку агента на Deep Agents, обвязке поверх LangGraph. Внутри рецепты под фабрику create_deep_agent, middleware с доступом к файлам, списком задач, суммаризацией и субагентами, и четыре бэкенда, которые решают, где лежат файлы. На выходе получается скомпилированный StateGraph, поэтому стриминг, чекпоинты и Studio работают как в остальном LangGraph.

Примеры кода готовы к правке: инструмент через @tool, модель из init_chat_model, субагенты как словари со своим промптом, набором инструментов и моделью, готовые графы в обёртке CompiledSubAgent. Стриминг есть в режимах updates и messages, синхронный и асинхронный. С чекпоинтером в конфиг обязательно кладут thread_id, иначе продолжения диалога не будет.

StoreBackend ничего не сохранит между тредами без store, переданного агенту. А FilesystemBackend смотрит в настоящую папку на диске и заодно включает инструмент execute для shell-команд. Укажете путь к проекту — агент сможет эти файлы менять.

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

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

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

  • Собери агента через create_deep_agent с инструментом поиска в интернете и системным промптом исследователя
  • Переведи файлы под /memories/ на StoreBackend, чтобы они пережили перезапуск сессии
  • Добавь субагента-кодера с отдельной моделью и отдай ему задачу через task

Как установить deepagents-implementation

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill deepagents-implementation -a claude-code

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

~/.claude/skills/deepagents-implementation/SKILL.md

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

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

Вопросы о deepagents-implementation

Как установить deepagents-implementation в Claude Code?

Выполните npx skills add existential-birds/beagle --skill deepagents-implementation -a claude-code. Файл скилла окажется по пути ~/.claude/skills/deepagents-implementation/SKILL.md.

Что делает deepagents-implementation?

Показывает, как собрать агента на Deep Agents: фабрика, middleware, бэкенды для файлов, субагенты, чекпоинты и режимы стриминга LangGraph.

Чем FilesystemBackend отличается от StateBackend?

StateBackend держит файлы в состоянии агента и живёт в пределах треда. FilesystemBackend читает и пишет на реальный диск и дополнительно включает инструмент execute для shell-команд.

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

SKILL.md · Apache-2.0
---
name: deepagents-implementation
description: Implements agents using Deep Agents. Use when building agents with create_deep_agent, configuring backends, defining subagents, adding middleware, or setting up human-in-the-loop workflows.
---

# Deep Agents Implementation

## Core Concepts

Deep Agents provides a batteries-included agent harness built on LangGraph:

- **`create_deep_agent`**: Factory function that creates a configured agent
- **Middleware**: Injected capabilities (filesystem, todos, subagents, summarization)
- **Backends**: Pluggable file storage (state, filesystem, store, composite)
- **Subagents**: Isolated task execution via the `task` tool

The agent returned is a compiled LangGraph `StateGraph`, compatible with streaming, checkpointing, and LangGraph Studio.

## Essential Imports

```python
# Core
from deepagents import create_deep_agent

# Subagents
from deepagents import CompiledSubAgent

# Backends
from deepagents.backends import (
    StateBackend,       # Ephemeral (default)
    FilesystemBackend,  # Real disk
    StoreBackend,       # Persistent cross-thread
    CompositeBackend,   # Route paths to backends
)

# LangGraph (for checkpointing, store, streaming)
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.store.memory import InMemoryStore

# LangChain (for custom models, tools)
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
```

## Basic Usage

### Minimal Agent

```python
from deepagents import create_deep_agent

# Uses Claude Sonnet 4 by default
agent = create_deep_agent()

result = agent.invoke({"messages": [{"role": "user", "content": "Hello!"}]})
```

### With Custom Tools

```python
from langchain_core.tools import tool
from deepagents import create_deep_agent

@tool
def web_search(query: str) -> str:
    """Search the web for information."""
    return tavily_client.search(query)

agent = create_deep_agent(
    tools=[web_search],
    system_prompt="You are a research assistant. Search the web to answer questions.",
)

result = agent.invoke({"messages": [{"role": "user", "content": "What is LangGraph?"}]})
```

### With Custom Model

```python
from langchain.chat_models import init_chat_model
from deepagents import create_deep_agent

# OpenAI
model = init_chat_model("openai:gpt-4o")

# Or Anthropic with custom settings
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model_name="claude-sonnet-4-5-20250929", max_tokens=8192)

agent = create_deep_agent(model=model)
```

### With Checkpointing (Persistence)

```python
from langgraph.checkpoint.memory import InMemorySaver
from deepagents import create_deep_agent

agent = create_deep_agent(checkpointer=InMemorySaver())

# Must provide thread_id with checkpointer
config = {"configurable": {"thread_id": "user-123"}}
result = agent.invoke({"messages": [...]}, config)

# Resume conversation
result = agent.invoke({"messages": [{"role": "user", "content": "Follow up"}]}, config)
```

## Streaming

The agent supports all LangGraph stream modes.

### Stream Updates

```python
for chunk in agent.stream(
    {"messages": [{"role": "user", "content": "Write a report"}]},
    stream_mode="updates"
):
    print(chunk)  # {"node_name": {"key": "value"}}
```

### Stream Messages (Token-by-Token)

```python
for chunk in agent.stream(
    {"messages": [{"role": "user", "content": "Explain quantum computing"}]},
    stream_mode="messages"
):
    # Real-time token streaming
    print(chunk.content, end="", flush=True)
```

### Async Streaming

```python
async for chunk in agent.astream(
    {"messages": [...]},
    stream_mode="updates"
):
    print(chunk)
```

### Multiple Stream Modes

```python
for mode, chunk in agent.stream(
    {"messages": [...]},
    stream_mode=["updates", "messages"]
):
    if mode == "messages":
        print("Token:", chunk.content)
    else:
        print("Update:", chunk)
```

## Backend Configuration

### StateBackend (Default - Ephemeral)

Files stored in agent state, persist within thread only.

```python
# Implicit - this is the default
agent = create_deep_agent()

# Explicit
from deepagents.backends import StateBackend
agent = create_deep_agent(backend=lambda rt: StateBackend(rt))
```

### FilesystemBackend (Real Disk)

Read/write actual files on disk. Enables `execute` tool for shell commands.

```python
from deepagents.backends import FilesystemBackend

agent = create_deep_agent(
    backend=FilesystemBackend(root_dir="/path/to/project"),
)
```

### StoreBackend (Persistent Cross-Thread)

Uses LangGraph Store for persistence across conversations.

```python
from langgraph.store.memory import InMemoryStore
from deepagents.backends import StoreBackend

store = InMemoryStore()

agent = create_deep_agent(
    backend=lambda rt: StoreBackend(rt),
    store=store,  # Required for StoreBackend
)
```

### CompositeBackend (Hybrid Routing)

Route different paths to different backends.

```python
from langgraph.store.memory import InMemoryStore
from deepagents.backends import CompositeBackend, StateBackend, StoreBackend

store = InMemoryStore()

agent = create_deep_agent(
    backend=CompositeBackend(
        default=StateBackend(),           # /workspace/* → ephemeral
        routes={
            "/memories/": StoreBackend(store=store),     # persistent
            "/preferences/": StoreBackend(store=store), # persistent
        },
    ),
    store=store,
)

# Files under /memories/ persist across all conversations
# Files under /workspace/ are ephemeral per-thread
```

## Subagents

### Using the Default General-Purpose Agent

By default, a `general-purpose` subagent is available with all main agent tools.

```python
agent = create_deep_agent(tools=[web_search])

# The agent can now delegate via the `task` tool:
# task(subagent_type="general-purpose", prompt="Research topic X in depth")
```

### Defining Custom Subagents

```python
from deepagents import create_deep_agent

research_agent = {
    "name": "researcher",
    "description": "Conducts deep research on complex topics with web search",
    "system_prompt": """You are an expert researcher.
    Search thoroughly, cross-reference sources, and synthesize findings.""",
    "tools": [web_search, document_reader],
}

code_agent = {
    "name": "coder",
    "description": "Writes, reviews, and debugs code",
    "system_prompt": "You are an expert programmer. Write clean, tested code.",
    "tools": [code_executor, linter],
    "model": "openai:gpt-4o",  # Optional: different model per subagent
}

agent = create_deep_agent(
    subagents=[research_agent, code_agent],
    system_prompt="Delegate research to the researcher and coding to the coder.",
)
```

### Pre-compiled LangGraph Subagents

Use existing LangGraph graphs as subagents.

```python
from deepagents import CompiledSubAgent, create_deep_agent
from langgraph.prebuilt import create_react_agent

# Existing graph
custom_graph = create_react_agent(
    model="anthropic:claude-sonnet-4-5-20250929",
    tools=[specialized_tool],
    prompt="Custom workflow instructions",
)

agent = create_deep_agent(
    subagents=[CompiledSubAgent(
        name="custom-workflow",
        description="Runs my specialized analysis workflow",
        runnable=custom_graph,
    )]
)
```

### Subagent with Custom Middleware

```python
from langchain.agents.middleware import AgentMiddleware

class LoggingMiddleware(AgentMiddleware):
    def transform_response(self, response):
        print(f"Subagent response: {response}")
        return response

agent_spec = {
    "name": "logged-agent",
    "description": "Agent with extra logging",
    "system_prompt": "You are helpful.",
    "tools": [],
    "middleware": [LoggingMiddleware()],  # Added after default middleware
}
```

## Human-in-the-Loop

### Basic Interrupt Configuration

Pause execution before specific tools for human approval.

```python
from deepagents import create_deep_agent

agent = create_deep_agent(
    tools=[send_email, delete_file, web_search],
    interrupt_on={
        "send_email": True,      # Simple interrupt
        "delete_file": True,     # Require approval before delete
        # web_search not listed - runs without approval
    },
    checkpointer=checkpointer,   # Required for interrupts
)
```

### Interrupt with Options

```python
agent = create_deep_agent(
    tools=[send_email],
    interrupt_on={
        "send_email": {
            "allowed_decisions": ["approve", "edit", "reject"]
        },
    },
    checkpointer=checkpointer,
)

# Invoke - will pause at send_email
config = {"configurable": {"thread_id": "user-123"}}
result = agent.invoke({"messages": [...]}, config)

# Check state
state = agent.get_state(config)
if state.next:  # Has pending interrupt
    # Resume with approval
    from langgraph.types import Command
    agent.invoke(Command(resume={"approved": True}), config)

    # Or resume with edit
    agent.invoke(Command(resume={"edited_args": {"to": "[email protected]"}}), config)

    # Or reject
    agent.invoke(Command(resume={"rejected": True}), config)
```

### Interrupt on Subagent Tools

```python
# Interrupts apply to subagents too
agent = create_deep_agent(
    subagents=[research_agent],
    interrupt_on={
        "web_search": True,  # Interrupt even when subagent calls it
    },
    checkpointer=checkpointer,
)
```

## Custom Middleware

### Middleware Structure

```python
from langchain.agents.middleware.types import (
    AgentMiddleware,
    ModelRequest,
    ModelResponse,
)
from langchain_core.tools import tool

class MyMiddleware(AgentMiddleware):
    # Tools to inject
    tools = []

    # System prompt content to inject
    system_prompt = ""

    def transform_request(self, request: ModelRequest) -> ModelRequest:
        """Modify request before sending to model."""
        return request

    def transform_response(self, response: ModelResponse) -> ModelResponse:
        """Modify response after receiving from model."""
        return response
```

### Injecting Tools via Middleware

```python
from langchain_core.tools import tool

@tool
def get_current_time() -> str:
    """Get the current time."""
    from datetime import datetime
    return datetime.now().isoformat()

class TimeMiddleware(AgentMiddleware):
    tools = [get_current_time]
    system_prompt = "You have access to get_current_time for time-sensitive tasks."

agent = create_deep_agent(middleware=[TimeMiddleware()])
```

### Context Injection Middleware

```python
class UserContextMiddleware(AgentMiddleware):
    def __init__(self, user_preferences: dict):
        self.user_preferences = user_preferences

    @property
    def system_prompt(self):
        return f"User preferences: {self.user_preferences}"

agent = create_deep_agent(
    middleware=[UserContextMiddleware({"theme": "dark", "language": "en"})]
)
```

### Response Logging Middleware

```python
import logging

class LoggingMiddleware(AgentMiddleware):
    def transform_response(self, response: ModelResponse) -> ModelResponse:
        logging.info(f"Agent response: {response.messages[-1].content[:100]}...")
        return response

agent = create_deep_agent(middleware=[LoggingMiddleware()])
```

## MCP Tool Integration

Connect MCP (Model Context Protocol) servers to provide additional tools.

```python
from langchain_mcp_adapters.client import MultiServerMCPClient
from deepagents import create_deep_agent

async def main():
    mcp_client = MultiServerMCPClient({
        "filesystem": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"],
        },
        "github": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-github"],
            "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
        },
    })

    mcp_tools = await mcp_client.get_tools()

    agent = create_deep_agent(tools=mcp_tools)

    async for chunk in agent.astream(
        {"messages": [{"role": "user", "content": "List my repos"}]}
    ):
        print(chunk)
```

## Implementation gates

Use this **sequenced** table for setups that touch **real disk, human interrupts, persistence, or MCP subprocesses** (skip for minimal `create_deep_agent()` smoke tests).

| Step | Pass condition |
|------|----------------|
| 1 | **FilesystemBackend or `execute`:** `root_dir` is deliberately scoped (not an accidental home or filesystem root); smoke-test in a disposable directory before trusting production paths. |
| 2 | **`interrupt_on` / resume:** A `checkpointer` is configured; every `invoke` / `astream` that may interrupt includes `config` with `configurable["thread_id"]`; after a pause, `agent.get_state(config)` shows pending interrupt state before `Command(resume=...)`, and the resume payload matches tool options (e.g. `allowed_decisions`) when set. |
| 3 | **Store, PostgreSQL saver, MCP:** Credentials come from environment or a secret manager, not committed source; MCP `command` / `args` / required `env` keys match what the deployment host actually provides (e.g. `npx`, tokens). |

## Additional References

For detailed reference documentation, see:

- **[Built-in Tools Reference](references/tools.md)** - Complete list of tools available on every agent (filesystem, task management, subagent delegation) with path requirements
- **[Common Patterns](references/patterns.md)** - Production-ready examples including research agents with memory, code assistants with disk access, multi-specialist teams, and production PostgreSQL setup

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

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

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
langchain-build-agent langchain-ai Скилл langchain-build-agent для Claude Code помогает проектировать и связывать агентов на Deep Agents, LangGraph и LangChain. Он выбирает архитектуру под задачу и согласует версии библиотек. CX Codex +1 352установок deepagents-setup-configuration soba-labs Скилл deepagents-setup-configuration для Claude Code создаёт и проверяет проекты Deep Agents на Python или JavaScript. Помогает настроить субагентов, память и подтверждение действий человеком. CX Codex +1 ★ 106звёзд репо deepagents-typescript-quickstart langchain-ai Скилл deepagents-typescript-quickstart собирает минимального Deep Agent на TypeScript по официальному квикстарту, с встроенным веб-поиском провайдера вместо Tavily. CX Codex +1 5 900установок migrating-deep-agents-to-pydantic-ai-harness pydantic Скилл migrating-deep-agents-to-pydantic-ai-harness для Claude Code переносит Python-приложения LangChain Deep Agents на Pydantic AI и Pydantic AI Harness. Работает с контрактами middleware, памяти, субагентов и sandbox. CX Codex +1 234установок instrumenting-with-mlflow-tracing mlflow Скилл instrumenting-with-mlflow-tracing добавляет или чинит MLflow tracing в Python и TypeScript: автологирование фреймворков, свои спаны, проверка сохранённых трейсов. CX Codex +1 1 100установок langchain-development Mindrally Скилл langchain-development для Claude Code: задаёт правила разработки на LangChain и LangGraph — композиция цепочек, агенты, память, RAG. Держит Python-проект в едином стиле. CX Codex +1 726установок

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

Весь набор →
llm-artifacts-detection Скилл llm-artifacts-detection находит типичный мусор после ИИ-кодеров: лишние слои абстракций, тесты стандартных библиотек, мёртвый код и очевидные комментарии. CX Codex +1 151установок go-testing-code-review Скилл go-testing-code-review ревьюит тесты Go: табличные кейсы, сообщения об ошибках, параллельность и покрытие. Замечания отдаёт с файлом, строкой и важностью. CX Codex +1 148установок pydantic-ai-testing Скилл pydantic-ai-testing помогает писать тесты для агентов PydanticAI: подменять ответы модели, проверять вызовы инструментов и воспроизводить записанные API-запросы. CX Codex +1 146установок adr-decision-extraction Скилл adr-decision-extraction извлекает архитектурные решения из чатов и расшифровок, чтобы подготовить материал для ADR. Он распознаёт выбор технологий, компромиссы и явные метки. CX Codex +1 144установок llm-judge Скилл llm-judge сравнивает две и более реализации одной задачи по файлу спецификации: собирает факты, ставит оценки по пяти измерениям и выдаёт отчёт с победителем. CX Codex +1 141установок pydantic-ai-dependency-injection Скилл pydantic-ai-dependency-injection показывает, как передавать базы данных, API-клиенты и контекст пользователя в PydanticAI через RunContext и deps_type. CX Codex +1 141установок watchos-code-review Скилл watchos-code-review для Claude Code проверяет watchOS-код на ошибки жизненного цикла, осложнений, WatchConnectivity и ограничения производительности. CX Codex +1 137установок swiftdata-code-review Скилл swiftdata-code-review проверяет код SwiftData на ошибки в моделях, предикатах, миграциях и конкурентности. Запускается при ревью файлов со связками @Model и @Query. CX Codex +1 136установок

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

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