Skip to main content
Deep 에이전트는 작업을 위임하기 위해 서브에이전트를 생성할 수 있습니다. subagents 매개변수에서 커스텀 서브에이전트를 지정할 수 있습니다. 서브에이전트는 컨텍스트 격리(메인 에이전트의 컨텍스트를 깨끗하게 유지)와 특화된 지시사항 제공에 유용합니다.

서브에이전트를 사용하는 이유

서브에이전트는 컨텍스트 비대화 문제를 해결합니다. 에이전트가 대용량 출력을 가진 도구(웹 검색, 파일 읽기, 데이터베이스 쿼리)를 사용할 때, 컨텍스트 윈도우는 중간 결과로 빠르게 채워집니다. 서브에이전트는 이러한 세부 작업을 격리합니다. 메인 에이전트는 수십 개의 도구 호출이 아닌 최종 결과만 받습니다. 서브에이전트를 사용해야 하는 경우:
  • ✅ 메인 에이전트의 컨텍스트를 어지럽힐 수 있는 다단계 작업
  • ✅ 커스텀 지시사항이나 도구가 필요한 특화된 도메인
  • ✅ 다른 모델 기능이 필요한 작업
  • ✅ 메인 에이전트가 고수준 조정에 집중하도록 하고 싶을 때
서브에이전트를 사용하지 말아야 하는 경우:
  • ❌ 간단한 단일 단계 작업
  • ❌ 중간 컨텍스트를 유지해야 하는 경우
  • ❌ 오버헤드가 이점보다 클 때

구성

subagents는 딕셔너리 목록 또는 CompiledSubAgent 객체여야 합니다. 두 가지 유형이 있습니다:

SubAgent (딕셔너리 기반)

대부분의 사용 사례에서는 서브에이전트를 딕셔너리로 정의합니다: 필수 필드:
  • name (str): 서브에이전트의 고유 식별자입니다. 메인 에이전트는 task() 도구를 호출할 때 이 이름을 사용합니다.
  • description (str): 이 서브에이전트가 수행하는 작업입니다. 구체적이고 행동 지향적으로 작성하세요. 메인 에이전트는 이를 사용하여 언제 위임할지 결정합니다.
  • system_prompt (str): 서브에이전트에 대한 지시사항입니다. 도구 사용 가이드와 출력 형식 요구사항을 포함하세요.
  • tools (List[Callable]): 서브에이전트가 사용할 수 있는 도구입니다. 최소한으로 유지하고 필요한 것만 포함하세요.
선택 필드:
  • model (str | BaseChatModel): 메인 에이전트의 모델을 재정의합니다. "provider:model-name" 형식을 사용하세요(예: "openai:gpt-4o").
  • middleware (List[Middleware]): 커스텀 동작, 로깅 또는 속도 제한을 위한 추가 미들웨어입니다.
  • interrupt_on (Dict[str, bool]): 특정 도구에 대한 human-in-the-loop을 구성합니다. 체크포인터가 필요합니다.

CompiledSubAgent

복잡한 워크플로우의 경우, 사전 구축된 LangGraph 그래프를 사용합니다: 필드:
  • name (str): 고유 식별자
  • description (str): 이 서브에이전트가 수행하는 작업
  • runnable (Runnable): 컴파일된 LangGraph 그래프(먼저 .compile()을 호출해야 함)

SubAgent 사용하기

import os
from typing import Literal
from tavily import TavilyClient
from deepagents import create_deep_agent

tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])

def internet_search(
    query: str,
    max_results: int = 5,
    topic: Literal["general", "news", "finance"] = "general",
    include_raw_content: bool = False,
):
    """Run a web search"""
    return tavily_client.search(
        query,
        max_results=max_results,
        include_raw_content=include_raw_content,
        topic=topic,
    )

