Skip to content

Chapter 09 · Subagents and context isolation ​

The built-in task tool lets the main agent spawn subagents: each subtask gets a fresh context and returns one report. Use it for context-bloating scenarios like heavy retrieval or heavy file reads.

Mechanics and design choices ​

Subagents are ephemeral and stateless: they return once, no back-and-forth. A general-purpose default exists; custom definitions are also possible. Context isolation is the core value, not a parallel compute framework.

Example ​

python
import os
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model=os.environ["MODEL_ID"],
    api_key=os.environ["DEEPAGENT_API_KEY"],
    base_url=os.environ.get("DEEPAGENT_BASE_URL", "https://api.openai.com/v1"),
)

from deepagents import create_deep_agent

research = {
    "name": "research-agent",
    "description": "Research tasks with focused searches",
    "system_prompt": "You are a focused researcher. Return findings as a short report.",
}
agent = create_deep_agent(
    model=model,
    subagents=[research],
    system_prompt="Delegate research subtasks to the research-agent subagent.",
)
result = agent.invoke(
    {"messages": [
        {"role": "user", "content": "Research: why do we isolate subtasks in their own context?"},
    ]
}, config={"configurable": {"thread_id": "ch09"}})
print(result["messages"][-1].content)

Run and verify ​

API key required. Acceptance: the trace shows a subagent call; the main agent receives the conclusion report only.

Pitfalls ​

Subagents solve context hygiene, not “smarter results.” Delegation must state acceptance criteria and boundaries, otherwise you only hide complexity.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is subagent state?

2. What is the core value?

3. What is the default subagent?

4. What must delegation specify?

Hands-on exercises ​

  1. Add another custom subagent and verify it is invoked.
  2. Consistency-check subtask results against the main agent’s answer.
  3. Define machine-checkable acceptance fields for delegation.

Official references ​

Verified on 2026-09-17 with Deep Agents 0.7.15.