Claude
Skills
Sign in
Back

langchain-deep-agents

Included with Lifetime
$97 forever

Build a LangGraph 1.0 Deep Agent — planner + subagents + virtual filesystem + reflection loop — without the state-growth and prompt-inheritance traps. Use when building a long-horizon agent that must plan, delegate subtasks, work against a scratchpad filesystem, and reflect on progress. Trigger with "langchain deep agent", "planner subagent", "virtual filesystem agent", "reflection loop", "langgraph deep agent".

Ads & Marketingsaaslangchainlanggraphpythonlangchain-1.0agentsdeep-agentsresearch

What this skill does

# LangChain Deep Agents (Python)

## Overview

Two pains bite every team reproducing LangChain's late-2025 Deep Agents blueprint.

**Virtual-FS state grows unboundedly (P51).** The planner and every subagent
write plans, scratch notes, intermediate drafts, and tool outputs into
`state["files"]`. Nothing ever evicts them. After 50 tool calls, the checkpointed
state is **8 MB**; every `MemorySaver.put()` takes **400 ms**; a run that started
at 1.2 s per node visit ends at 2.5 s per node visit. The LangSmith trace viewer
times out loading the thread. The user sees latency doubling over the run with
no obvious tool-level culprit.

**Subagent persona leak (P52).** The naive prompt-composition inside the
blueprint APPENDS the subagent role message to the parent's system message
instead of replacing it. The research-specialist subagent receives:
`"You are a senior planner coordinating subagents..."` + `"You are a research
specialist..."` — and responds as the planner. It produces generic task
decomposition instead of the specific lookup you asked for. The bug is invisible
in unit tests because both messages "sound right" to a reviewer.

This skill pins to `langgraph 1.0.x` + `langchain-core 1.0.x` and walks through
the four-component Deep Agent pattern — **planner**, **subagent pool** of 3-8
role-specialized workers, **virtual filesystem** with eviction, **reflection
node** with bounded depth 3-5 — and shows exactly how to avoid P51 (cleanup
node + checkpoint-on-boundary) and P52 (explicit `SystemMessage(override=True)`
for every subagent). Pain-catalog anchors: **P51, P52**.

## Prerequisites

- Python 3.10+
- `langgraph >= 1.0, < 2.0` and `langchain-core >= 1.0, < 2.0`
- At least one provider package: `pip install langchain-anthropic` or `langchain-openai`
- Completed skills:
  - `langchain-langgraph-agents` (L26) — you already know `create_react_agent`,
    tool schemas, recursion limits
  - `langchain-langgraph-subgraphs` (L30) — subagent ≈ subgraph with a bounded
    contract; if L30 is not yet installed, the subagent construction in Step 3
    is self-contained
- Provider API key: `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`
- Recommended: `langchain-eval-harness` skill installed for trajectory-level eval

## Instructions

### Step 1 — Understand the four-component architecture

A Deep Agent has four components. Each has a fixed contract; violating a
contract is exactly where P51 / P52 show up.

| Component | Input | Output | Invariants |
|-----------|-------|--------|------------|
| **Planner** | User goal, current `state["plan"]`, current `state["files"]` summary (not full contents) | An ordered list of subtasks; each subtask has `{subagent_role, instruction, expected_artifact_name}` | Must NOT write to `state["files"]` directly. Only emits plan + assignments. |
| **Subagent** | `{subagent_role, instruction, read_files: [names]}` from planner | `{artifact_name, content, status}` back to planner via structured output | Receives a fresh `SystemMessage` with `override=True` — no parent prompt inheritance (P52). Typical pool size: **3-8**. |
| **Virtual FS** | Writes from subagents (never from planner) | Reads by planner (summaries) and subagents (full content) | Bounded. Cleanup node evicts entries older than N steps or `status=="done"` (P51). |
| **Reflection** | Plan vs actual artifacts produced, subagent errors, step count | Decision: `continue` / `replan` / `end` / `escalate_to_human` | Runs at most **3-5** times per user-facing turn. |

The graph topology:

