Skip to content

05 · Research Squad

Two complementary multi-Agent patterns in one example. First, a coordinator calls a researcher's delegate tool for three independent factual lookups, requesting concurrent calls in one response. Then a second coordinator delegates arithmetic to a math_expert Agent. Both use Agent.as_tool() with explicitly constructed workers.

Migrating older examples

TaskConfig and the automatically injected run_subtask / run_subtasks tools are deprecated and will be removed in 1.4.0. This example uses explicit delegation.

What it covers#

  • Constructing workers with their own prompts, model configs, and tools.
  • Requesting multiple calls to a delegate in one model response for concurrent fan-out.
  • Wrapping an Agent with Agent.as_tool() to expose it as a named delegate (task_math-expert) on a parent's tool list.
  • Subscribing to TaskStarted / TaskCompleted lifecycle events to observe the fan-out from outside the Agent.

Primitives covered#

  • Explicit worker Agents exposed as tools for concurrent fan-out
  • Agent.as_tool(description=...) for sibling delegation
  • TaskStarted / TaskCompleted events on the stream
  • MemoryStream + stream.where(EventType).subscribe(...)

Source#

"""05 · Research squad — parallel subtasks and sibling delegation

Two patterns for multi-Agent orchestration:

1. **Concurrent delegation.** The coordinator requests three calls to
   ``task_researcher`` in one model response. Each call runs the explicit
   researcher Agent on its own fresh stream. The researcher has no tools,
   so it cannot delegate further.

2. **``Agent.as_tool()``.** A second Agent (``math_expert``) is exposed to
   the coordinator as a callable tool. The wrapped Agent has no tools,
   so it cannot delegate further.

Run::

    .venv/bin/python 05_research_squad.py
"""

import asyncio
import time

from ag2 import Agent
from ag2.config import GeminiConfig
from ag2.events import TaskCompleted, TaskStarted
from ag2.stream import MemoryStream

def section(title: str) -> None:
    print(f"\n── {title} ───")

async def main() -> None:
    config = GeminiConfig(model="gemini-3.6-flash", temperature=0)

    section("Parallel subtasks — fan out three lookups through a delegate")

    researcher = Agent(
        "researcher",
        prompt="Answer the factual lookup concisely. Return only the result.",
        config=config,
    )

    coordinator = Agent(
        "coordinator",
        prompt=(
            "You answer multi-part questions by calling task_researcher. "
            "Issue a separate call for each sub-question in one response "
            "so the lookups run concurrently. Then combine the results. Be concise."
        ),
        config=config,
        tools=[researcher.as_tool(description="Answer an independent factual lookup.")],
    )

    # Collect subtask lifecycle events so we can show the fan-out to the user
    starts: list[TaskStarted] = []
    completions: list[TaskCompleted] = []
    stream = MemoryStream()
    stream.where(TaskStarted).subscribe(lambda e: starts.append(e))
    stream.where(TaskCompleted).subscribe(lambda e: completions.append(e))

    start = time.monotonic()
    reply = await coordinator.ask(
        "Call task_researcher three times in one response to answer: "
        "(a) what is the tallest waterfall in the world, "
        "(b) what year was the Eiffel Tower completed, "
        "(c) what is the boiling point of nitrogen in Celsius. "
        "Then list all three answers.",
        stream=stream,
    )
    elapsed = time.monotonic() - start

    print(reply.body)
    print()
    print(f"Subtasks dispatched: {len(starts)}")
    print(f"Subtasks finished:   {len(completions)}")
    print(f"Wall time:           {elapsed:.2f}s")

    section("Sibling delegation — math_expert is a tool on coordinator2")

    math_expert = Agent(
        "math-expert",
        prompt="You are an arithmetic specialist. Reply with only the number.",
        config=config,
    )

    coordinator2 = Agent(
        "coordinator2",
        prompt=(
            "When arithmetic comes up, delegate to the task_math-expert tool "
            "rather than computing yourself. Then present the answer in a "
            "complete sentence."
        ),
        config=config,
        tools=[
            math_expert.as_tool(
                description="Delegate arithmetic problems to the math expert.",
            )
        ],
    )

    reply2 = await coordinator2.ask("What is 237 times 19?")
    print(reply2.body)

if __name__ == "__main__":
    asyncio.run(main())