Module 4: Planning and Control·Lesson 12 of 15·7 min read

Multi-Agent Systems in Python: Orchestrator, Workers, and When One Agent Is Better

The problem: one agent with every tool gets crowded

As an agent grows, its tool list grows. The trip helper started with one tool; a real one might have weather, currency, hotels, flights, restaurants, visas and bookings. Every tool definition goes into every request, and the model has to pick the right one from a longer and longer list. OpenAI's function calling guide suggests keeping the number of functions available at the start of a turn small, under about 20 as a soft guideline, for better accuracy.

One answer is to split the work. An orchestrator agent reads the request, breaks it into parts, and hands each part to a worker agent that has only the tools for that part. Each worker sees a short tool list and a focused system prompt. Anthropic's "Building effective agents" describes this as the orchestrator-workers pattern.

It sounds strictly better. It is not. More agents means more model calls, more places for information to get lost, and more to debug. This lesson builds both designs for the same task, runs them side by side, and counts the cost.

The design

  • Two workers, each a small tool loop with scoped tools:
    • weather_agent can only call get_weather.
    • money_agent can only call convert_currency and search_hotels.
  • The orchestrator is also a tool loop, but its "tools" are the workers. When it calls weather_agent, your code runs a whole worker agent and returns its report as the tool result.
  • A single agent with all three tools, for comparison.

That is the key idea: to the orchestrator, a worker is just a tool. The agent loop from lesson 2 already knows how to call tools, so no new machinery is needed.

sequenceDiagram
    autonumber
    actor U as User
    participant O as Orchestrator
    participant MA as money_agent
    participant WA as weather_agent
    participant T as trip_tools
    U->>O: 300 USD, Lisbon hotel under 100 EUR, umbrella?
    Note over O,WA: Workers cannot see the user message
    O->>MA: task: Find hotels in Lisbon under 100 EUR
    MA->>T: search_hotels Lisbon, under 100 EUR
    T-->>MA: Casa Azul, 95 EUR
    MA-->>O: report
    O->>WA: task: Will it rain in Lisbon?
    WA->>T: get_weather Lisbon
    T-->>WA: sunny, 10% rain
    WA-->>O: report
    O-->>U: Casa Azul at 95 EUR, no rain expected
    Note over U,T: 6 model calls in total, single agent used 2

Diagram: To the orchestrator a worker is just a tool. Each worker sees only the task string it is handed.

The code

This file uses trip_tools.py from lesson 4. Save it as multi_agent.py:

python
# file: multi_agent.py
import json

from llm import client, MODEL
from trip_tools import FUNCTIONS, TOOLS, run_tool

CALLS = {"count": 0}  # count model calls so you can compare designs


def tool_loop(system: str, task: str, tools: list, functions: dict, label: str, max_steps: int = 5) -> str:
    messages = [{"role": "system", "content": system}, {"role": "user", "content": task}]
    for _ in range(max_steps):
        CALLS["count"] += 1
        msg = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, temperature=0).choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            return msg.content
        for call in msg.tool_calls:
            result = run_tool(call.function.name, call.function.arguments, functions=functions)
            print(f"  [{label}] {call.function.name}({call.function.arguments}) -> {result[:70]}")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
    return "Stopped at the step limit."


def pick(names):  # a worker sees only its own tools
    return [t for t in TOOLS if t["function"]["name"] in names], {n: FUNCTIONS[n] for n in names}


def as_text(task) -> str:
    """Models sometimes send an object where the schema says string. Accept it instead of failing."""
    return task if isinstance(task, str) else json.dumps(task)


def weather_agent(task: str) -> dict:
    task = as_text(task)
    tools, fns = pick(["get_weather"])
    return {"report": tool_loop("You are a weather specialist. Use get_weather, then answer in one sentence.",
                                task, tools, fns, "weather")}


def money_agent(task: str) -> dict:
    task = as_text(task)
    tools, fns = pick(["convert_currency", "search_hotels"])
    return {"report": tool_loop("You are a budget and hotel specialist. Use your tools, then answer briefly.",
                                task, tools, fns, "money")}


