langchain-deep-agents
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".
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
ads
IncludedMulti-platform paid advertising audit and optimization skill. Analyzes Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, and Apple Ads. 250+ checks with scoring, parallel agents, industry templates, and AI creative generation.
banana
IncludedAI image generation Creative Director powered by Google Gemini Nano Banana models. Use this skill for ANY request involving image creation, editing, visual asset production, or creative direction. Triggers on: generate an image, create a photo, edit this picture, design a logo, make a banner, visual for my anything, and all /banana commands. Handles text-to-image, image editing, multi-turn creative sessions, batch workflows, and brand presets.
rpg-migration-analyzer
IncludedAnalyzes legacy RPG (Report Program Generator) programs from AS/400 and IBM i systems for migration to modern Java applications. Extracts business logic from RPG III/IV/ILE source code, identifies data structures (D-specs), file operations (F-specs), program dependencies (CALLB/CALLP), and converts RPG constructs to Java equivalents. Generates migration reports, complexity estimates, and Java implementation strategies with POJO classes, JPA entities, and service methods. Use when modernizing AS/400 or IBM i legacy systems, analyzing RPG source files (.rpg, .rpgle, .RPGLE), converting RPG to Java, mapping data specifications to Java classes, planning legacy system migration, or when user mentions RPG analysis, Report Program Generator, RPG III/IV/ILE, AS/400 modernization, IBM i migration, packed decimal conversion, or mainframe application rewrite.
brand-library-architect
IncludedBuild a complete brand library for a product — visual asset render pipeline, brand documentation set (BRAND, COPY, MANIFESTO, BIOS, FAQ, GLOSSARY, TONE, PRICING), open-source convention files (README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT), and a self-contained press kit. This skill should be used when the user asks to "build a brand library / brand kit / press kit / brand assets" for a product, "set up a brand library workflow," "create a positioning manifesto plus visual identity," or any combination of brand documentation + visual asset pipeline. Apply phase-by-phase or run end-to-end. Templates are product-agnostic and use {{TOKEN}} placeholders the skill prompts the user to fill.
writing-tech-post
IncludedAuthors engineering blog posts end-to-end: launch deep-dives, incident postmortems, architecture migrations, performance case studies, tutorials, AI/agent system writeups, security disclosures, and research-to-product translations. Picks the correct archetype, plans the abstraction ladder, enforces an evidence cadence (diagrams, benchmarks, profiles, traces, code, ablations), tunes voice against publisher house styles (Datadog, Vercel, GitHub, AWS, Meta, Cloudflare, Jane Street), and runs a pre-publish gate for narrative momentum and disclosure ethics. Use when drafting a new engineering post, restructuring a draft that feels flat, deciding which evidence form belongs where, validating that depth and product context are balanced, or preparing a postmortem, migration, or performance narrative for external publication. Do not use for API reference documentation, README authoring, marketing copy, release notes, generic SEO content, ghost-written executive thought leadership, or non-engineering long-form essays.
blog-google
IncludedGoogle API integration for blog performance: PageSpeed Insights, CrUX Core Web Vitals with 25-week history, Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search for embedding, and Google Ads Keyword Planner. Progressive feature availability based on credential tier (API key, OAuth/service account, GA4, Ads). Shares config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user says "google data", "page speed", "core web vitals", "search console", "indexation", "GA4", "keyword research", "nlp entities", "blog performance", "youtube search", "google api setup".