research_subagent = {
    "name": "research-agent",
    "description": "Used to research more in depth questions",
    "system_prompt": "You are a great researcher",
    "tools": [internet_search],
    "model": "openai:gpt-4o",  # Optional override, defaults to main agent model
}
subagents = [research_subagent]

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-20250514",
    subagents=subagents
)

CompiledSubAgent 사용하기

더 복잡한 사용 사례의 경우, 사전 구축된 LangGraph 그래프를 서브에이전트로 제공할 수 있습니다:
from deepagents import create_deep_agent, CompiledSubAgent
from langchain.agents import create_agent

# 커스텀 에이전트 그래프 생성
custom_graph = create_agent(
    model=your_model,
    tools=specialized_tools,
    prompt="You are a specialized agent for data analysis..."
)

# 커스텀 서브에이전트로 사용
custom_subagent = CompiledSubAgent(
    name="data-analyzer",
    description="Specialized agent for complex data analysis tasks",
    runnable=custom_graph
)

subagents = [custom_subagent]

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-20250514",
    tools=[internet_search],
    system_prompt=research_instructions,
    subagents=subagents
)

범용 서브에이전트

사용자 정의 서브에이전트 외에도, deep 에이전트는 항상 general-purpose 서브에이전트에 접근할 수 있습니다. 이 서브에이전트는:
  • 메인 에이전트와 동일한 시스템 프롬프트를 가집니다
  • 동일한 모든 도구에 접근할 수 있습니다
  • 동일한 모델을 사용합니다(재정의되지 않은 경우)

언제 사용하나요

범용 서브에이전트는 특화된 동작 없이 컨텍스트 격리에 이상적입니다. 메인 에이전트는 복잡한 다단계 작업을 이 서브에이전트에 위임하고 중간 도구 호출의 비대화 없이 간결한 결과를 받을 수 있습니다.

예시

메인 에이전트가 10개의 웹 검색을 수행하고 컨텍스트를 결과로 채우는 대신, 범용 서브에이전트에 위임합니다: task(name="general-purpose", task="Research quantum computing trends"). 서브에이전트는 모든 검색을 내부적으로 수행하고 요약만 반환합니다.

모범 사례

명확한 설명 작성

메인 에이전트는 설명을 사용하여 어떤 서브에이전트를 호출할지 결정합니다. 구체적으로 작성하세요: 좋음: "Analyzes financial data and generates investment insights with confidence scores" 나쁨: "Does finance stuff"

시스템 프롬프트를 상세하게 유지

도구 사용 방법과 출력 형식에 대한 구체적인 가이드를 포함하세요:
research_subagent = {
    "name": "research-agent",
    "description": "Conducts in-depth research using web search and synthesizes findings",
    "system_prompt": """You are a thorough researcher. Your job is to:

    1. Break down the research question into searchable queries
    2. Use internet_search to find relevant information
    3. Synthesize findings into a comprehensive but concise summary
    4. Cite sources when making claims

    Output format:
    - Summary (2-3 paragraphs)
    - Key findings (bullet points)
    - Sources (with URLs)

    Keep your response under 500 words to maintain clean context.""",
    "tools": [internet_search],
}

도구 세트 최소화

서브에이전트에게 필요한 도구만 제공하세요. 이는 집중력과 보안을 향상시킵니다:
# ✅ 좋음: 집중된 도구 세트
email_agent = {
    "name": "email-sender",
    "tools": [send_email, validate_email],  # Only email-related
}

# ❌ 나쁨: 너무 많은 도구
email_agent = {
    "name": "email-sender",
    "tools": [send_email, web_search, database_query, file_upload],  # Unfocused
}

작업별로 모델 선택