ORCHESTRATOR_TOOLS = [
    {"type": "function", "function": {
        "name": "weather_agent", "description": "Delegate a weather question about one city to the weather specialist.",
        "parameters": {"type": "object", "properties": {"task": {"type": "string", "description":
            "A complete, standalone task with the city name, e.g. 'Will it rain in Lisbon?'"}},
            "required": ["task"]}}},
    {"type": "function", "function": {
        "name": "money_agent", "description": "Delegate currency conversion or hotel search to the budget specialist.",
        "parameters": {"type": "object", "properties": {"task": {"type": "string", "description":
            "A complete, standalone task with every city, amount and currency, "
            "e.g. 'Find hotels in Lisbon under 100 EUR a night'"}},
            "required": ["task"]}}},
]
ORCHESTRATOR_FUNCTIONS = {"weather_agent": weather_agent, "money_agent": money_agent}

TASK = "I have 300 USD. Find me a Lisbon hotel under 100 EUR a night and tell me if I need an umbrella there."

if __name__ == "__main__":
    print("MULTI-AGENT")
    answer = tool_loop("You are a trip planner. Split the request, delegate each part to a specialist, "
                       "then combine their reports into one short answer. The specialists cannot see "
                       "the user's message, so every task you send must repeat all the details it needs.",
                       TASK, ORCHESTRATOR_TOOLS, ORCHESTRATOR_FUNCTIONS, "orchestrator")
    print(answer, f"\n(model calls: {CALLS['count']})\n")

    CALLS["count"] = 0
    print("SINGLE AGENT")
    answer = tool_loop("You are a trip helper. Use tools for facts. Be brief.", TASK, TOOLS, FUNCTIONS, "single")
    print(answer, f"\n(model calls: {CALLS['count']})")

Walk through the parts:

  • tool_loop is the agent loop, written once and reused by every agent. It takes a system prompt, a task, a tool list and a function map. A label is printed with each tool call so you can see which agent made it.
  • pick builds a worker's tool list and function map from the shared trip_tools. run_tool from lesson 4 accepts a functions argument, so a worker can only run the functions it was given, even if the model asks for another.
  • weather_agent and money_agent each run tool_loop with their own prompt and tools, and return {"report": ...}.
  • ORCHESTRATOR_TOOLS describes each worker as a function with one task string argument.
  • CALLS counts every model call, so the two designs can be compared on cost.

The context problem: workers cannot see the user

The most important line in the file is in the orchestrator's system prompt: "The specialists cannot see the user's message, so every task you send must repeat all the details it needs."

Each worker starts with a brand new messages list. It knows only the task string the orchestrator wrote. If the orchestrator writes "hotel search", the worker has no idea which city or budget.

That exact failure happened in the first test run. The orchestrator delegated {"task": "hotel search"} to the money agent, which then searched for hotels in "New York, NY" with a budget of 150 EUR, details it made up. The final answer mixed a correct Lisbon weather report with a failed New York hotel search.

Two changes fixed it:

  1. The orchestrator's system prompt now says workers cannot see the user's message.
  2. Each worker's task parameter has a description with a complete example, such as "Find hotels in Lisbon under 100 EUR a night".

This is the central cost of multi-agent designs: every handoff is a chance to lose information. A single agent has the whole conversation in one list and never has this problem.

Animation: A vague task sent the money agent to New York. A task that carried the city and budget found Casa Azul at 95 EUR.

A second failure: the wrong argument type

In the next test run, the orchestrator sent task as a JSON object, for example {"city": "Lisbon", "type": "will_rain"}, even though the schema says it is a string. The worker passed that object on as message content, the server rejected the request, and run_tool turned the exception into an error result. The orchestrator then told the user something went wrong.

The fix is as_text: if task is not a string, convert it to JSON text before handing it to the worker. The object usually contains the needed details anyway, so the worker can still do its job. This is the same "fix predictable mistakes in code" rule from lesson 4.

What happened in the final run

With both fixes, running python multi_agent.py with qwen2.5:1.5b on Ollama:

