# Multi-Agent: Supervisor Pattern

Ref:

- https://docs.langchain.com/oss/python/langchain/multi-agent

The supervisor pattern uses a central controller agent that calls other agents as tools.

**Characteristics:**

- Centralized control flow
- Sub-agents don't interact directly with users
- Good for structured workflows

**Example:** Supervisor coordinates a calculator agent and a writer agent to solve math problems and explain solutions.


## Setup

Configure `.env` before running. See `.env.sample`.



```python
import rich
from dotenv import load_dotenv

load_dotenv()
```




    True



## Define Sub-Agents

Create specialized agents for different tasks.



```python
from typing import Any

from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
from langchain_core.tools import tool
from langgraph.graph.state import CompiledStateGraph

model = ChatAnthropic(model="claude-sonnet-4-5-20250929")


# Calculator agent tools
@tool
def add(a: float, b: float) -> float:
    """Add two numbers."""
    return a + b


@tool
def subtract(a: float, b: float) -> float:
    """Subtract b from a."""
    return a - b


@tool
def multiply(a: float, b: float) -> float:
    """Multiply two numbers."""
    return a * b


@tool
def divide(a: float, b: float) -> float:
    """Divide a by b."""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b


calculator_agent: CompiledStateGraph[Any] = create_agent(
    model=model,
    tools=[add, subtract, multiply, divide],
    system_prompt="You are a calculator. Use your tools to perform calculations. Return only the numeric result.",
)


# Writer agent (uses LLM directly for writing)
writer_agent: CompiledStateGraph[Any] = create_agent(
    model=model,
    tools=[],
    system_prompt="""You are a writing assistant. Create clear explanations based on the information provided.
Write concisely and format appropriately.""",
)

rich.print("Sub-agents created: calculator_agent, writer_agent")
```


    Sub-agents created: calculator_agent, writer_agent



## Wrap Sub-Agents as Tools

Create tool wrappers that the supervisor can call.



```python
@tool("calculate", parse_docstring=True)
def call_calculator_agent(expression: str) -> str:
    """Perform mathematical calculations.

    Use this to compute arithmetic expressions, solve equations, or do any math.

    Args:
        expression: The math problem to solve (e.g., "What is 25 * 4 + 10?").
    """
    result = calculator_agent.invoke({"messages": [{"role": "user", "content": expression}]})
    return str(result["messages"][-1].content)


@tool("write", parse_docstring=True)
def call_writer_agent(request: str) -> str:
    """Write or explain content.

    Use this to create explanations, summaries, or written content.

    Args:
        request: What to write, including context and any specific requirements.
    """
    result = writer_agent.invoke({"messages": [{"role": "user", "content": request}]})
    return str(result["messages"][-1].content)


rich.print("Tool wrappers created: calculate, write")
```


    Tool wrappers created: calculate, write



## Create Supervisor Agent

The supervisor coordinates the sub-agents to accomplish complex tasks.



```python
supervisor: CompiledStateGraph[Any] = create_agent(
    model=model,
    tools=[call_calculator_agent, call_writer_agent],
    system_prompt="""You are a supervisor agent that coordinates calculation and writing tasks.

When given a task:
1. Use the calculate tool to perform any necessary math
2. Use the write tool to explain or summarize results
3. Synthesize the results into a final response""",
)

rich.print("Supervisor agent created")
```


    Supervisor agent created



## Test: Coordinated Task

Ask the supervisor to complete a task that requires both calculation and explanation.



```python
response = supervisor.invoke(
    {"messages": [{"role": "user", "content": "Calculate 15% tip on a $85 dinner bill and explain the calculation."}]}
)

rich.print("Final response:")
rich.print(response["messages"][-1].content)
```


    Final response:




    ## Answer
    
    For a $85 dinner bill with a 15% tip:
    
    **The tip amount is $12.75**
    
    ### Calculation Breakdown:
    
    1. **Convert percentage to decimal**: 15% = 0.15
    2. **Multiply**: $85 × 0.15 = $12.75
    
    ### Quick Mental Math Alternative:
    - 10% of $85 = $8.50
    - 5% of $85 = $4.25
    - Add together: $8.50 + $4.25 = $12.75
    
    ### Total Payment:
    - Bill: $85.00
    - Tip: $12.75
    - **Total: $97.75**
    
    The mental math method is especially handy when you're at the restaurant without a calculator!