```
START -> planner -> (for each subtask) subagent_dispatcher -> virtual_fs_write
                                             |
                                             v
                                        reflection -> planner (replan)
                                                   -> END (done)
                                                   -> interrupt (escalate)
```

The cleanup node is an edge-less side-effect node hooked onto the reflection
transition — it prunes `state["files"]` before the next planner step runs.

### Step 2 — Build the planner prompt skeleton

The planner's prompt must be narrow. It decomposes, assigns, and revises —
that is all. It does not answer the user's question itself.

```python
PLANNER_SYSTEM = """You are the planner for a Deep Agent.

Your job is to decompose the user's goal into subtasks and assign each to a
specialized subagent. You do NOT execute subtasks yourself.

Available subagent roles: {roles_list}

Return a JSON plan:
{{
  "subtasks": [
    {{"role": "research-specialist",
      "instruction": "Find the most recent SEC 10-K filing for ACME.",
      "expected_artifact": "acme_10k_summary.md",
      "read_files": []}}
  ],
  "reasoning": "Why this decomposition."
}}

Do not write file contents. Do not answer the user directly.
"""
```

Keep the planner system prompt under ~1500 chars. Long planner prompts leak
into subagents if the `override=True` contract in Step 3 is skipped.

### Step 3 — Construct subagents with EXPLICIT system-message override

This is the fix for **P52**. Never rely on default prompt composition for
subagents. Always build a fresh `SystemMessage` and pass `override=True`.

```python
from langchain_core.messages import SystemMessage, HumanMessage
from langgraph.prebuilt import create_react_agent
from langchain_anthropic import ChatAnthropic

SUBAGENT_PROMPTS = {
    "research-specialist": (
        "You are a research specialist. Given an instruction, produce a "
        "fact-dense summary with inline citations. Return ONLY the summary. "
        "Do NOT plan, do NOT delegate."
    ),
    "code-writer": (
        "You are a code writer. Given a spec, produce runnable Python. "
        "Return ONLY code in one fenced block. Do NOT explain."
    ),
    "critic": (
        "You are a critic. Given an artifact and a spec, list concrete defects. "
        "Return a JSON list of {line, issue, severity}. Do NOT rewrite the artifact."
    ),
}

def build_subagent(role: str, model):
    return create_react_agent(
        model=model,
        tools=ROLE_TOOLS[role],
        # KEY: prompt parameter replaces default state_modifier; override=True
        # means no parent-prompt composition.
        prompt=SystemMessage(content=SUBAGENT_PROMPTS[role]),
    )

def invoke_subagent(subagent, instruction: str, read_files: dict):
    # Build messages from scratch — do not reuse parent message list.
    context = "\n\n".join(f"# {name}\n{content}" for name, content in read_files.items())
    messages = [HumanMessage(content=f"{context}\n\n## Task\n{instruction}")]
    result = subagent.invoke({"messages": messages})
    return result["messages"][-1].content
```

Rules:

1. **New message list per invocation.** Do not pass the planner's message
   history into the subagent. Build from scratch with `HumanMessage(task)`.
2. **`prompt=SystemMessage(...)`** on `create_react_agent` replaces the default
   `state_modifier`. On LangGraph 1.0.x this is the supported way to pin a
   subagent's persona.
3. **Return type is a string or a structured JSON artifact** — never the full
   message list. The planner does not need subagent reasoning traces.

See [Subagent Prompting](references/subagent-prompting.md) for the full
override-vs-append test, the handoff structured-output schema, and how to
unit-test for P52 persona leak.

### Step 4 — Implement the virtual filesystem with eviction

This is the fix for **P51**. The virtual FS lives in the graph state dict for
small artifacts (< 100 KB) and on real disk / an object store for large ones.
A cleanup node evicts old entries before every planner step.

```python
from typing import TypedDict, Annotated
from operator import or_  # merge dict state updates

class DeepAgentState(TypedDict):
    messages: list
    plan: dict
    files: Annotated[dict, or_]  # {name: {content, written_at_step, status}}
    step: int
    reflection_depth: int

MAX_FILE_AGE_STEPS = 20
INLINE_SIZE_LIMIT_BYTES = 100 * 1024  

Related in Ads & Marketing