Multi-agent:

  • The orchestrator delegated to the money agent with a task object that included "Find hotels in Lisbon under 100 EUR a night". The money agent called search_hotels for Lisbon under 100 EUR and found Casa Azul at 95 EUR.
  • It delegated to the weather agent with "Will it rain in Lisbon?". The weather agent called get_weather, and its report began with the contradictory "Yes, it will not rain in Lisbon", followed by the correct forecast.
  • The orchestrator's final answer named Casa Azul at 95 EUR and said it will not rain, with the 10% chance. That answer is correct.
  • It never converted the 300 USD, which the single agent did. The task does not strictly need it, but it shows the orchestrator dropped part of the request.
  • Total: 6 model calls.

Single agent:

  • It called convert_currency, search_hotels and get_weather with correct arguments, in 2 model calls (it asked for all three tools in one turn).
  • Its answer had the right hotel and the right forecast, but opened with "You need an umbrella in Lisbon" next to a 10% chance of rain.

So in this run, the multi-agent version gave the better final answer, and it cost three times as many model calls. On another run, or another model, the result could flip. One run of each is an example, not a measurement; the eval harness in lesson 14 is how you would compare them properly.

When multiple agents help

Based on the patterns in Anthropic's guide and the trade offs above, splitting into workers tends to pay off when:

  • The tool set is large and falls into clear groups, so each worker has a short, focused list.
  • Parts of the task are independent and can run in parallel. The orchestrator above calls workers one at a time, but independent workers could run concurrently.
  • Workers need different instructions or models, for example a careful model for bookings and a cheap one for lookups.
  • You want hard boundaries. A worker that cannot see the booking tool cannot book, whatever the orchestrator says. That is a safety property, similar to the allowlist in lesson 6.

When one agent is better

  • Small tool sets. Three tools do not need three agents. The single agent here used a third of the calls.
  • Tasks where context matters across parts. If the hotel choice depends on the weather, a single agent sees both. Workers only see what they are told.
  • Tight budgets. Every worker is a full agent loop with its own calls and its own system prompt and tool definitions in every request.
  • Debugging. One trace is easier to follow than a tree of them. If you build multi-agent systems, the tracing in lesson 15 becomes essential.

A good default is to start with one agent, measure where it fails, and split only the part that needs it.

Common mistakes

  • Vague handoffs. Workers start blank. Spell out the details or pass the relevant context explicitly.
  • Trusting the orchestrator's arguments. Handle wrong types, missing fields and empty tasks in code.
  • No overall budget. Each worker has a step limit, but the whole tree needs one too. Share a Budget from lesson 11 across all agents.
  • Workers with all the tools. That throws away the main benefit. Scope each worker's tools.
  • Splitting by default. Multi-agent is a tool for specific problems, not a sign of a more advanced agent.

What to try next

  • Make weather_agent and money_agent run in parallel with concurrent.futures.ThreadPoolExecutor when the orchestrator asks for both in one turn.
  • Remove the "specialists cannot see the user's message" sentence and rerun to see how the handoffs change.
  • Share one Budget from lesson 11 across the orchestrator and workers, and stop the whole run when it is exceeded.
  • Add a third worker, booking_agent, that holds book_hotel behind the approval step from lesson 6, so only that worker can book.

Module 4 is done: your agent can plan, stop, retry safely and delegate. Module 5 is about shipping it: connecting to tools over MCP, testing it, and tracing it.

Sources

Try it yourselfEasy

Send each task to the right specialist agent

In a multi-agent setup an orchestrator hands each task to a worker with a short tool list. A simple router matches keywords.

Write route(task, workers).

- workers maps a worker name to a list of keywords, like {"weather": ["rain", "forecast"]}.
- Score each worker by how many of its keywords appear in the task as whole words, ignoring case.
- Return the name with the highest score. On a tie, return the name that comes first alphabetically. If every score is 0, return "generalist".

solution.py
Runs in your browser with Python and NumPy. No model or API key needed.

The worked solution unlocks after your first attempt.

Saved in this browser. Pass the quiz while signed in to count it for the certificate.

Check what you learned

Answer all 3 questions. You need at least 2 right to pass.

1. Why did the money agent search New York in the first run?

2. In the final run, how many model calls did multi-agent and single agent use?

3. When is a single agent usually the better choice?