Intermediate

Implementing Sub Agents

Learn how to build and configure sub agents across different platforms - from Claude Code's built-in Agent tool to custom implementations with the Claude Agent SDK and OpenAI Assistants.

Sub Agents in Claude Code (Agent Tool)

Claude Code has a built-in Agent tool that spawns sub agents directly within the CLI. When Claude Code decides a task benefits from delegation, it invokes the Agent tool with a task description.

Claude Code - Agent Tool Invocation
// Claude Code internally calls the Agent tool like this:

Tool: Agent
Prompt: "Search the codebase for all files that import
from the 'utils/auth' module. For each file, document:
1. The file path
2. Which functions are imported
3. How they are used
Return a structured summary."

// The sub agent runs with read-only tools:
// Read, Glob, Grep
// It cannot modify files or run bash commands
💡
How it works: You do not call the Agent tool directly. Claude Code decides when to use it based on the complexity of your request. You can encourage sub agent usage by asking complex, multi-part questions or requesting tasks that naturally decompose into subtasks.

Agent Tool Configuration

The Agent tool in Claude Code supports several configuration options:

Option Description Default
prompt The task description sent to the sub agent Required
background Run the agent in the background (non-blocking) false
isolation Use a separate git worktree for file isolation false

Implementing in Python (Claude Agent SDK)

The Claude Agent SDK (also called claude-agent-sdk) lets you build custom sub agent systems in Python. Here is a complete example:

Python - Basic Sub Agent
import anthropic
from anthropic import Anthropic

client = Anthropic()

def run_sub_agent(task: str, tools: list = None) -> str:
    """Spawn a sub agent with a specific task."""
    messages = [
        {"role": "user", "content": task}
    ]

    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=4096,
        system="You are a focused sub agent. Complete the "
               "given task thoroughly and return results "
               "in a structured format.",
        messages=messages,
        tools=tools or []
    )

    return response.content[0].text

# Parent agent orchestration
def parent_agent(user_request: str):
    # Step 1: Research
    research = run_sub_agent(
        f"Research the following topic: {user_request}"
    )

    # Step 2: Plan based on research
    plan = run_sub_agent(
        f"Based on this research:\n{research}\n\n"
        "Create an implementation plan."
    )

    # Step 3: Implement based on plan
    result = run_sub_agent(
        f"Implement the following plan:\n{plan}"
    )

    return result

Advanced: Parallel Sub Agents in Python

Python - Parallel Sub Agents with asyncio
import asyncio
from anthropic import AsyncAnthropic

client = AsyncAnthropic()

async def run_agent_async(task: str) -> str:
    """Run a sub agent asynchronously."""
    response = await client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=4096,
        system="Complete the task and return results.",
        messages=[{"role": "user", "content": task}]
    )
    return response.content[0].text

async def parallel_agents():
    # Spawn 3 agents simultaneously
    tasks = [
        run_agent_async("Research authentication patterns"),
        run_agent_async("Research database schema design"),
        run_agent_async("Research API rate limiting"),
    ]

    results = await asyncio.gather(*tasks)

    # Aggregate results
    for i, result in enumerate(results):
        print(f"Agent {i+1}: {result[:200]}...")

    return results

asyncio.run(parallel_agents())

Implementing with OpenAI Assistants

OpenAI's Assistants API provides a different approach to sub agents. Each assistant is a persistent entity with its own instructions, tools, and thread history.

Python - OpenAI Assistants Sub Agent
from openai import OpenAI

client = OpenAI()

# Create a specialized research assistant
research_assistant = client.beta.assistants.create(
    name="Research Agent",
    instructions="You are a research specialist. "
                 "Analyze topics thoroughly and return "
                 "structured findings.",
    model="gpt-4o",
    tools=[{"type": "code_interpreter"}]
)

# Create a thread and run the assistant
thread = client.beta.threads.create()

message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="Research best practices for JWT auth"
)

run = client.beta.threads.runs.create_and_poll(
    thread_id=thread.id,
    assistant_id=research_assistant.id
)

# Get the result
if run.status == "completed":
    messages = client.beta.threads.messages.list(
        thread_id=thread.id
    )
    print(messages.data[0].content[0].text.value)

Configuration Options

Regardless of the platform, sub agent configuration typically involves these key settings:

Model Selection

Choose a faster, cheaper model for simple tasks (e.g., Haiku for research) and a more capable model for complex tasks (e.g., Opus for coding).

Isolation Level

Decide whether agents share the file system or work in isolated environments (e.g., git worktrees) to prevent conflicts.

Execution Mode

Choose between foreground (blocking) for sequential workflows or background (non-blocking) for parallel execution.

Token Limits

Set max_tokens per agent to control costs and ensure agents return focused, concise responses.

Cost awareness: Each sub agent call is a separate API request. A parent agent that spawns 5 sub agents will incur at least 6 API calls (1 parent + 5 children). Use smaller models for simple sub tasks and set appropriate token limits to manage costs.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.