서로 다른 모델은 서로 다른 작업에 탁월합니다:
subagents = [
    {
        "name": "contract-reviewer",
        "description": "Reviews legal documents and contracts",
        "system_prompt": "You are an expert legal reviewer...",
        "tools": [read_document, analyze_contract],
        "model": "anthropic:claude-sonnet-4-20250514",  # Large context for long documents
    },
    {
        "name": "financial-analyst",
        "description": "Analyzes financial data and market trends",
        "system_prompt": "You are an expert financial analyst...",
        "tools": [get_stock_price, analyze_fundamentals],
        "model": "openai:gpt-4o",  # Better for numerical analysis
    },
]

간결한 결과 반환

서브에이전트가 원시 데이터가 아닌 요약을 반환하도록 지시하세요:
data_analyst = {
    "system_prompt": """Analyze the data and return:
    1. Key insights (3-5 bullet points)
    2. Overall confidence score
    3. Recommended next actions

    Do NOT include:
    - Raw data
    - Intermediate calculations
    - Detailed tool outputs

    Keep response under 300 words."""
}

일반적인 패턴

여러 특화 서브에이전트

서로 다른 도메인에 대한 특화된 서브에이전트를 생성하세요:
from deepagents import create_deep_agent

subagents = [
    {
        "name": "data-collector",
        "description": "Gathers raw data from various sources",
        "system_prompt": "Collect comprehensive data on the topic",
        "tools": [web_search, api_call, database_query],
    },
    {
        "name": "data-analyzer",
        "description": "Analyzes collected data for insights",
        "system_prompt": "Analyze data and extract key insights",
        "tools": [statistical_analysis],
    },
    {
        "name": "report-writer",
        "description": "Writes polished reports from analysis",
        "system_prompt": "Create professional reports from insights",
        "tools": [format_document],
    },
]

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-20250514",
    system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
    subagents=subagents
)
워크플로우:
  1. 메인 에이전트가 고수준 계획을 생성합니다
  2. data-collector에 데이터 수집을 위임합니다
  3. 결과를 data-analyzer에 전달합니다
  4. 인사이트를 report-writer에 보냅니다
  5. 최종 출력을 컴파일합니다
각 서브에이전트는 작업에만 집중하는 깨끗한 컨텍스트로 작업합니다.

문제 해결

서브에이전트가 호출되지 않음

문제: 메인 에이전트가 위임하는 대신 직접 작업을 수행하려고 합니다. 해결책:
  1. 설명을 더 구체적으로 작성:
    # ✅ 좋음
    {"name": "research-specialist", "description": "Conducts in-depth research on specific topics using web search. Use when you need detailed information that requires multiple searches."}
    
    # ❌ 나쁨
    {"name": "helper", "description": "helps with stuff"}
    
  2. 메인 에이전트에게 위임하도록 지시:
    agent = create_deep_agent(
        system_prompt="""...your instructions...
    
        IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
        This keeps your context clean and improves results.""",
        subagents=[...]
    )
    

컨텍스트가 여전히 비대화됨

문제: 서브에이전트를 사용함에도 컨텍스트가 채워집니다. 해결책:
  1. 서브에이전트에게 간결한 결과를 반환하도록 지시:
    system_prompt="""...
    
    IMPORTANT: Return only the essential summary.
    Do NOT include raw data, intermediate search results, or detailed tool outputs.
    Your response should be under 500 words."""
    
  2. 대용량 데이터에 파일 시스템 사용:
    system_prompt="""When you gather large amounts of data:
    1. Save raw data to /data/raw_results.txt
    2. Process and analyze the data
    3. Return only the analysis summary
    
    This keeps context clean."""
    

잘못된 서브에이전트가 선택됨

문제: 메인 에이전트가 작업에 부적절한 서브에이전트를 호출합니다. 해결책: 설명에서 서브에이전트를 명확하게 구분하세요:
subagents = [
    {
        "name": "quick-researcher",
        "description": "For simple, quick research questions that need 1-2 searches. Use when you need basic facts or definitions.",
    },
    {
        "name": "deep-researcher",
        "description": "For complex, in-depth research requiring multiple searches, synthesis, and analysis. Use for comprehensive reports.",
    }
]

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.