## Stream Execution

Stream to see the supervisor's decision-making process.



```python
query = "If I invest $1000 at 5% annual interest, how much will I have after 3 years? Explain compound interest."

for chunk in supervisor.stream({"messages": [{"role": "user", "content": query}]}):
    rich.print("chunk =", chunk)
```


    chunk =
    {
        'model': {
            'messages': [
                AIMessage(
                    content=[
                        {
                            'text': "I'll help you calculate your investment return and explain compound interest.",
                            'type': 'text'
                        },
                        {
                            'id': 'toolu_01TJSLzdaUhvTFxdasBNznTY',
                            'input': {'expression': '1000 * (1 + 0.05)^3'},
                            'name': 'calculate',
                            'type': 'tool_use'
                        },
                        {
                            'id': 'toolu_014FwM5KW8uAAG1sqTPp2Wuk',
                            'input': {
                                'request': "Explain what compound interest is, how it works, and why it's important for
    investments. Make it clear and accessible for someone learning about investing."
                            },
                            'name': 'write',
                            'type': 'tool_use'
                        }
                    ],
                    additional_kwargs={},
                    response_metadata={
                        'id': 'msg_015UKgtZgqSPJ3F2TCBagQoo',
                        'model': 'claude-sonnet-4-5-20250929',
                        'stop_reason': 'tool_use',
                        'stop_sequence': None,
                        'usage': {
                            'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
                            'cache_creation_input_tokens': 0,
                            'cache_read_input_tokens': 0,
                            'input_tokens': 763,
                            'output_tokens': 141,
                            'server_tool_use': None,
                            'service_tier': 'standard'
                        },
                        'model_name': 'claude-sonnet-4-5-20250929',
                        'model_provider': 'anthropic'
                    },
                    id='lc_run--0d3bebe4-9b13-4b55-b413-6753e62e411a-0',
                    tool_calls=[
                        {
                            'name': 'calculate',
                            'args': {'expression': '1000 * (1 + 0.05)^3'},
                            'id': 'toolu_01TJSLzdaUhvTFxdasBNznTY',
                            'type': 'tool_call'
                        },
                        {
                            'name': 'write',
                            'args': {
                                'request': "Explain what compound interest is, how it works, and why it's important for
    investments. Make it clear and accessible for someone learning about investing."
                            },
                            'id': 'toolu_014FwM5KW8uAAG1sqTPp2Wuk',
                            'type': 'tool_call'
                        }
                    ],
                    usage_metadata={
                        'input_tokens': 763,
                        'output_tokens': 141,
                        'total_tokens': 904,
                        'input_token_details': {
                            'cache_read': 0,
                            'cache_creation': 0,
                            'ephemeral_5m_input_tokens': 0,
                            'ephemeral_1h_input_tokens': 0
                        }
                    }
                )
            ]
        }
    }




    chunk =
    {
        'tools': {
            'messages': [
                ToolMessage(
                    content='# Compound Interest: Your Money\'s Growth Engine\n\n## What It Is\n\nCompound interest is 
    when you earn returns not just on your original investment, but also on the returns you\'ve already earned. In 
    simple terms: **you earn interest on your interest**.\n\n## How It Works\n\nLet\'s say you invest $1,000 at 10% 
    annual interest:\n\n**Year 1:** \n- You earn $100 (10% of $1,000)\n- New total: $1,100\n\n**Year 2:**\n- You earn 
    $110 (10% of $1,100) — *notice it\'s more than Year 1*\n- New total: $1,210\n\n**Year 3:**\n- You earn $121 (10% of
    $1,210)\n- New total: $1,331\n\nEach year, your earnings grow because you\'re calculating interest on an 
    increasingly larger amount.\n\n## Why It Matters for Investing\n\n**1. Time is your best friend**\nThe longer your 
    money compounds, the more dramatic the growth. After 30 years at 10%, that $1,000 becomes over $17,000.\n\n**2. 
    Small differences compound too**\nAn extra 2% annual return doesn\'t sound like much, but over decades, it can mean
    tens of thousands of dollars more.\n\n**3. Starting early beats investing more later**\nSomeone who invests $5,000 
    at age 25 can end up with more than someone who invests $10,000 at age 40, even though they put in less 
    money.\n\n## The Key Takeaway\n\nAlbert Einstein allegedly called compound interest "the eighth wonder of the 
    world." The sooner you start investing, the harder your money works for you—automatically.',
                    name='write',
                    id='bcd1feaa-1f25-485f-995b-ed3e0a20cfbf',
                    tool_call_id='toolu_014FwM5KW8uAAG1sqTPp2Wuk'
                )
            ]
        }
    }




    chunk =
    {
        'tools': {
            'messages': [
                ToolMessage(
                    content='1157.625',
                    name='calculate',
                    id='ca341ba0-ef91-4b4d-a851-60c1a2c7f94f',
                    tool_call_id='toolu_01TJSLzdaUhvTFxdasBNznTY'
                )
            ]
        }
    }




    chunk =
    {
        'model': {
            'messages': [
                AIMessage(
                    content='## Your Investment Results\n\n**After 3 years, your $1,000 investment at 5% annual 
    compound interest will grow to $1,157.63**\n\nHere\'s the breakdown:\n- **Initial investment:** $1,000\n- 
    **Interest rate:** 5% annually\n- **Time period:** 3 years\n- **Final amount:** $1,157.63\n- **Total interest 
    earned:** $157.63\n\n### Year-by-Year Growth:\n- **Year 1:** $1,000 → $1,050.00 (earned $50)\n- **Year 2:** $1,050 
    → $1,102.50 (earned $52.50)\n- **Year 3:** $1,102.50 → $1,157.63 (earned $55.13)\n\nNotice how each year you earn 
    slightly more interest than the previous year? That\'s compound interest at work!\n\n---\n\n# Compound Interest: 
    Your Money\'s Growth Engine\n\n## What It Is\n\nCompound interest is when you earn returns not just on your 
    original investment, but also on the returns you\'ve already earned. In simple terms: **you earn interest on your 
    interest**.\n\n## How It Works\n\nLet\'s say you invest $1,000 at 10% annual interest:\n\n**Year 1:** \n- You earn 
    $100 (10% of $1,000)\n- New total: $1,100\n\n**Year 2:**\n- You earn $110 (10% of $1,100) — *notice it\'s more than
    Year 1*\n- New total: $1,210\n\n**Year 3:**\n- You earn $121 (10% of $1,210)\n- New total: $1,331\n\nEach year, 
    your earnings grow because you\'re calculating interest on an increasingly larger amount.\n\n## Why It Matters for 
    Investing\n\n**1. Time is your best friend**\nThe longer your money compounds, the more dramatic the growth. After 
    30 years at 10%, that $1,000 becomes over $17,000.\n\n**2. Small differences compound too**\nAn extra 2% annual 
    return doesn\'t sound like much, but over decades, it can mean tens of thousands of dollars more.\n\n**3. Starting 
    early beats investing more later**\nSomeone who invests $5,000 at age 25 can end up with more than someone who 
    invests $10,000 at age 40, even though they put in less money.\n\n## The Key Takeaway\n\nAlbert Einstein allegedly 
    called compound interest "the eighth wonder of the world." The sooner you start investing, the harder your money 
    works for you—automatically.',
                    additional_kwargs={},
                    response_metadata={
                        'id': 'msg_01DXYC52BQ4MBChytyjF4WT7',
                        'model': 'claude-sonnet-4-5-20250929',
                        'stop_reason': 'end_turn',
                        'stop_sequence': None,
                        'usage': {
                            'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
                            'cache_creation_input_tokens': 0,
                            'cache_read_input_tokens': 0,
                            'input_tokens': 1348,
                            'output_tokens': 596,
                            'server_tool_use': None,
                            'service_tier': 'standard'
                        },
                        'model_name': 'claude-sonnet-4-5-20250929',
                        'model_provider': 'anthropic'
                    },
                    id='lc_run--cf76c322-a342-454e-9ae5-2404d8f54e5d-0',
                    usage_metadata={
                        'input_tokens': 1348,
                        'output_tokens': 596,
                        'total_tokens': 1944,
                        'input_token_details': {
                            'cache_read': 0,
                            'cache_creation': 0,
                            'ephemeral_5m_input_tokens': 0,
                            'ephemeral_1h_input_tokens': 0
                        }
                    }
                )
            ]
        }
    }


