Skip to content

Subagents

Subagents let agents delegate work to other agents through tool calling. The calling agent's LLM decides when and what to delegate, and each sub-task runs on its own isolated stream with independent history.

Why Use Subagents#

Breaking work across multiple agents gives you:

  • Separation of concerns — each agent has a focused prompt, tools, and config tuned for its role.
  • Independent context — sub-tasks run on fresh streams, so history doesn't grow unboundedly.
  • LLM-driven orchestration — the calling agent decides when to delegate, what context to pass, and how to use the result.

Note

When the LLM returns multiple tool calls in a single response, the framework dispatches them concurrently. Plain variables are deep-copied for each branch; explicitly shared variables remain visible across the tree. See Variable Scopes Across Subagents for ownership and synchronization rules.

TaskConfig is deprecated

TaskConfig, Agent(tasks=...), Agent.tasks, and the automatically injected run_subtask / run_subtasks tools will be removed in 1.4.0. Existing code continues to work with deprecation warnings. Use Agent.as_tool() for new code and follow the migration guide below.

Subagents API#

Use Agent.as_tool() to make one agent available as a tool for another.

from ag2 import Agent
from ag2.config import AnthropicConfig

config = AnthropicConfig("claude-sonnet-5")

researcher = Agent(
    "researcher",
    prompt="You are a thorough researcher. Provide concise factual findings.",
    config=config,
    tools=[search_tool],
)

writer = Agent(
    "writer",
    prompt="You are a skilled writer. Turn research into clear prose.",
    config=config,
)

coordinator = Agent(
    "coordinator",
    prompt="First delegate research, then pass findings to the writer.",
    config=config,
    tools=[
        researcher.as_tool(description="Research a topic and return findings."),
        writer.as_tool(description="Write an article. Pass research notes in the context parameter."),
    ],
)

reply = await coordinator.ask("Write a short article about the history of Python.")
print(await reply.content())

The coordinator's LLM sees two tools — task_researcher and task_writer — and calls them as needed. Each call spawns the target agent on a fresh stream, runs it to completion, and returns the result.

The calling agent's LLM sees a tool named task_{agent.name} with objective (required) and context (optional) parameters.

The context tool parameter is how the calling LLM shares relevant information with the sub-task:

1
2
3
4
task_writer(
    objective="Write an article about Python's history",
    context="Key findings: Created by Guido van Rossum in 1991. Named after Monty Python."
)

as_tool() accepts these parameters:

Parameter Type Description
description str Tool description shown to the LLM (required)
name str | None Override the default task_{agent.name} tool name
stream StreamFactory | None Factory to create custom streams for sub-tasks (see Sub-Task Streams)
middleware Iterable[ToolMiddleware] Tool middleware applied to the delegate tool (e.g., approval_required)

You can also use subagent_tool() directly for more control:

1
2
3
4
5
6
7
8
9
from ag2.tools.subagents import subagent_tool

coordinator = Agent(
    "coordinator",
    config=config,
    tools=[
        subagent_tool(researcher, description="Research a topic."),
    ],
)

Observe and Address Subagents#

Register an observer on the parent to observe its entire delegation subtree, including grandchildren and transient chunks. Operational events arrive as ChildEvent observations; UsageEvent and task lifecycle events arrive as themselves with delegation provenance. Observation does not execute a child's tools or model requests in the parent.

An observed event's live event.origin addresses the invocation that authored it. Use await event.origin.send(event_to_deliver) to send an event back through that invocation's normal handlers. Handles expire when the invocation ends and are unavailable when reading saved history.

See Observe a Delegation Tree for event types, filtering, and source accounting, and Reply to an Event's Author for a runnable addressed-delivery example.

Delegation Lifecycle#

Each delegation uses the same task lifecycle as an opted-in ask() or run(): one TaskStarted and one terminal event for that invocation. TaskCancelled identifies cancellation; TaskFailed identifies an execution error. The start carries a TaskSpec and the parent tool-call ID. Ancestors receive task events with the original delegation path, alongside source UsageEvent records.

Lifecycle is automatic for delegates. A capability-tagged parent run has its own lifecycle in addition to each child's, with a distinct task ID. TaskCompleted.usage is a cumulative stream snapshot for inspection; accounting reads source usage records rather than summing these snapshots.

