What Is a Subagent?
Quick Definition#
A subagent is a specialized AI agent that receives a scoped task from a parent orchestrator agent, executes it independently using its own tools and reasoning, and returns results. Subagents are the building blocks of multi-agent systems ā they allow complex tasks to be divided into specialized pieces that can run in parallel, with each subagent applying domain-specific tools and knowledge to its assigned portion.
The subagent pattern is the practical implementation of how AI Agent Orchestration works at scale. For foundational context, read AI Agents and Multi-Agent Systems first. Browse all AI agent terms in the AI Agent Glossary.
Why Subagents Matter#
Single-agent systems have fundamental limits:
- Context window constraints: Complex, multi-step tasks require more context than any single LLM call can handle
- Sequential bottlenecks: An agent doing everything sequentially is slow on parallel-friendly tasks
- Specialization gaps: A generalist agent may be mediocre at research, writing, and code review; specialized subagents can be expert at each
Subagents solve these problems by enabling:
- Parallelization: Multiple subagents working simultaneously on independent subtasks
- Specialization: Each subagent has its own system prompt, tools, and model optimized for its domain
- Context isolation: Each subagent maintains a focused context for its specific task, avoiding context window pollution from unrelated information
- Composability: Complex workflows are assembled from reusable, independently testable subagent components
Orchestrator vs. Subagent Roles#
Orchestrator Agent#
The orchestrator receives the original complex request and is responsible for:
- Task decomposition: Breaking the request into subtasks that can be delegated
- Subagent selection: Choosing which specialized subagent to handle each subtask
- State management: Tracking which subtasks are complete and combining results
- Error handling: Deciding what to do if a subagent fails or returns low-quality output
- Final synthesis: Combining subagent outputs into a coherent final response
Subagent#
The subagent receives a scoped subtask and is responsible for:
- Task execution: Applying its tools and reasoning to complete the assigned subtask
- Result reporting: Returning structured output the orchestrator can process
- Error signaling: Communicating failures or insufficient context back to the orchestrator
The Same Agent Can Play Both Roles#
A middle-level agent can be both orchestrator (to its subagents) and subagent (to a higher-level orchestrator):
Top-Level Orchestrator
āāā Research Orchestrator (subagent to top, orchestrator to its team)
ā āāā Web Search Subagent
ā āāā Academic Search Subagent
ā āāā Source Verification Subagent
āāā Writing Orchestrator (subagent to top, orchestrator to its team)
ā āāā Outline Subagent
ā āāā Draft Subagent
ā āāā Edit Subagent
āāā Quality Check Subagent
How Subagents Work in Practice#
Sequential Delegation#
The orchestrator delegates tasks one at a time, where each task may depend on previous results:
# Orchestrator sequentially delegates to subagents
# (each subagent result informs the next task)
research_result = await research_subagent.run(
task=f"Research the topic: {user_query}"
)
outline_result = await writing_subagent.run(
task=f"Create an outline based on this research: {research_result}"
)
draft_result = await drafting_subagent.run(
task=f"Write a full draft from this outline: {outline_result}"
)
Parallel Delegation#
For independent subtasks, the orchestrator launches subagents simultaneously:
import asyncio
# Orchestrator runs multiple subagents in parallel
results = await asyncio.gather(
legal_subagent.run(task="Review contract for legal risks"),
financial_subagent.run(task="Review contract financial terms"),
compliance_subagent.run(task="Check regulatory compliance"),
)
legal_result, financial_result, compliance_result = results
# Orchestrator synthesizes all three into a final report
OpenAI Agents SDK: Handoffs#
The OpenAI Agents SDK implements the orchestrator/subagent pattern through handoffs:
from agents import Agent, Runner
# Define specialized subagents
research_agent = Agent(
name="ResearchAgent",
instructions="Research topics thoroughly using web search. Return detailed findings.",
tools=[web_search_tool],
model="gpt-4o",
)
writing_agent = Agent(
name="WritingAgent",
instructions="Write clear, engaging content based on research provided.",
tools=[],
model="gpt-4o",
)
# Orchestrator with handoffs to subagents
orchestrator = Agent(
name="Orchestrator",
instructions="""Coordinate content creation tasks.
- Use ResearchAgent to gather information
- Use WritingAgent to create the final content
- Synthesize their outputs into a final result""",
handoffs=[research_agent, writing_agent],
model="gpt-4o",
)
result = Runner.run_sync(orchestrator, "Write a blog post about quantum computing")
LangGraph: Subagent as a Node#
In LangGraph, subagents are nodes in a state graph that the orchestrator routes between:
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
import operator
class WorkflowState(TypedDict):
task: str
research: str
draft: str
final: str
def research_node(state: WorkflowState):
"""Research subagent"""
result = research_agent.invoke({"input": state["task"]})
return {"research": result["output"]}
def writing_node(state: WorkflowState):
"""Writing subagent"""
result = writing_agent.invoke({
"input": f"Write content about: {state['task']}\nResearch: {state['research']}"
})
return {"draft": result["output"]}
def review_node(state: WorkflowState):
"""Review subagent"""
result = review_agent.invoke({
"input": f"Review and improve this draft: {state['draft']}"
})
return {"final": result["output"]}
# Build the orchestrated workflow
graph = StateGraph(WorkflowState)
graph.add_node("research", research_node)
graph.add_node("write", writing_node)
graph.add_node("review", review_node)
graph.add_edge("research", "write")
graph.add_edge("write", "review")
graph.add_edge("review", END)
graph.set_entry_point("research")
workflow = graph.compile()
Subagent Design Principles#
Scope Each Subagent Narrowly#
A subagent should have a clear, well-defined responsibility. "Research anything" is too broad; "search the web for current statistics about X and return structured results" is appropriately scoped.
Use Task-Specific Tools#
Each subagent should have only the tools relevant to its task. A research subagent needs search tools. A database subagent needs SQL tools. Giving subagents unnecessary tools increases cost and the chance of unexpected actions.
Design for Structured Output#
Subagents should return structured, parseable results the orchestrator can process reliably. Use TypedDict, Pydantic models, or JSON schemas to define output formats. Free-form text output requires the orchestrator to do additional parsing that can fail.
Handle Failures Gracefully#
Subagents fail. A web search subagent may return no results. A database subagent may hit a timeout. Design subagent output schemas to include error states, and ensure orchestrators handle these gracefully rather than failing silently.
Subagents vs. Direct Tool Calling#
| Dimension | Subagent | Direct Tool Call |
|---|---|---|
| Complexity | Multi-step reasoning | Single function |
| Context | Independent reasoning context | Shares orchestrator context |
| Cost | Higher (full LLM calls) | Lower (function execution) |
| Adaptability | Can adjust approach mid-task | Fixed behavior |
| When to use | Complex sub-tasks requiring reasoning | Simple data retrieval or actions |
Use subagents when the subtask requires multiple steps, judgment, or adaptation. Use direct tool calls when the subtask is a deterministic function (query a database, call an API, read a file).
Real-World Use Cases#
Competitive intelligence workflow#
An orchestrator agent coordinates three subagents: one searches competitor websites, one extracts pricing data, and one analyzes feature lists. The orchestrator synthesizes their outputs into a comparison report.
Code review pipeline#
A PR review orchestrator spawns subagents for security review, performance analysis, style checking, and test coverage evaluation ā running all four in parallel, then combining their feedback into a structured review comment.
Customer support escalation#
A support orchestrator routes incoming tickets to specialized subagents: a billing subagent for payment questions, a technical subagent for product issues, and a retention subagent for cancellation requests.
Common Misconceptions#
Misconception: Subagents are just function calls with extra steps Subagents perform multi-step reasoning and adapt their approach based on intermediate results. A function call executes a deterministic operation. A subagent can search for information, evaluate what it found, search again with a refined query, and return a synthesized result.
Misconception: More subagents always produce better results Adding subagents adds coordination overhead, cost, and failure points. The right number of subagents depends on the task's actual parallelism and specialization requirements. Over-engineering with subagents introduces complexity without proportional benefit.
Misconception: Subagents run in complete isolation Subagents share resources ā LLM API rate limits, external service quotas, and network bandwidth. Uncoordinated parallel subagents can hit rate limits or cause contention on external services. Production systems need coordination strategies for resource-constrained environments.
Related Terms#
- Multi-Agent Systems ā The broader architecture subagents operate in
- AI Agent Orchestration ā How orchestrators manage subagents
- Agent Handoff ā How control transfers between agents
- Agent Planning ā How orchestrators decompose tasks for subagents
- A2A Protocol ā Standard for cross-platform subagent communication
- Build AI Agent with CrewAI ā Tutorial using CrewAI's role-based subagent pattern
- LangGraph Multi-Agent Tutorial ā LangGraph approach to subagent coordination and state management
Frequently Asked Questions#
What is a subagent in AI?#
A subagent is an AI agent that receives scoped tasks from an orchestrating parent agent, executes them independently using its own tools and reasoning, and returns results. Subagents enable multi-agent systems to parallelize work and apply specialized capabilities to different parts of a complex task.
What is the difference between an orchestrator and a subagent?#
An orchestrator receives complex requests, decomposes them into subtasks, delegates to subagents, and synthesizes results. A subagent receives a scoped subtask, executes it, and returns output. The same agent can be both ā acting as an orchestrator within its domain while being a subagent to a higher-level orchestrator.
Can a subagent spawn its own subagents?#
Yes, creating hierarchical multi-agent architectures. A research subagent might spawn web search, academic search, and summarization subagents. This nesting is powerful but requires careful depth limits, error propagation handling, and distributed tracing for observability.
How do subagents communicate with their orchestrator?#
Communication varies by framework. LangGraph uses shared state objects, OpenAI Agents SDK uses handoffs with structured output, CrewAI uses task output passing, and A2A-compliant systems use the A2A task protocol. The common pattern is structured input from orchestrator, structured output returned to orchestrator.
What are the main risks of using subagents?#
Key risks: error amplification (subagent mistakes propagate), cost multiplication (each subagent uses LLM calls), coordination overhead (orchestrators must handle failures), and reduced observability. Mitigate with structured output validation, explicit error handling at agent boundaries, and comprehensive logging with agent tracing.