Migrating from TaskConfig#

Create a worker explicitly, then add its delegate tool to the parent's tools list. This replaces tasks=TaskConfig(...) without adding a new configuration API:

from ag2 import Agent
from ag2.config import OpenAICompletionsConfig

worker = Agent(
    "worker",
    prompt="Complete the assigned task concisely. Return only the result.",
    config=OpenAICompletionsConfig(model="gpt-4o-mini"),
)
coordinator = Agent(
    "coordinator",
    prompt="Delegate independent work to task_worker, then combine the results.",
    config=OpenAICompletionsConfig(model="gpt-4o-mini"),
    tools=[worker.as_tool(description="Complete a focused sub-task.")],
)

reply = await coordinator.ask("Compare Python and Rust for web APIs.")
print(reply.body)

Map each TaskConfig field onto the worker explicitly. Some of its defaults were implicit, so check each one:

TaskConfig Explicit worker
config=None (the subtask used the parent's config) Pass the parent's config to the worker: config= is not inherited.
prompt (default: "You are a task agent. Complete the assigned task thoroughly and concisely. Return only the result.") Set the worker's prompt=; there is no default task prompt.
Parent tools, filtered by include_tools / exclude_tools List the tools in the worker's tools=. The list is fixed when the worker is built: tools added to the parent later with add_tool are not picked up.
extra_tools Add them to the worker's tools=.
max_concurrency See Limiting concurrency below.

Omit tasks= from the parent and update prompts that mention run_subtask or run_subtasks to use the delegate's tool name (task_worker above) and its objective / context parameters.

A few behaviours differ:

  • One worker, many calls. run_subtask built a fresh Agent per call; a delegate reuses the same worker Agent. Each call still runs on a fresh stream, so history does not leak between calls. Don't use a persistent or shared stream for a worker meant to run in parallel — calls on one stream run one turn at a time.
  • Fan-out is up to the model. run_subtasks dispatched the whole batch from a single tool call when parallel execution was enabled. With delegates, the calling LLM requests several calls in one response and the framework runs them concurrently; prompt for it explicitly. Where order matters, have the LLM call the delegate one step at a time.
  • No built-in recursion guard. Subtasks could never spawn subtasks. A worker can delegate only through the tools you give it, so keep delegate tools off the worker (avoid self-delegation here).
  • Workers composed per task. If you relied on run_subtask to spin up a generic worker for arbitrary work, dynamic_agent() is the closer fit: the LLM composes a focused worker per objective, and spawned workers cannot spawn further.

TaskStarted, TaskCompleted and TaskFailed lifecycle events, HITL bridging, and forwarding of source UsageEvent records work with delegates.

Limiting concurrency#

as_tool() has no max_concurrency parameter. To cap how many delegate calls run at once, pass the same tool middleware to every delegate that shares the cap:

import asyncio

from ag2 import Agent
from ag2.middleware import ToolMiddleware

def concurrency_limit(limit: int) -> ToolMiddleware:
    slots = asyncio.Semaphore(limit)

    async def limited(call_next, event, context):
        async with slots:
            return await call_next(event, context)

    return limited

limit = concurrency_limit(3)
coordinator = Agent(
    "coordinator",
    tools=[
        researcher.as_tool(description="Research a question.", middleware=[limit]),
        writer.as_tool(description="Draft a section.", middleware=[limit]),
    ],
)

Use a function, not a middleware object

Tool middleware is deep-copied when its tool is registered. A callable object holding the semaphore is copied once per delegate, so each delegate silently gets its own cap. A function and its closure are not copied, so every delegate shares one semaphore. Create the limiter inside the event loop that runs the agent; an asyncio.Semaphore must not be shared across loops.

Deprecation warnings#

Agent(tasks=TaskConfig(...)) emits one DeprecationWarning pointing at the line that builds the Agent. Constructing, copying or pickling a TaskConfig doesn't warn at runtime, but type checkers flag every use of the class. Reading Agent.tasks and leaving tasks disabled emit no warning.

Background Subagents#

as_tool() and subagent_tool() are blocking: the tool call doesn't return until the sub-task finishes, so the calling LLM waits for the result before doing anything else. background_agent_tool() is fire-and-forget — it starts the sub-task, returns a task id immediately, and lets the parent LLM keep working in the same turn. The result is delivered later as a follow-up message to the parent.

from ag2.tools.subagents import background_agent_tool

coordinator = Agent(
    "coordinator",
    prompt="Kick off long-running research in the background, then keep helping the user.",
    config=config,
    tools=[
        background_agent_tool(researcher, description="Research a topic in the background."),
    ],
)

reply = await coordinator.ask("Start deep research on Rust async runtimes, then outline the article.")

The calling LLM sees a tool named background_task_{agent.name} with the same objective (required) and context (optional) parameters as as_tool(). Calling it returns "Background task started: {task_id}" right away, so the LLM can issue other tool calls or continue reasoning while the sub-task runs.

How it behaves:

  • The sub-task runs concurrently via run_task on its own stream (a fresh MemoryStream by default, or one built by the stream factory).
  • The parent Agent.ask loop keeps running and will not return until the background task finishes. Once it does, its result is pushed back into the parent's inbox as a follow-up turn (via context.enqueue), so the parent LLM can react to it.
  • On success the follow-up message reports the task result; on failure it reports the error — the exception does not propagate to the parent.

background_agent_tool() accepts these parameters:

Parameter Type Description
agent Agent The agent to run as a background sub-task (positional)
description str Tool description shown to the LLM (required)
name str | None Override the default background_task_{agent.name} tool name
stream StreamFactory | None Factory to create custom streams for sub-tasks (see Sub-Task Streams)
middleware Iterable[ToolMiddleware] Tool middleware applied to the delegate tool (e.g., approval_required)

Note

Background sub-tasks are for work the parent can fire off and revisit later within the same turn — the ask call still awaits their completion before returning. They are not detached jobs that outlive the turn.

Self-Delegation#

An agent can delegate to itself to break complex work into independent sub-tasks. Each sub-task runs as a fresh copy of the agent with its own stream and history.

analyst = Agent(
    "analyst",
    prompt=(
        "You have search and sub_task tools. "
        "Only use sub_task when the task has clearly independent parts. "
        "Otherwise handle it directly with search."
    ),
    config=config,
    tools=[search_tool],
)

analyst.add_tool(
    analyst.as_tool(
        description="Break work into a focused sub-task for independent analysis.",
        name="sub_task",
    )
)

reply = await analyst.ask("Compare Python vs Rust for web APIs: performance, DX, and ecosystem.")

The analyst's LLM may call sub_task multiple times — one per aspect — then synthesise the results.

Dynamic Agents#

dynamic_agent() lets the calling LLM construct an ephemeral agent at runtime — picking a name, system prompt, and a subset of available tools per objective — instead of pre-defining each delegate as a named as_tool(). Use it when the orchestrator should compose a focused worker on demand for each sub-task.

from ag2 import Agent
from ag2.tools.dynamic import dynamic_agent
from ag2.config import OpenAICompletionsConfig

config = OpenAICompletionsConfig(model="gpt-4o-mini")

orchestrator = Agent(
    "orchestrator",
    config=config,
    prompt=(
        "You orchestrate sub-tasks by calling create_and_run_agent. "
        "For each task, invent a focused agent name and system prompt, "
        "include only the tools the child genuinely needs, "
        "and pass a clear objective."
    ),
    tools=[
        dynamic_agent(available_tools=[calc, web_search], config=config),
    ],
)

reply = await orchestrator.ask("What is 17 * 25 + 4? Use a child agent.")

The orchestrator's LLM sees one tool, create_and_run_agent(spec, objective). Each call spawns an ephemeral child Agent on a fresh stream, runs the objective via run_task, and returns the reply string.

dynamic_agent() accepts these parameters:

Parameter Type Description
available_tools Iterable[Tool | Callable[..., Any]] Pool of tools the spawned child may pick from by name
config ModelConfig Model configuration used for every spawned child
middleware Iterable[ToolMiddleware] Tool middleware applied to create_and_run_agent

The AgentSpec the LLM constructs#

The LLM builds an AgentSpec on every call. It is JSON-serializable and captures the declarative parts of the child:

Field Type Purpose
name str Display name of the spawned child
prompt list[str] System prompt for the child
tool_names list[str] Subset of available_tools names to give the child
response_schema ResponseSchemaSpec | None Optional structured output schema

Unrecognised keys are ignored, as Pydantic would anyway, but they raise an UnknownSpecFieldWarning naming the key and suggesting the closest valid field — so a misspelled tool_nammes no longer silently produces a child with no tools. To make it fatal, promote the warning:

1
2
3
4
import warnings
from ag2.spec import UnknownSpecFieldWarning

warnings.simplefilter("error", UnknownSpecFieldWarning)

How the LLM discovers available tool names#

The pool's names and descriptions are rendered into the create_and_run_agent tool description automatically when the factory is built. The calling agent's system prompt does not need to enumerate them — the LLM discovers the valid names from the tool schema.

Tip

If the LLM picks a name not in the pool, the framework returns Error: unknown tools [...]. Available: [...] as a recoverable string. The LLM reads the hint and retries with a corrected spec — no exception propagates to the caller. The auto-rendered menu prevents this in the common case.

Warning

Spawned children are themselves constructed without dynamic_agent, so they cannot recursively spawn further dynamic agents. Recursion is structurally impossible — no depth limit needed.

Sub-Task Streams#

Default Behavior#

By default, each sub-task creates a fresh MemoryStream. The sub-task's history is isolated — it doesn't carry over between invocations.

It means that subagent has no information about previous calls or results. It just sees the current call and the context.

What Behavior Why
Dependencies Shallow-copied; the parent's configuration fills only keys the sub-agent doesn't set Replacing a mapping entry stays in the child, but referenced objects remain shared. Values passed to ask(dependencies=...) or set at runtime override the sub-agent's own; the parent's constructor and plugin defaults don't (e.g. the sub-agent's KnowledgePlugin store wins over the parent's)
Variables Plain / copied values are deep-copied, local values are excluded, and root-declared shared bindings remain shared Scope declarations control visibility. Reserved ag: / a2a: keys, including approval_required "always" answers, are not inherited
History Fresh stream Clean context — the LLM passes relevant info via context parameter
Agent prompt, tools, config Supplied by the worker Agent Nothing is inherited from the parent; construct each worker with its own capabilities

Persistent Stream#

persistent_stream() gives the same agent a consistent stream across multiple invocations within a context. The sub-task's history accumulates across calls rather than starting fresh each time:

1
2
3
4
5
6
from ag2.tools.subagents import persistent_stream

researcher.as_tool(
    description="Research a topic",
    stream=persistent_stream(),
)

It stores the stream ID in context.dependencies keyed by f"ag:{agent.name}:stream" and reuses the parent stream's storage backend. This is useful when the sub-agent benefits from seeing its own prior work — for example, a researcher that should avoid repeating searches.

Shared Stream Instance#

Pass a Stream instance directly to keep a handle on the sub-agent's events. Every delegation runs against that same stream, so you can read its history — or subscribe to it — from the calling code:

from ag2 import MemoryStream

sub_stream = MemoryStream()

researcher.as_tool(
    description="Research a topic",
    stream=sub_stream,
)

# after the run
events = await sub_stream.history.get_events()

Warning

Reusing one stream also makes the sub-agent stateful: because the history is shared, each delegation sees every earlier delegation's turns, and token cost grows with them. This is the same trade-off as persistent_stream(). To observe events without accumulating child conversation history, register observers on the parent and keep the default fresh stream per call.

Unlike persistent_stream(), an instance you construct yourself carries its own storage backend unless you pass the parent's — MemoryStream(storage=parent_stream.history.storage).

Custom Factory#

For full control, pass any callable matching StreamFactory = Callable[[Agent, Context], Stream]:

from ag2 import Agent, Context
from ag2.streams.redis import RedisStream

def make_redis_stream(agent: Agent, ctx: Context) -> RedisStream:
    return RedisStream(MY_REDIS_URL, prefix=f"ag2:sub:{agent.name}")

researcher.as_tool(
    description="Research a topic",
    stream=make_redis_stream,
)

Note

stream= accepts exactly these three shapes — None, a Stream instance, or a factory. Anything else raises TypeError when the tool is built, not when it first runs. Passing the class (stream=MemoryStream) instead of an instance (stream=MemoryStream()) is rejected the same way. The same rules apply to background_agent_tool().